-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeightChecker.java
47 lines (46 loc) · 1.26 KB
/
HeightChecker.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// https://leetcode.com/problems/height-checker/
// #array
class Solution {
public int heightChecker(int[] heights) {
// // idea: use counter sort
// int max_number_element = 101;
// int[] counter_arr = new int[max_number_element];
// for (int height : heights) {
// counter_arr[height] += 1;
// }
// int[] sorted_arr = new int[max_number_element];
// int next_idx = 0;
// for(int i=0; i < max_number_element; i++) {
// while(counter_arr[i] > 0) {
// sorted_arr[next_idx] = i;
// counter_arr[i] -= 1;
// next_idx += 1;
// }
// }
// int result = 0;
// for (int i=0; i < heights.length; i++) {
// if (heights[i] != sorted_arr[i]) {
// result++;
// }
// }
// return result;
// idea: use counter sort
int max_number_element = 101;
int[] counter_arr = new int[max_number_element];
for (int height : heights) {
counter_arr[height] += 1;
}
int next_idx = 0;
int result = 0;
for (int i = 0; i < max_number_element; i++) {
while (counter_arr[i] > 0) {
if (heights[next_idx] != i) {
result++;
}
counter_arr[i] -= 1;
next_idx += 1;
}
}
return result;
}
}