寻找第 N 个丑数

丑数

https://www.nowcoder.com/practice/6aa9e04fc3794f68acf8778237ba065b?tpId=188&&tqId=36879&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking

public class Solution {

    public int GetUglyNumber_Solution(int index) {
        if (index < 7) return index;

        // 维护一个对应索引的丑数序列
        int[] ans = new int[index];
        ans[0] = 1;
        // 分别用于维护 2, 3, 5 的倍数序列
        int t2 = 0, t3 = 0, t5 = 0;

        for (int i = 1; i < index; i ++) {
            // 寻找 2, 3, 5 倍数序列的最小值
            ans[i] = Math.min(2 * ans[t2], Math.min(3 * ans[t3], 5 * ans[t5]));
            // 将满足条件的数出队列
            if (ans[t2] * 2 == ans[i]) t2 ++;
            if (ans[t3] * 3 == ans[i]) t3 ++;
            if (ans[t5] * 5 == ans[i]) t5 ++;
        }
        return ans[index - 1];
    }
}
全部评论

相关推荐

02-24 10:34
门头沟学院 Java
在思考的熊熊很讨厌吃香菜:之前发最美的女孩基本爱答不理,发最帅的hr终于有反馈了,女孩子也要自信起来
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客企业服务