intheightChecker(int* heights, int heightsSize) { int *expected = (int *)malloc(sizeof(int) * heightsSize); memcpy(expected, heights, sizeof(int) * heightsSize); qsort(expected, heightsSize, sizeof(int), cmp); int ans = 0; for (int i = 0; i < heightsSize; ++i) { if (heights[i] != expected[i]) { ++ans; } } free(expected); return ans; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10
funcheightChecker(heights []int) (ans int) { sorted := append([]int{}, heights...) sort.Ints(sorted) for i, v := range heights { if v != sorted[i] { ans++ } } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var heightChecker = function(heights) { let n = heights.length, ans = 0; const expected = newArray(n).fill(0); expected.splice(0, n, ...heights); expected.sort((a, b) => a - b); for (let i = 0; i < n; ++i) { if (heights[i] !== expected[i]) { ++ans; } } return ans; };
intheightChecker(int* heights, int heightsSize) { int m = 0; for (int i = 0; i < heightsSize; i++) { m = MAX(m, heights[i]); } int *cnt = (int *)malloc(sizeof(int) * (m + 1)); memset(cnt, 0, sizeof(int) * (m + 1)); for (int i = 0; i < heightsSize; i++) { ++cnt[heights[i]]; } int idx = 0, ans = 0; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= cnt[i]; ++j) { if (heights[idx] != i) { ++ans; } ++idx; } } free(cnt); return ans; }
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcheightChecker(heights []int) (ans int) { cnt := [101]int{} for _, v := range heights { cnt[v]++ }
idx := 0 for i, c := range cnt { for ; c > 0; c-- { if heights[idx] != i { ans++ } idx++ } } return }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var heightChecker = function(heights) { const m = parseInt(_.max(heights)); const cnt = newArray(m + 1).fill(0); for (const h of heights) { ++cnt[h]; }
let idx = 0, ans = 0; for (let i = 1; i <= m; ++i) { for (let j = 1; j <= cnt[i]; ++j) { if (heights[idx] !== i) { ++ans; } ++idx; } } return ans; };
复杂度分析
时间复杂度:O(n + C),其中 n 是数组 heights 的长度,C 是数组 heights 中的最大值。即为计数排序需要的时间。