Leetcode -- Ugly Number II

来源:互联网 发布:天庭淘宝城在线txt下载 编辑:程序博客网 时间:2024/04/29 17:50

题目:
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.

思路:
hints说的蛮清楚的。相当三个有序链表的merge。

代码:

class Solution {public:    int nthUglyNumber(int n) {        int c2 = 2, c3 = 3, c5 = 5;        int l2 = 0, l3 = 0, l5 = 0;        int last;        vector<int> uglyArray (n, 1);        for (int i = 1; i<n; i++)        {            last = uglyArray[i] = min(c2, min(c3, c5));            while(c2<=last) c2 = 2 * uglyArray[++l2];            while(c3<=last) c3 = 3 * uglyArray[++l3];            while(c5<=last) c5 = 5 * uglyArray[++l5];        }        return uglyArray[n -1];    }};

好像暴力解决,也是可以的。计算出所有的uglyNum,然后获取第n个。

0 0
原创粉丝点击