[Algorithm] 4. Ugly Number II

Description

Ugly number is a number that only havefactors 23 and 5.

Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

Example

If n=9, return 10.

Challenge

O(n log n) or O(n) time.

Notice

Note that 1 is typically treated as an ugly number.

Answer

 1     /**
 2      * @param n: An integer
 3      * @return: the nth prime number as description.
 4      */
 5     public int nthUglyNumber(int n) {
 6         // find out the nth ugly number.
 7         int checker,count=0;
 8         int num=1;
 9         
10         do{
11             checker = num;
12             
13             while( checker%2 == 0 ) checker /= 2;
14             while( checker%3 == 0 ) checker /= 3;
15             while( checker%5 == 0 ) checker /= 5;
16             if( checker==1 )
17             {
18                 count++;
19             }
20             if( count == n )
21             {
22                 return num;
23             }
24             
25             num++;
26         }while(true);
27     }

Better Solution

 1     /**
 2      * @param n: An integer
 3      * @return: the nth prime number as description.
 4      */
 5     int nthUglyNumber(int n) {
 6         // find out the nth ugly number.
 7         int* uglyNum = new int[n];
 8         int factor2=2, factor3=3, factor5=5;
 9         int index2=0, index3=0, index5=0;
10         
11         uglyNum[0]=1;
12         
13         for(int i=1; i<n; i++)
14         {
15             factor2 = uglyNum[index2]*2; factor3 = uglyNum[index3]*3; factor5 = uglyNum[index5]*5;
16             int minNum = min(factor2, min(factor3, factor5) );
17             uglyNum[i] = minNum;
18             if ( minNum == factor2 )    index2++;
19             if ( minNum == factor3 )    index3++;
20             if ( minNum == factor5 )    index5++;
21         }
22         
23         return uglyNum[n-1];        
24     }

Hints

  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are notugly. 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).
  (1) 1x2,  2x2, 2x2, 3x2, 3x24x2, 5x2...
  (2) 1x3,  1x3, 2x3, 2x3, 2x3, 3x3, 3x3...
  (3) 1x5,  1x5, 1x5, 1x5, 2x5, 2x5, 2x5...
 
posted @ 2018-11-08 15:52  jjlovezz  阅读(151)  评论(0编辑  收藏  举报