zoukankan      html  css  js  c++  java
  • 264. 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.

    Hint:

    1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
    2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
    3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
    4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).

    答案:

    找出第n个丑陋数,排除依次判断是否为丑陋数的做法,根据题目的提示,可以以2,3,5为基准数,分为三个数列,每次从三个数列中取一个数字,选出最小的那个。

    实现代码如下:

     

     1 class Solution {
     2 public:
     3     int nthUglyNumber(int n) {
     4         int arr[n];
     5         arr[0]=1;
     6         int num2=2,num3=3,num5=5;
     7         int count2=0,count3=0,count5=0;
     8         for(int i=1;i<n;i++){
     9             arr[i]=getMin(num2,num3,num5);
    10             if(arr[i]==num2){
    11                 num2=2*arr[++count2];
    12             }
    13             if(arr[i]==num3){
    14                 num3=3*arr[++count3];
    15             }
    16             if(arr[i]==num5){
    17                 num5=5*arr[++count5];
    18             }
    19         }
    20         return arr[n-1];
    21     }
    22     int getMin(int a,int b,int c){
    23         int minNum=(a<=b?a:b);
    24         minNum=(minNum<=c?minNum:c);
    25         return minNum;
    26     }
    27 };

     

    注意:第11,14,17行的加号是在count前面的,先加再取数

     

  • 相关阅读:
    CGLib实现不同类中同名不同类型属性复制
    stream 伪复用实现
    年终盘点 | 2020年,国内私有云正式进入3.0时代
    高危端口135,137,138,139,445,1025,2475,3127,6129,3389,593
    在jsp引入js失败,提示404
    安全漏洞扫描
    Go 实现的文件行数统计工具
    .NET Core 获取域名 DNS 解析记录
    .NET Core 操作 Windows 注册表
    .NET MongoDb BsonDocument 序列化
  • 原文地址:https://www.cnblogs.com/Reindeer/p/5727361.html
Copyright © 2011-2022 走看看