第n个丑数

来源:互联网 发布:msn软件官方下载 编辑:程序博客网 时间:2024/05/22 04:47

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).
  5. 1到N的丑数为 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … ; 
    可以分成如下三组:

    <code class="hljs  has-numbering" style="display: block; padding: 0px; background-color: transparent; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; word-wrap: normal; background-position: initial initial; background-repeat: initial initial;">(1) 1×2, 2×2, 3×2, 4×2, 5×2, …(2) 1×3, 2×3, 3×3, 4×3, 5×3, …(3) 1×5, 2×5, 3×5, 4×5, 5×5, …</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; background-color: rgb(238, 238, 238); top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right;"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li><li style="box-sizing: border-box; padding: 0px 5px;">3</li></ul>

    只需要保证每次迭代的过程中选取最小的丑数(或者说是质因数),可以理解为后面的数字是前面的数组针对2,3,5的乘积。 
    C++可以AC的代码如下:

     //求三个数的最小值    int min(int a, int b, int c){        int minNum = a > b ? b : a;        return minNum > c ? c : minNum;    }    //求第N个丑数    int nthUglyNumber(int n) {        int *ugly = new int[n];        memset(ugly, 0, sizeof(int) * n);        ugly[0] = 1;        int factor2 = 2, factor3 = 3, factor5 = 5;        int index2, index3, index5;        index2 = index3 = index5 = 0;        for(int i=1; i<n; i++){            int minNum = min(factor2, factor3, factor5);            ugly[i] = minNum;            if(factor2 == minNum)                 factor2 = 2 * ugly[++index2];            if(factor3 == minNum)                 factor3 = 3 * ugly[++index3];            if(factor5 == minNum)                 factor5 = 5 * ugly[++index5];        }        return ugly[n-1];    }


0 0
原创粉丝点击