Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 1.65 KB

264. Ugly Number II.md

File metadata and controls

51 lines (39 loc) · 1.65 KB

264. Ugly Number II

Problem

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).

Solution

暴力求解

直观的做法是对整数进行遍历,逐步判断每个数是否是丑数

动态规划

丑数序列可以拆为以下子列表: 1x2,2x2,3x2,4x2...nextUgly2... 1x3,2x3,3x3,4x3...nextUgly3... 1x5,2x5,3x5,4x5...nextUgly*5... 采用合并有序链表的方法,从三个子列表中逐步获取最小的丑数。

    public int nthUglyNumber(int n) {
    	List<Integer> ugly = new ArrayList<Integer>(n);
    	ugly.add(1);
    	int p2 = 0, p3=0, p5=0;
    	while (ugly.size()<n) {
    		int min = min(ugly.get(p2)*2, ugly.get(p3)*3, ugly.get(p5)*5);
    		if(min==ugly.get(p2)*2) p2+=1;
    		if(min==ugly.get(p3)*3) p3+=1;
    		if(min==ugly.get(p5)*5) p5+=1;
    		ugly.add(min);
    	}
    	return ugly.get(n-1);
    }
    
    int min(int a, int b, int c) {
    	int min = Math.min(a, b);
    	min = Math.min(min, c);
    	return min;
    }