您的位置:首页 > 其它

[LeetCode]263. Ugly Number&264. Ugly Number II

2016-09-16 21:16 253 查看
263 . Ugly Number

Easy

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

2ms:

public boolean isUgly(int num) {
if(num<=0)
return false;

while(num%2==0)
num /= 2;
while(num%3==0)
num /= 3;
while(num%5==0)
num /= 5;

return num==1;
}


264 . Ugly Number II

Medium

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.

72ms:

public int nthUglyNumber(int n) {
int ans = 0;
List<Integer> list1 = new LinkedList<Integer>();
List<Integer> list2 = new LinkedList<Integer>();
List<Integer> list3 = new LinkedList<Integer>();
list1.add(1);
list2.add(1);
list3.add(1);
for(int i = 0; i < n; i++){
ans = Math.min(Math.min(list1.get(0),list2.get(0)), list3.get(0));
if(ans == list1.get(0)) list1.remove(0);
if(ans == list2.get(0)) list2.remove(0);
if(ans == list3.get(0)) list3.remove(0);
list1.add(ans*2);
list2.add(ans*3);
list3.add(ans*5);
}
return ans;
}


13ms:

public int nthUglyNumber(int n) {
if (n <= 0)return 0;
int[] index = new int[3];
int[] uglyNumber = new int
;
uglyNumber[0] = 1;
int min_num = 1;
int i = 1;
while (n > 1) {
min_num = Math.min(2*uglyNumber[index[0]], Math.min(3*uglyNumber[index[1]], 5*uglyNumber[index[2]]));
uglyNumber[i] = min_num;
while(2*uglyNumber[index[0]]<=min_num) index[0]++;
while(3*uglyNumber[index[1]]<=min_num) index[1]++;
while(5*uglyNumber[index[2]]<=min_num) index[2]++;
i++;
n--;
}
return min_num;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode