思路
- 使用数组来存储丑数,第一个丑数为 1,后面的丑数都是在 1 基础上*2,*3,*5 得到的,下一个丑数一定是 1 分别乘 2、乘 3、乘 5 后得到的最小值;
- 首先我们对通过*2、*3、*5 得到的丑数进行分类,使用 r2、r3、r5 来记录它们对应丑数的下标,初始时肯定都指向第一个丑数 1,所以他们的初始值无一例外都为 0;
- 下面我们从下标 1 开始遍历,一直遍历到第 index 个丑数(对应下标为 index-1)
- 分别计算三类丑数,将最小值赋值给下一个丑数;(比如 2 3 5 选择 2)
- 选中的这个数满足 ug[ri]*i == ug[i] ,因为这个位置的丑数就是根据它计算出来的,然后我们递增它(指向它能够计算的下一个丑数);(比如之前 2 被选中了,我们增加 r2 ,相当于将 4 加入了,下一轮将从 3 4 5 中选择)
- 遍历结束,丑数切片最后一个位置(对应下标 index-1)就是我们要求的丑数了。
图示

代码
package main
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param index int整型
* @return int整型
*/
func GetUglyNumber_Solution( index int ) int {
// write code here
if index <= 6 {
return index
}
pUglyNumbers := make([]int, index)
pUglyNumbers[0] = 1
r2, r3, r5 := 0, 0, 0
for i := 1; i < index; i++ {
// 取 2 3 5 中的最小值 2
// 取 3 4 5 中的最小值 3
pUglyNumbers[i] = min(min(pUglyNumbers[r2]*2, pUglyNumbers[r3]*3), pUglyNumbers[r5]*5)
// 选中 2,加入 4
if pUglyNumbers[i] == pUglyNumbers[r2] * 2 {
r2++
}
// 选中 3,加入 6
if pUglyNumbers[i] == pUglyNumbers[r3] * 3 {
r3++
}
if pUglyNumbers[i] == pUglyNumbers[r5] * 5 {
r5++
}
}
return pUglyNumbers[index-1]
}
func min(a, b int) int {
if a < b {
return a
}
return b
}