-
Notifications
You must be signed in to change notification settings - Fork 0
/
height_checker.cpp
73 lines (66 loc) · 1.52 KB
/
height_checker.cpp
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
/*
* =====================================================================================
*
* Filename: height_checker.cpp
*
* Description: 1051. Height Checker
* https://leetcode.com/problems/height-checker/description/
*
* Version: 1.0
* Created: 01/24/2023 22:08:56
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <cstdio>
#include <vector>
using std::vector;
// Sorting
class Solution1 {
public:
int heightChecker(vector<int>& heights) {
int num = 0;
vector<int> copy(heights.begin(), heights.end());
std::sort(copy.begin(), copy.end());
for (int i = 0; i < heights.size(); i++) {
if (heights[i] != copy[i]) {
num += 1;
}
}
return num;
}
};
// Counting sort
class Solution2 {
public:
int heightChecker(vector<int>& heights) {
int num = 0;
vector<int> counts(101, 0);
for (const int h : heights) {
counts[h] += 1;
}
int i = 0;
for (const int h : heights) {
while (counts[i] == 0) {
i++;
}
if (i != h) {
num += 1;
}
counts[i] -= 1;
}
return num;
}
};
using Solution = Solution2;
int main(int argc, char* argv[]) {
vector<int> heights({1, 1, 4, 2, 1, 3});
const int num = Solution().heightChecker(heights);
printf("Number of indices: %d\n", num);
return 0;
}