[LeetCode]Ugly Number II

先吐槽一下这个题目,和他的名字一样丑陋。我真的不知道这个题对于一个程序员的考点在哪里,也不知道是不是在45分钟的面试中,第一次碰到这个题目想不出这个解法就能说明这个程序员不好? 感觉完全的奥数式题目

(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, …

public class Solution {
    public int nthUglyNumber(int n) {
        if (n == 1) {
            return 1;
        }
        int[] record = new int[n];
        record[0] = 1;
        int i = 0, j = 0, k = 0;
        int first = record[i] * 2;
        int second = record[j] * 3;
        int third = record[k] * 5;
        int result = 0;
        for (int t = 1; t < n; t++) {
            result = Math.min(first, Math.min(second, third));
            record[t] = result;
            if (result == first) {
                i ++;
                first = record[i] * 2;
            }
            if (result == second) {
                j ++;
                second = record[j] * 3;
            }
            if (result == third) {
                k ++;
                third = record[k] * 5;
            }
        }
        return result;
    }
}

 

posted @ 2015-11-26 16:10  Weizheng_Love_Coding  阅读(125)  评论(0)    收藏  举报