LeetCode 264 Ugly Number II (递推)

原创 2016年08月31日 14:13:06

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 first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.


题目链接:https://leetcode.com/problems/ugly-number-ii/

题目分析:用一个uglyNum数组记录,保证按升序构造,用当前的每个丑数,分别乘2,3,5其中比最大的大的最少的就是当前的下一个丑数,递推时间复杂度O(n)

public class Solution {
    
    public int Min3(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }
    
    public int nthUglyNumber(int n) {
        int[] uglyNum = new int[n + 5];
        uglyNum[1] = 1;
        int i = 1, i2 = 1, i3 = 1, i5 = 1, cur;
        while(i <= n) {
            cur = Min3(uglyNum[i2] * 2, uglyNum[i3] * 3, uglyNum[i5] * 5);
            if(cur == uglyNum[i2] * 2) {
                i2 ++;
            }
            if(cur == uglyNum[i3] * 3) {
                i3 ++;
            }
            if(cur == uglyNum[i5] * 5) {
                i5 ++;
            }
            uglyNum[++ i] = cur;
        }
        return uglyNum[n];
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Leetcode 264(Ugly Number II)

QuestionWrite a program to find the nthn^{th} ugly number.Ugly numbers are positive numbers whose pr...
  • senliuy
  • senliuy
  • 2015年08月19日 13:31
  • 519

<LeetCode OJ> 26 / 264 / 313 Ugly Number (I / II / III)

263. Ugly Number My Submissions Question Total Accepted: 33755 Total Submissions: 96873 Difficul...

LeetCode 264: Ugly Number II

264. Ugly Number IIDifficulty: Medium Write a program to find the n-th ugly number.Ugly numbers are...

leetcode 264. Ugly Number II

Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors...

Leetcode-264. Ugly Number II

题目: 代码: 版本1: class Solution1 { public: int nthUglyNumber(int n) { vectornum = {2,3,5}; vect...

Leetcode 264. Ugly Number II[medium]

题目: Write a program to find the n-th ugly number.Ugly numbers are positive numbers whose prime fact...

[leetcode] 264.Ugly Number II

题目: Write a program to find the n-th ugly number.Ugly numbers are positive numbers whose prime fact...

leetcode - 264. Ugly Number II

算法系列博客之Dynamic Programming 本篇博客将运用动态规划的思想来解决leetcode上264号问题 问题描述:Write a program to find the n-th ...
  • Quiteen
  • Quiteen
  • 2017年06月11日 19:54
  • 109

[leetcode] 264. Ugly Number II 解题报告

题目链接:https://leetcode.com/problems/ugly-number-ii/ Write a program to find the n-th ugly number. ...

leetcode263_264:Ugly Number & Ugly Number II

Ugly NumberWrite a program to check whether a given number is an ugly number.Ugly numbers are positi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode 264 Ugly Number II (递推)
举报原因:
原因补充:

(最多只允许输入30个字)