您的位置:首页 > 其它

[Leetcode] Ugly Number II

2015-10-14 11:18 447 查看
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.

public class Solution {
public int nthUglyNumber(int n) {
List<Integer> record = new ArrayList<>();
record.add(1);
int twoPosition = 0;
int threePosition = 0;
int fivePosition = 0;
while(record.size() < n){
int nextUglyNumber = Math.min(record.get(twoPosition)*2, Math.min(record.get(threePosition)*3, record.get(fivePosition)*5));
record.add(nextUglyNumber);

int lastElement = nextUglyNumber;
if( lastElement == record.get(twoPosition)*2)
twoPosition++;
if(lastElement == record.get(threePosition) * 3)
threePosition++;
if(lastElement == record.get(fivePosition) * 5)
fivePosition++;
}
return record.get(record.size()-1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: