剑指Offer——丑数
2017-11-02 14:29
197 查看
Question
把只包含因子2、3和5的数称作丑数。Solution
用空间换时间。保存之前生成的丑数,因为之后生成的丑数都是之前的丑数乘上2,3或5得到的。而且只需要,乘上2,3,5以后比当前最大值大的最小值。因此,我们可以标记乘上2,3,5,刚好比最大值大的位置。Code
class Solution { public: int GetUglyNumber_Solution(int index) { vector<int> vec(index, 0); vec[0] = 1; int p2 = 0; int p3 = 0; int p5 = 0; int p = 1; while (p < index) { int minValue = min(vec[p5] * 5, min(vec[p2] * 2, vec[p3] * 3)); vec[p] = minValue; while (vec[p2] * 2 <= vec[p]) p2++; while (vec[p3] * 3 <= vec[p]) p3++; while (vec[p5] * 5 <= vec[p]) p5++; p++; } return vec[index - 1]; } };
相关文章推荐
- 剑指Offer32 丑数
- 【剑指offer】面试题34-丑数
- 剑指offer 丑数
- 码农小汪-剑指Offer之31 -丑数
- 【九度OJ1214】|【剑指offer34】丑数
- 剑指Offer - 九度1214 - 丑数
- 剑指offer的34题 丑数
- 剑指offer34——丑数
- 剑指offer之丑数
- 剑指Offer面试题34题:丑数(Ugly Number)(while循环里面的三个小问题)
- 剑指Offer面试题:29.丑数
- 剑指offer 34. 丑数
- 剑指offer——丑数(好题,思路)
- 剑指offer面试题之求第n个丑数
- 【剑指offer-Java版】34丑数
- 剑指offer:丑数
- 剑指Offer(java版):丑数
- 剑指offer——面试题34:丑数
- 剑指offer-面试题34-丑数
- 剑指offer 34- 丑数