264. Ugly Number II

原题链接:https://leetcode.com/problems/ugly-number-ii/description/
《剑指Offer》上面的原题,我已经看过解答了,就不废话了:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.nthUglyNumber(1300));
        System.out.println(s.nthUglyNumber1(1300));
    }

    /**
     * 方法二:以空间换时间
     * 
     * @param n
     * @return
     */
    public int nthUglyNumber(int n) {
        if (n < 1) {
            return 0;
        }

        int[] arr = new int[n];
        arr[0] = 1;

        int doublePoint = 0;
        int triplePoint = 0;
        int pentaPoint = 0;

        int i = 1;
        while (i < n) {
            int doublePointNum = arr[doublePoint] * 2;
            int triplePointNum = arr[triplePoint] * 3;
            int pentaPointNum = arr[pentaPoint] * 5;

            if (doublePointNum <= triplePointNum && doublePointNum <= pentaPointNum) {
                if (doublePointNum > arr[i - 1]) {
                    arr[i++] = doublePointNum;
                    doublePoint++;
                } else {
                    doublePoint++;
                }
            } else if (triplePointNum <= doublePointNum && triplePointNum <= pentaPointNum) {
                if (triplePointNum > arr[i - 1]) {
                    arr[i++] = triplePointNum;
                    triplePoint++;
                } else {
                    triplePoint++;
                }
            } else {
                if (pentaPointNum > arr[i - 1]) {
                    arr[i++] = pentaPointNum;
                    pentaPoint++;
                } else {
                    pentaPoint++;
                }
            }
        }

        return arr[n - 1];
    }

    /**
     * 方法一:这种方法简单粗暴,空间复杂度较低,但是耗时较长,正如《剑指Offer》里面所说,它超时了
     *
     * Submission Result: Time Limit Exceeded
     *
     * @param n
     * @return
     */
    public int nthUglyNumber1(int n) {
        int start = 0;
        int count = 0;
        while (count < n) {
            start++;
            if (isUgly(start)) {
                count++;
            }
        }
        return start;
    }

    public boolean isUgly(int num) {
        if (num < 1) {
            return false;
        }
        while (num % 2 == 0) {
            num /= 2;
        }
        while (num % 3 == 0) {
            num /= 3;
        }
        while (num % 5 == 0) {
            num /= 5;
        }
        return num == 1;
    }

}
posted @ 2018-04-06 18:16  optor  阅读(131)  评论(0编辑  收藏  举报