死磕算法系列文章
“Leetcode : https://leetcode-cn.com/problems/chou-shu-lcof/
“GitHub : https://github.com/nateshao/leetcode/blob/main/algo-notes/src/main/java/com/nateshao/sword_offer/topic_36_nthUglyNumber/Solution.java
“题目描述 :我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。 难度:中等
示例 :
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
思路:
“丑数的递推性质:丑数只包含因子2,3,5, 因此有“丑数=某较小丑数x洇子”(例如: 10=5x2)。
设已知长度为n的丑数序列 x_1,x_2,... ,x_n ,求第n+1个丑数 x_{n+1} 。根根据递推性质,丑数xn+1只可能 是以下三种情况其中之一 (索引a, b,c为未知数) :
丑数递推公式:若索引a, b,c满足以上条件,则下个丑数x_{n+1} 为以下三种情况中的最小值;X_{n+1} = min(x_a * 2,x_b * 3,x_c * 5) 于 x_{n+1} 是最接近xn的丑数,因此索引a, b,c需满足以下条件:x_a*2 > x_n ≥ x_{a-1}*2 ,,即xa为首个乘以2后大于xn的丑数x_b*3 > x_n ≥ x_{b-1}*3 ,即xb为首个乘以3后大于xn的丑数x_c*2 > x_n ≥ x_{c-1}*5 , 即xc为首个乘以5后大于xn的丑数
因此,可设置指针a, b,c指向首个丑数(即1 ),循环根据递推公式得到下个丑数, 并每轮将对应指针执行 +1即可。
复杂度分析:
package com.nateshao.sword_offer.topic_36_nthUglyNumber;
/**
* @date Created by 邵桐杰 on 2021/12/11 22:54
* @微信公众号 程序员千羽
* @个人网站 www.nateshao.cn
* @博客 https://nateshao.gitee.io
* @GitHub https://github.com/nateshao
* @Gitee https://gitee.com/nateshao
* Description: 丑数
* 描述:我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
*/
public class Solution {
public static void main(String[] args) {
System.out.println("nthUglyNumber(10) = " + nthUglyNumber(10));//nthUglyNumber(10) = 12
System.out.println("nthUglyNumber2(10) = " + nthUglyNumber2(10));//nthUglyNumber2(10) = 12
}
/**
* 思路:乘 2 或 3 或 5,之后比较取最小值。
*
* @param n
* @return
*/
public static int nthUglyNumber(int n) {
if (n <= 0) return 0;
int[] arr = new int[n];
arr[0] = 1;// 第一个丑数为 1
int multiply2 = 0, multiply3 = 0, multiply5 = 0;
for (int i = 1; i < n; i++) {
int min = Math.min(arr[multiply2] * 2, Math.min(arr[multiply3]
* 3, arr[multiply5] * 5));
arr[i] = min;
if (arr[multiply2] * 2 == min) multiply2++;
if (arr[multiply3] * 3 == min) multiply3++;
if (arr[multiply5] * 5 == min) multiply5++;
}
return arr[n - 1];// 返回第 n 个丑数
}
/**
* 作者:Krahets
*
* @param n
* @return
*/
public static int nthUglyNumber2(int n) {
int a = 0, b = 0, c = 0;
int[] dp = new int[n];
dp[0] = 1;
for (int i = 1; i < n; i++) {
int n2 = dp[a] * 2, n3 = dp[b] * 3, n5 = dp[c] * 5;
dp[i] = Math.min(Math.min(n2, n3), n5);
if (dp[i] == n2) a++;
if (dp[i] == n3) b++;
if (dp[i] == n5) c++;
}
return dp[n - 1];
}
}
参考链接:https://leetcode-cn.com/problems/chou-shu-lcof/solution/mian-shi-ti-49-chou-shu-dong-tai-gui-hua-qing-xi-t/