leetcode [264] - 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
.
Example:
Input: n = 10 Output: 12 Explanation:1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.
Note:
1. 1
is typically treated as an ugly number.
2. n
does not exceed 1690.
题目大意:
程序输出第n个丑数。(丑数指只能被2,3,5整除的数)
理 解:
可以很容易发现,后面的丑数都是在前面的丑数基础上乘以2或者3或者5.
设置三个指针分别指向2,3,5对应的"基数",比较当前三个数的大小,选择最小的数作为当前的丑数。
【参考了其他人的想法,指针这个方法真的很奇妙。】
代 码 C++:
class Solution { public: int nthUglyNumber(int n) { int *uglyNumber = new int[n]; uglyNumber[0]=1; int nextUglyIndex = 1; int *uglyNumberOfTwo = uglyNumber; int *uglyNumberOfThree = uglyNumber; int *uglyNumberOfFive = uglyNumber; int min; while(nextUglyIndex<n){ min = (((*uglyNumberOfTwo)*2) < ((*uglyNumberOfThree)*3))? ((*uglyNumberOfTwo)*2):((*uglyNumberOfThree)*3); min = (min < *uglyNumberOfFive*5)?min:*uglyNumberOfFive*5; uglyNumber[nextUglyIndex]=min; if(*uglyNumberOfTwo*2<=min) uglyNumberOfTwo++; if(*uglyNumberOfThree*3<=min) uglyNumberOfThree++; if(*uglyNumberOfFive*5<=min) uglyNumberOfFive++; nextUglyIndex++; } return uglyNumber[n-1]; } };
标签:uglyNumber,丑数,int,Number,ugly,II,Ugly,numbers,10 来源: https://www.cnblogs.com/lpomeloz/p/10922166.html