LeetCode 264. Ugly Number II

原题俩接在这里:https://leetcode.com/problems/ugly-number-ii/

题目:

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 first 10 ugly numbers.

Note:  

  1. 1 is typically treated as an ugly number.
  2. n does not exceed 1690.

题解:

找出第n个ugly number.

(1) 1×2, 2×2, 3×2, 4×2, 5×2, …
(2) 1×3, 2×3, 3×3, 4×3, 5×3, …
(3) 1×5, 2×5, 3×5, 4×5, 5×5, …

Let arr[i] denotes ith ugly number, it is choosen from previous ugly number * 2, * 3,  * 5.

Thus we need to maintain the index of previous * 2, * 3, * 5 positions. And move corresponding position when it is chosen. 

Note: when 2 numbers are the same, like arr[i2] = 3, arr[i3] = 2. arr[i2] * 2 == arr[i3] * 3. We need to move both i2 and i3. Since we don't want another 6.

Time Complexity: O(n). Space: O(n).

AC Java:

 1 class Solution {
 2     public int nthUglyNumber(int n) {
 3         int [] arr = new int[n];
 4         arr[0] = 1;
 5         int i2 = 0;
 6         int i3 = 0;
 7         int i5 = 0;
 8         
 9         int f2 = 2;
10         int f3 = 3;
11         int f5 = 5;
12         
13         for(int i = 1; i < n; i++){
14             arr[i] = Math.min(f2, Math.min(f3, f5));
15             if(arr[i] == f2){
16                 i2++;
17                 f2 = arr[i2] * 2;
18             }
19             
20             if(arr[i] == f3){
21                 i3++;
22                 f3 = arr[i3] * 3;
23             }
24             
25             if(arr[i] == f5){
26                 i5++;
27                 f5 = arr[i5] * 5;
28             }
29         }
30         
31         return arr[n - 1];
32     }
33 }

 

类似Ugly Number.

跟上Super Ugly Number.

posted @ 2015-09-15 06:21  Dylan_Java_NYC  阅读(275)  评论(0编辑  收藏  举报