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) { if(n==1||n==2||n==3) return n; int count=3; int i=4; for(;count<n;i++) { int c=i; while(c%2==0) c=c/2; while(c%3==0) c=c/3; while(c%5==0) c=c/5; if(c==1) count++; } return i-1; } }
方法二:(借鉴的别人的方法)
1 public class Solution { 2 public int nthUglyNumber(int n) { 3 if(n<=1) 4 return 1; 5 List<Integer> list1=new ArrayList<>(); 6 List<Integer> list2=new ArrayList<>(); 7 List<Integer> list3=new ArrayList<>(); 8 list1.add(1); 9 list2.add(1); 10 list3.add(1); 11 12 int min=0; 13 for(int i=1;i<=n;i++) 14 { 15 min=Math.min(Math.min(list1.get(0),list2.get(0)),list3.get(0)); 16 if(list1.get(0)==min) list1.remove(0); 17 if(list2.get(0)==min) list2.remove(0); 18 if(list3.get(0)==min) list3.remove(0); 19 list1.add(min*2); 20 list2.add(min*3); 21 list3.add(min*5); 22 } 23 return min; 24 25 } 26 27 }
浙公网安备 33010602011771号