LeetCode(264) Ugly Number II

不知道为什么注释掉的三条if语句不和下面的两条语句等价。一个导致结果是正确的,一个导致是错误的,想不通。现在在同学的帮助下想通了,如果v2和v3相等,counter就会加两次。所以这两段代码是不等效的。

class Solution {
public:
    int nthUglyNumber(int n) {

        int id2 = 0; int id3 = 0; int id5 = 0;
        int rst = 1; int counter = 2;
        vector<int> buf; buf.push_back(1);
        int v2, v3, v5;
        while(counter <= n) {

            v2 = 2 * buf[id2]; v3 = 3 * buf[id3]; v5 = 5 * buf[id5];
            rst = min(v2, min(v3, v5));
            buf.push_back(rst);
            //if(rst == v2) { id2++; counter++; }
            //if(rst == v3) { id3++; counter++; }
            //if(rst == v5) { id5++; counter++; }
            id2 += (rst == v2); id3 += (rst == v3); id5 += (rst == v5);
            counter++;
        }

        return rst;
    }
};

你可能感兴趣的:(LeetCode)