Ugly number is anumber that only have factors 2, 3and5.
Design an algorithm to find the nth ugly number. The first10 ugly
numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Example
If n=9, return10.
Solution
import java.util.*;
public class Solution {
/**
* @param n: An integer
* @return: the nth prime number as description.
*/public int nthUglyNumber(int n) {
// write your code here
ArrayList<Integer>list=new ArrayList<>();
list.add(1);
int i=1;
//使用三个计数值,分别表示2,3,5的倍数的最小值的当前下标
int min=1,m2 =0,m3 =0,m5 =0;
while(i<=n){
i++;
min= Math.min(Math.min(list.get(m2)*2,list.get(m3)*3),list.get(m5)*5);
list.add(min);
if(min==list.get(m2)*2) m2++;
elseif(min==list.get(m3)*3) m3++;
else m5++;
//这里注意可能有重复值,需要去重while(list.get(m2)*2<=min) m2++;
while(list.get(m3)*3<=min) m3++;
while(list.get(m5)*5<=min) m5++;
}
returnlist.get(n-1);
}
}