*LeetCode-Ugly Number II

记录三个指针 指向上一次被乘以 2 3 5 的地方分别 

  1. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
public class Solution {
    public int nthUglyNumber(int n) {
        if ( n == 0 )
            return 0;
        int pos2 = 0;
        int pos3 = 0;
        int pos5 = 0;
        int [] nums = new int [n];
        nums[0] = 1;
        for ( int i = 1; i < nums.length; i ++ ){
            nums [ i ] = Math.min(nums[pos2] * 2, Math.min( nums[pos3] * 3, nums[pos5] * 5));
            if ( nums[i] == nums[pos2] * 2)
                pos2 ++;
            if ( nums[i] == nums[pos3] * 3)
                pos3 ++;
            if ( nums[i] == nums[pos5] * 5)
                pos5 ++;
        }
        return nums[n-1];
    }
}

记住pos每次假如用了就要更新

你可能感兴趣的:(*LeetCode-Ugly Number II)