您的位置:首页 > 其它

lintcode-medium-Ugly Number II

2016-04-07 06:13 423 查看
Ugly number is a number that only have factors
2
,
3
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...


Notice

Note that
1
is typically treated as an ugly number.

Example

If
n=9
, return
10
.

Challenge

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

class Solution {
/**
* @param n an integer
* @return the nth prime number as description.
*/
public int nthUglyNumber(int n) {
// Write your code here

if(n <= 0)
return 0;

ArrayList<Integer> res = new ArrayList<Integer>();
res.add(1);

int cur = 1;
int p1 = 0;
int p2 = 0;
int p3 = 0;

int min1 = 1;
int min2 = 1;
int min3 = 1;

while(res.size() < n){

while(res.get(p1) * 2 <= cur)
p1++;
min1 = res.get(p1) * 2;

while(res.get(p2) * 3 <= cur)
p2++;
min2 = res.get(p2) * 3;

while(res.get(p3) * 5 <= cur)
p3++;
min3 = res.get(p3) * 5;

int next = Math.min(min1, Math.min(min2, min3));

res.add(next);
cur = next;
}

return res.get(n - 1);
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: