[LeetCode] 1051. Height Checker

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].

Example 1:
Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
heights: [1,1,4,2,1,3]
expected: [1,1,1,2,3,4]
Indices 2, 4, and 5 do not match.

Example 2:
Input: heights = [5,1,2,3,4]
Output: 5
Explanation:
heights: [5,1,2,3,4]
expected: [1,2,3,4,5]
All indices do not match.

Example 3:
Input: heights = [1,2,3,4,5]
Output: 0
Explanation:
heights: [1,2,3,4,5]
expected: [1,2,3,4,5]
All indices match.

Constraints:
1 <= heights.length <= 100
1 <= heights[i] <= 100

高度检查器。

学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。

请你返回能让所有学生以 非递减 高度排列的最小必要移动人数。

注意,当一组学生被选中时,他们之间可以以任何可能的方式重新排序,而未被选中的学生应该保持不动。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/height-checker
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路一 - 排序

因为题目问的是需要移动多少个人的位置,所以当排序过后,每个人就知道他们应该站在什么位置上了。此时把排序过的和未排序过的数组进行比较,有不同的,则说明需要移动。

复杂度

时间O(nlogn)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int heightChecker(int[] heights) {
int len = heights.length;
int[] sorted = new int[len];
for (int i = 0; i < len; i++) {
sorted[i] = heights[i];
}
Arrays.sort(sorted);

int count = 0;
for (int i = 0; i < len; i++) {
if (sorted[i] != heights[i]) {
count++;
}
}
return count;
}
}

思路二 - 桶排序

桶排序的做法类似,但是更高效。因为身高的数据范围是 [1, 100],所以我们创建 101 个桶,表示身高从 0 到 100 每个不同身高分别有多少人。第一次遍历数组,记录不同身高分别有多少人。再次遍历数组,因为需要满足排列是非递减,把桶中的元素按照桶的下标从小到大一个个放到 expected 数组内,然后再比较 expected 数组和 heights 数组,有不同的,则说明需要移动。

复杂度

时间O(n)
空间O(n)

代码

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
class Solution {
public int heightChecker(int[] heights) {
int[] map = new int[101];
for (int height : heights) {
map[height]++;
}

int n = heights.length;
int[] expected = new int[n];
int index = 0;
for (int i = 0; i < map.length; i++) {
while (map[i] != 0) {
expected[index++] = i;
map[i]--;
}
}

int diff = 0;
for (int i = 0; i < n; i++) {
if (expected[i] != heights[i]) {
diff++;
}
}
return diff;
}
}

[LeetCode] 1051. Height Checker
https://shurui91.github.io/posts/742715672.html
Author
Aaron Liu
Posted on
October 28, 2020
Licensed under