Middle-题目81:264. Ugly Number II

原创 2016年05月31日 17:00:56

题目原文:
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.
题目大意:
求第n个丑陋数。
丑陋数指的是质因数只有2,3,5的正整数。注意1是丑数。
题目分析:
其实本题是前面的Middle-题目41的退化情况,相当于求列表[2,3,5]下的超级丑数。因此算法本质与那道题完全一样,只是这次只维护2,3,5三个素数的索引值即可。
源码:(language:java)

public class Solution {
    public int nthUglyNumber(int n) {
        int l1=1,l2=1,l3=1;
        int a,b,c;
        int[] uglyNumber = new int[n+1];
        uglyNumber[1] = 1;
        for(int i = 2;i<=n;i++) {
            a=uglyNumber[l1]*2;
            b=uglyNumber[l2]*3;
            c=uglyNumber[l3]*5;
            int min = min(a,b,c);
            if(min==a)
                l1++;
            if(min==b)
                l2++;
            if(min==c)
                l3++;
            uglyNumber[i]=min;
        }
        return uglyNumber[n];
    }
    private  int min(int a, int b, int c) {
        if(a<=b && a<=c)
            return a;
        else if(b<=a && b<=c)
            return b;
        else 
            return c;
    }
}

成绩:
7ms,beats 96.36%,众数9ms,12.39%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

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...

264. Ugly Number II -Medium

Question Write a program to find the n-th ugly number. Ugly numbers are positive numbers whos...

leetcode - 264. Ugly Number II

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

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

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

264. Ugly Number II

Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors...
  • x_shuck
  • x_shuck
  • 2016年05月16日 18:37
  • 128

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
  • 503

<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...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目81:264. Ugly Number II
举报原因:
原因补充:

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