# Code language: Python classSolution: defheightChecker(self, heights: List[int]) -> int: returnsum(i != j for i, j inzip(heights, sorted(heights)))
1 2 3 4 5 6 7 8 9 10 11 12
// Code language: Java classSolution { publicintheightChecker(int[] heights) { int[] expected = heights.clone(); Arrays.sort(expected); intcnt=0; for (inti=0, n = heights.length; i < n; ++i) { if (heights[i] != expected[i]) ++cnt; } return cnt; } }
1 2 3 4 5 6 7 8 9 10 11 12 13
// Code language: C++ classSolution { public: intheightChecker(vector<int>& heights){ vector<int> expected(heights.begin(), heights.end()); sort(expected.begin(), expected.end()); int cnt = 0; for (int i = 0, n = heights.size(); i < n; ++i) { if (heights[i] != expected[i]) ++cnt; } return cnt; } };
时间复杂度: \(O(n \log n)\)
空间复杂度: \(O(1)\)
计数排序&模拟
注意到数据范围只有 100,使用计数排序会快些。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Code language: Python classSolution: defheightChecker(self, heights: List[int]) -> int: expected = [0for _ inrange(107)] for h in heights: expected[h] += 1 cnt, p = 0, 1 for h in heights: while expected[p] == 0: p += 1 if h != p: cnt += 1 expected[p] -= 1 return cnt
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Code language: Java classSolution { publicintheightChecker(int[] heights) { int[] expected = newint[107]; for (int h: heights) expected[h]++; intcnt=0; for (inti=0, p = 0, n = heights.length; i < n; ++i) { while(expected[p] == 0) ++p; if (heights[i] != p) ++cnt; expected[p]--; } return cnt; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: C++ classSolution { public: intheightChecker(vector<int>& heights){ int expected[107]; memset(expected, 0, sizeof(expected)); for (int h: heights) expected[h]++; int cnt = 0; for (int i = 0, p = 0, n = heights.size(); i < n; ++i) { while(expected[p] == 0) ++p; if (heights[i] != p) ++cnt; expected[p]--; } return cnt; } };