• Ugly Number II


    Write a program to find the n-th ugly number.

    Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

    Note that 1 is typically treated as an ugly number.

    Analyse: We can divide the ugly numbers into three categories: 

    2:  1*2, 2*2, 3*2, 4*2, 5*2...

    3:  1*3, 2*3, 3*3, 4*3, 5*3...

    5:  1*5, 2*5, 3*5, 4*5, 5*5...

    So our job is to find the first n number in these three arrays. If we already find the i-th smallest number, the next number should be min(l1*2, l2*3, l3*5). The point is that we need to mark the current position of the three arrays, which means that the factor that we want to multiply is the smallest one in the result array. Thus, if the element in one array is selected, then we increase this index. 

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     int nthUglyNumber(int n) {
     4         if(n <= 1) return n;
     5         
     6         const int len = n;
     7         int ugly[n] = {1};
     8         int l1 = 0, l2 = 0, l3 = 0;//to represent the current location of the arrays respectively
     9         int f1 = 2, f2 = 3, f3 = 5;//to represent the current ugly factors
    10         
    11         for(int i = 1; i < n; i++){
    12             int least = min(min(f1, f2), f3);
    13             if(least == f1) {
    14                 ugly[i] = f1;
    15                 f1 = 2 * ugly[++l1];
    16             }
    17             if(least == f2){
    18                 ugly[i] = f2;
    19                 f2 = 3 * ugly[++l2];
    20             }
    21             if(least == f3){
    22                 ugly[i] = f3;
    23                 f3 = 5 * ugly[++l3];
    24             }
    25         }
    26         return ugly[n - 1];
    27     }
    28 };
  • 相关阅读:
    USB
    Google
    机型参数
    mac
    反编译
    xcode
    Ios 消息推送
    真机:特殊
    Android
    object-c
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4749451.html
Copyright © 2020-2023  润新知