處理 非遞減或者非遞增 排列 的時候 ,可以使用計數排序,將時間 復雜度變為 O(N),空間復雜度變為O(1)。
1 int heightChecker(vector<int>& heights) { 2 vector<int> res(101); 3 for (auto c : heights) 4 { 5 ++res[c]; 6 } 7 int count = 0; 8 for (int i = 0, j = 1; i < heights.size(); ++j) 9 { 10 while (res[j] > 0) 11 { 12 --res[j]; 13 if (heights[i] == j) 14 { 15 ++i; 16 } 17 else 18 { 19 ++i; 20 ++count; 21 } 22 } 23 } 24 return count; 25 }
?