You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/1000-1099/1051.Height Checker/README_EN.md
+21-12
Original file line number
Diff line number
Diff line change
@@ -74,7 +74,11 @@ All indices match.
74
74
75
75
<!-- solution:start -->
76
76
77
-
### Solution 1
77
+
### Solution 1: Sorting
78
+
79
+
We can first sort the heights of the students, then compare the sorted heights with the original heights, and count the positions that are different.
80
+
81
+
The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of students.
78
82
79
83
<!-- tabs:start -->
80
84
@@ -114,7 +118,9 @@ public:
114
118
vector<int> expected = heights;
115
119
sort(expected.begin(), expected.end());
116
120
int ans = 0;
117
-
for (int i = 0; i < heights.size(); ++i) ans += heights[i] != expected[i];
121
+
for (int i = 0; i < heights.size(); ++i) {
122
+
ans += heights[i] != expected[i];
123
+
}
118
124
return ans;
119
125
}
120
126
};
@@ -123,17 +129,15 @@ public:
123
129
#### Go
124
130
125
131
```go
126
-
func heightChecker(heights []int) int {
127
-
expected := make([]int, len(heights))
128
-
copy(expected, heights)
132
+
func heightChecker(heights []int) (ans int) {
133
+
expected := slices.Clone(heights)
129
134
sort.Ints(expected)
130
-
ans := 0
131
135
for i, v := range heights {
132
136
if v != expected[i] {
133
137
ans++
134
138
}
135
139
}
136
-
return ans
140
+
return
137
141
}
138
142
```
139
143
@@ -152,7 +156,11 @@ function heightChecker(heights: number[]): number {
152
156
153
157
<!-- solution:start -->
154
158
155
-
### Solution 2
159
+
### Solution 2: Counting Sort
160
+
161
+
Since the height of the students in the problem does not exceed $100$, we can use counting sort. Here we use an array $cnt$ of length $101$ to count the number of times each height $h_i$ appears.
162
+
163
+
The time complexity is $O(n + M)$, and the space complexity is $O(M)$. Where $n$ is the number of students, and $M$ is the maximum height of the students. In this problem, $M = 101$.
156
164
157
165
<!-- tabs:start -->
158
166
@@ -244,16 +252,17 @@ func heightChecker(heights []int) int {
0 commit comments