您的位置:首页 > 编程语言 > C语言/C++

LeetCode-Ugly Number II-解题报告

2015-08-28 15:52 651 查看
原链接https://leetcode.com/problems/ugly-number-ii/

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.

将包含一个数分解质因素后只有2,3,5中的数 

如果一个数是ugly数  那么乘以2,3,5中的一个或多个,那么它也是ugly数

关键是如果从小到大依次求的

1肯定是ugly数

1*2 1*3 1*5 中最小的是2 所以下一个是2

1 2;

那么下一个个数是肯定是在 2*2 1*3 1*5 中的

所以 定义一个cnt[3],表示2,3,5该乘上ugly数组中的arr[cnt[0,1,2]];

如果对应的2,3,或者5为当前最小的,那么他的cnt应该++;

然而这并不能求出最终答案,应为可能出现相同的数

比如 2*3 3*2这种情况。

只需要在取出数字后判断是否可前面一个相等,相等继续循环,并且循环变量-1,也就是让下次继续求第i个ugly数,直到与前面一个不同。

class Solution {
public:
int nthUglyNumber(int n) {
int cnt[3] = { 0 };
int* arr = new int
;
arr[0] = 1;
for (int i = 1; i < n; ++i)
{
int pos = 0;
arr[i] = Min(arr[cnt[0]] * 2, arr[cnt[1]] * 3, arr[cnt[2]] * 5, pos);
if (arr[i] == arr[i - 1])i--;
cnt[pos]++;
}
return arr[n - 1];
}
inline int Min(int a, int b, int c, int& pos)
{
if (a > b)a = b, pos = 1;
if (a > c)a = c, pos = 2;
return a;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode