LeetCode 1051. Height Checker
考点 | 难度 |
---|---|
Sorting | Easy |
题目
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i]
is the expected height of the ith student in line.
You are given an integer array heights representing the current order that the students are standing in. Each heights[i]
is the height of the ith student in line (0-indexed).
Return the number of indices where heights[i] != expected[i].
思路
counting sort。用另外一个array存储每个height出现的次数,并且根据这个array决定下一个expected height是多少。如果和实际height不一样,result加一,expected height的个数减一。
答案
public int heightChecker(int[] heights) {
int[] heightToFreq = new int[101];
for (int height : heights) {
heightToFreq[height]++;
}
int result = 0;
int curHeight = 0;
for (int i = 0; i < heights.length; i++) {
while (heightToFreq[curHeight] == 0) {
curHeight++;
}
if (curHeight != heights[i]) {
result++;
}
heightToFreq[curHeight]--;
}
return result;
}