Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Key: each of 2\3\5 is trying to multiply with the least number it has not been multiplied.

class Solution {
public:
    int nthUglyNumber(int n) {
        if(n< 1) return 0;
        int ret = 1, i2 = 0, i3= 0, i5 = 0;
        vector<int> buf;
        while(--n)
        {
            buf.push_back(ret);
            
            int v2 = buf[i2] * 2;
            int v3 = buf[i3] * 3;
            int v5 = buf[i5] * 5;
            ret = min(v2, min(v3, v5));
            
            i2 += ret == v2;
            i3 += ret == v3;
            i5 += ret == v5;
        }
        return ret;
    }
};
posted on 2015-08-25 13:15  Tonix  阅读(124)  评论(0编辑  收藏  举报