From cbdaa6448d8e4f85e54466e510fe828cac16728c Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Tue, 11 Feb 2020 18:25:03 +0800 Subject: [PATCH] update 264 --- solutions/264. Ugly Number II.md | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/solutions/264. Ugly Number II.md b/solutions/264. Ugly Number II.md index 922fa9e..e36b301 100644 --- a/solutions/264. Ugly Number II.md +++ b/solutions/264. Ugly Number II.md @@ -6,6 +6,8 @@ 题目要求第n大的ugly数, 所以可以维护一个从小到大的ugly数组, 每次取2x, 3y, 5z三者最小的push进数组作为下一个ugly数, 详情可见代码. +时空复杂度均为O(n) + # C++ ``` C++ class Solution { @@ -14,18 +16,14 @@ public: vectorugly{1}; int idx2 = 0, idx3 = 0, idx5 = 0; - int tmp2, tmp3, tmp5; - while(1){ - if(!(--n)) break; - tmp2 = ugly[idx2] * 2; - tmp3 = ugly[idx3] * 3; - tmp5 = ugly[idx5] * 5; - - int next = min(tmp2, min(tmp3, tmp5)); - if(next == tmp2) idx2++; - if(next == tmp3) idx3++; - if(next == tmp5) idx5++; + int tmp2 = 2, tmp3 = 3, tmp5 = 5, next; + while(--n){ + next = min(tmp2, min(tmp3, tmp5)); ugly.push_back(next); + + if(next == tmp2) tmp2 = ugly[++idx2] * 2; + if(next == tmp3) tmp3 = ugly[++idx3] * 3; + if(next == tmp5) tmp5 = ugly[++idx5] * 5; } return ugly.back(); }