Leetcode 264. Ugly Number II-輸出前n個醜數(從小到大)
阿新 • • 發佈:2019-01-14
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
.
Example:
Input: n = 10 Output: 12 Explanation:1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.
Note:
1
n
does not exceed 1690.
方法1:
public class Leetcode_264_UglyNumberII { public static void main(String[] args) { Leetcode_264_UglyNumberII leetcode_264_uglyNumberII = new Leetcode_264_UglyNumberII(); System.out.println(leetcode_264_uglyNumberII.nthUglyNumber(11)); } /** * 1 乘以之前確定好的醜數才行,並不是單純的+2,+3,+5,因為14不是醜數 * 2 如果Min2 == Min3 < Min5 ,則取完最小值後,Min2,Min3都會增加,這樣是正確的,繼續看下一次哪個數最小 * @param n * @return */ //Runtime: 4 ms, faster than 76.19% of Java online submissions for Ugly Number II. public int nthUglyNumber(int n) { int[] ugly = new int[n]; int index2 = 0, index3 = 0, index5 = 0, min2 = 2, min3 = 3, min5 = 5; ugly[0] = 1; for (int i = 1; i < n; i++) { ugly[i] = Math.min(Math.min(min2, min3), min5); if (ugly[i] == min2) { min2 = 2 * ugly[++index2]; } if (ugly[i] == min3) { min3 = 3 * ugly[++index3]; } if (ugly[i] == min5) { min5 = 5 * ugly[++index5]; } } return ugly[n - 1]; } /** * 這是錯誤的方法 * @param n * @return */ public int nthUglyNumber2(int n) { int[] ugly =new int[n]; int index2=1,index3=1,index5=1,min2=2,min3=3,min5=5; ugly[0]=1; for(int i=1;i<n;i++){ ugly[i] =Math.min( Math.min(min2,min3),min5); if( ugly[i] == min2){ min2 +=2;// 12 +2 = 14 ,14並不是醜數,需要乘以之前確定的醜數才行 } if( ugly[i] == min3){ min3 +=3;//12 +3 = 15, } if( ugly[i] == min5){ min5 +=5; } } return ugly[n-1]; } }
O(n) Java solution
https://leetcode.com/problems/ugly-number-ii/discuss/69362/O(n)-Java-solution
就是比較*2,*3,*5哪個數是最小的,如果*2的數最小,則繼續使*2的數變大一次,下次再比較誰最小