LeetCode1051-高度检查器

题目链接

英文链接:https://leetcode.com/problems/height-checker/

中文链接:https://leetcode-cn.com/problems/height-checker/

题目详述

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

请你返回至少有多少个学生没有站在正确位置数量。该人数指的是:能让所有学生以 非递减 高度排列的必要移动人数。

示例:

1
2
3
4
输入:[1,1,4,2,1,3]
输出:3
解释:
高度为 4、3 和最后一个 1 的学生,没有站在正确的位置。

提示:

  1. 1 <= heights.length <= 100
  2. 1 <= heights[i] <= 100

题目详解

  • 将原数组拷贝一份,然后排序。
  • 统计两个数组有多少个位置不同。
  • 时间复杂度为 O(nlogn),主要花在排序上。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class LeetCode_01051 {

public int heightChecker(int[] heights) {
int[] copy = Arrays.copyOf(heights, heights.length);
Arrays.sort(copy);
int res = 0;
for (int i = 0; i < heights.length; ++i) {
if (heights[i] != copy[i]) {
++res;
}
}
return res;
}
}
  • 由于 1 <= heights[i] <= 100,可以采用类似计数排序的方法,统计每个数各出现了多少次。
  • 然后遍历哈希表,计算哈希表下标与原数组值不同的个数。
  • 时间复杂度为 O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class LeetCode_01051 {

public int heightChecker(int[] heights) {
int[] cnt = new int[101];
for (int height : heights) {
++cnt[height];
}
int res = 0;
for (int i = 0, j = 0; i < cnt.length; i++) {
while (cnt[i]-- > 0) {
if (i != heights[j++]) {
++res;
}
}
}
return res;
}
}