处理 非递减或者非递增 排列 的时候 ,可以使用计数排序,将时间 复杂度变为 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 }