维护三个“指针”,分别对应应该和2/3/5
做乘法运算的元素的下标,如此一来可以:
- 确保数组中的每个数都与
2/3/5
做过一遍乘法 - 保证每次添加到数组中的新元素为下一个最小值,且不重复
代码如下:
// // Created by jt on 2020/9/2. // #include <vector> using namespace std; class Solution { public: int GetUglyNumber_Solution(int index) { if (index < 1) return 0; vector<int> vec(index, 1); int idx2 = 0, idx3 = 0, idx5 = 0; for (int i = 1; i < index; ++i) { vec[i] = min(vec[idx2] * 2, min(vec[idx3] * 3, vec[idx5] * 5)); if (vec[i] == vec[idx2] * 2) ++idx2; if (vec[i] == vec[idx3] * 3) ++idx3; if (vec[i] == vec[idx5] * 5) ++idx5; } return vec[index-1]; } };