您的位置:首页 > 其它

LeetCode: Ugly Number II

2015-08-19 16:04 183 查看
题目链接https://leetcode.com/problems/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.
题目意思:找第n个丑数

思路:按顺序省城丑数,当前要生成的丑数肯定是前面某一个丑数乘以2,3或5。但并不需要把当前每个丑数都乘以2,3和5,因为已生成的丑数在数组是按顺序存放的。对于乘以2而言,肯定存在某一个丑数t2,使得排在它之前的每一个丑数乘以2得到的结果都会小于已有最大丑数,在它之后的每个丑数乘以2得到的结果都会大于当前最大丑数。我们只需要记下这个丑数的位置,同时每次生成新的丑数时去更新这个t2。对于3和5,同样存在t3和t5。

AC代码

public class Solution {
    public int MinT(int t1, int t2, int t3) {
		int min = t1 < t2 ? t1 : t2;
		return min < t3 ? min : t3;
	}
	
	public int nthUglyNumber(int n) {
		int[] uglyNums = new int
;
		int next = 1;
		int i=0, j=0, k=0;			//分别记录t2,t3,t5当前位置
		uglyNums[0] = 1;
		
		while(next < n) {
			int min = MinT(uglyNums[i]*2, uglyNums[j]*3, uglyNums[k]*5);
			uglyNums[next] = min;
			
			if(uglyNums[i]*2 == min) i++;
			if(uglyNums[j]*3 == min) j++;
			if(uglyNums[k]*5 <= min) k++;
			next++;
		}
		
		return uglyNums[n-1];
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: