-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1051. Height Checker
75 lines (57 loc) · 1.59 KB
/
1051. Height Checker
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//LEETCODE PROBLEM
//LEVEL - Easy
//1051. Height Checker
/* JAVA ACCEPTED SOLUTION - SORTING */
class Solution {
public int heightChecker(int[] heights) {
int []expected = new int[heights.length];
for(int i=0;i<heights.length;i++){
expected[i]=heights[i];
}
Arrays.sort(expected);
int count=0;
for(int i=0;i<heights.length;i++){
if(heights[i] != expected[i]) count++;
}
return count;
}
}
//TC - O(nlogn)
LOGIC- sort the array and then compare the both
/* JAVA ACCEPTED COUNTING SORT */
class Solution {
public int heightChecker(int[] heights) {
int[] count = new int[101];
for (int i = 0; i < heights.length; i++) {
count[heights[i]]++;
}
for (int i = 1; i < count.length; i++) {
count[i] += count[i-1];
}
int result = 0;
for (int i = heights.length-1; i >= 0; i--) {
count[heights[i]]--; // this is the correct location for heights[i] based on counting sort
if (heights[count[heights[i]]] != heights[i])
result++;
}
return result;
}
}
/* BUCKET SORTING */
class Solution {
public int heightChecker(int[] heights) {
// perform a bucket-sort
int[] bucket = new int[101];
for(int number : heights) {
bucket[number]++;
}
// check the ammount of disparities between the input array and the bucket
int count = 0, index = 0;
for(int i = 1; i <= 100; i++) {
while(bucket[i] > 0) {
if(i != heights[index++]) count++;
bucket[i]--;
}
}
return count;
}