-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHeightChecker.java
More file actions
53 lines (43 loc) · 1.15 KB
/
HeightChecker.java
File metadata and controls
53 lines (43 loc) · 1.15 KB
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
48
49
50
51
52
53
package array;
import java.util.Arrays;
/**
* Description: https://leetcode.com/problems/height-checker
* Difficulty: Easy
*/
public class HeightChecker {
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public int heightCheckerViaCountingSort(int[] heights) {
int[] freqMap = new int[101];
for (int height : heights) {
freqMap[height]++;
}
int mismatch = 0;
int currentHeight = 1;
for (int height : heights) {
while (freqMap[currentHeight] == 0) {
currentHeight++;
}
if (height != currentHeight) {
mismatch++;
}
freqMap[currentHeight]--;
}
return mismatch;
}
/**
* Time complexity: O(nlog n)
* Space complexity: O(n)
*/
public int heightCheckerViaSorting(int[] heights) {
int[] expected = Arrays.copyOf(heights, heights.length);
Arrays.sort(expected);
int mismatch = 0;
for (int i = 0; i < heights.length; i++) {
if (heights[i] != expected[i]) mismatch++;
}
return mismatch;
}
}