码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 264. Ugly Number II

时间:2016-07-16 11:29:34      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

264. Ugly Number II

  • Total Accepted: 35338
  • Total Submissions: 120258
  • Difficulty: Medium

 

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.

 

 

思路:动态规划。维持3条线路,uglynumnew=min(uglynum[k2]*2,uglynum[k3]*3,uglynum[k5]*3)(k2,k3,k5从0开始,uglynum[0]=1)。但要注意,可能会出现uglynumnew=uglynum[k2]*2=uglynum[k3]*3=uglynum[k5]*3的情况,此时,k2,k3,k5都要加1。

 

 

代码:

 1 class Solution {
 2 public:
 3     int minnum(int a,int b,int c){
 4         return c<(min(a,b))?c:min(a,b);
 5     }
 6     int nthUglyNumber(int n) {
 7         vector<int> uglynum(1,1);
 8         int k2=0,k3=0,k5=0;
 9         while(uglynum.size()<n){
10             int temp=minnum(uglynum[k2]*2,uglynum[k3]*3,uglynum[k5]*5);
11             uglynum.push_back(temp);
12             if(temp==uglynum[k2]*2){
13                 k2++;
14             }
15             if(temp==uglynum[k3]*3){
16                 k3++;
17             }
18             if(temp==uglynum[k5]*5){
19                 k5++;
20             }
21         }
22         return uglynum[n-1];
23     }
24 };

 

 

Leetcode 264. Ugly Number II

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5675727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!