LeetCode--264--medium--UglyNumberII

package com.app.main.LeetCode.dynamic;

/**
 * 264
 *
 * medium
 *
 * 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 is typically treated as an ugly number.
 * n does not exceed 1690.
 *
 *
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2019/12/23
 * Time:下午6:13
 */
public class UglyNumberII {
    public int nthUglyNumber(int n) {
        int[] dp = new int[n];
        dp[0] = 1;
        int idx1 = 0;
        int idx2 = 0;
        int idx3 = 0;
        for (int i = 1 ; i < n; i++) {
            dp[i] = Math.min(Math.min(dp[idx1] * 2, dp[idx2] * 3), dp[idx3] * 5);
            if (dp[i] == dp[idx1] * 2) {
                idx1++;
            }
            if (dp[i] == dp[idx2] * 3) {
                idx2++;
            }
            if (dp[i] == dp[idx3] * 5) {
                idx3++;
            }
        }
        return dp[n - 1];
    }
}
发布了187 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/huangdingsheng/article/details/103914803