264. 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
. For example,1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.Note that
1
is typically treated as an ugly number, and n does not exceed 1690.题目大意:给定一个数字n,找出第n个丑数,丑数正能被2,3,5整除
思路:由于丑数的性质,每个数只能被2,3,5整除,所以有
(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, …可以看出,丑数序列,即丑数序列中的数乘以2,3,5。然后我们使用与合并排序类似的合并方法,从三个子序列中获取每个丑数。每一步我们选择最小的一个,然后移动一步,包括数值相同的数字。
代码
package DP; import java.util.Arrays; /** * @author OovEver * 2018/1/3 11:01 */ public class LeetCode264 { public static int nthUglyNumber(int n) { int[] ugly = new int[n]; int index2 = 0, index3 = 0, index5 = 0; int factor2 = 2, factor3 = 3, factor5 = 5; ugly[0] = 1; for(int i=1;i<n;i++) { int min = Math.min(factor2, Math.min(factor3, factor5)); ugly[i] = min; if (factor2 == min) { factor2 = 2 * ugly[++index2]; } if (factor3 == min) { factor3 = 3 * ugly[++index3]; } if (factor5 == min) { factor5 = 5 * ugly[++index5]; } } return ugly[n - 1]; } }