zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    js 变量的声明能提升 初始化不会提升
    老公教我写分页
    响应式布局
    闭包优缺点
    正则表达式验证邮箱格式
    DDL表和库管理语言
    DML数据库操作语言
    python实现求第K小
    硬币凑数
    MySQL学习的表单定义
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4749451.html
Copyright © 2011-2022 走看看