题目
单个文件行
a single file line
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
解法
方法一:双重for循环(笨死了)
class Solution {
public int heightChecker(int[] heights) {
int[] unSortedHeights = new int[heights.length];
for (int i = 0; i < heights.length; i++) {
unSortedHeights[i] = heights[i];
}
// System.out.println("unSortedHeights -->" + unSortedHeights);
Arrays.sort(heights);
// System.out.println("heights --> " + heights);
int sortedHeigthsLength = heights.length;
int unSortedHeightsLength = unSortedHeights.length;
int res = 0;
for (int i = 0; i < unSortedHeightsLength; i++) {
for (int j = 0; j < sortedHeigthsLength; j++) {
if (i == j && unSortedHeights[i] != heights[j]) {
// System.out.println("unSortedHeights[i] -- > " + unSortedHeights[i]);
// System.out.println("heights[j] -- > " + heights[j]);
res += 1;
}
}
}
return res;
}
}
方法三: 基于比较的排序
代码
static class Solution2 {
public static int heightChecker(int[] heights) {
int l = heights.length, ans = 0;
int[] expected = new int[l];
System.arraycopy(heights, 0, expected, 0, l);
Arrays.sort(expected);
for (int i = 0; i < l; i++) {
if (heights[i] == expected[i]) {
ans++;
}
}
return ans;
}
}
复杂度分析
-
时间复杂度:O(nlogn),其中 n 是数组 heights 的长度。即为排序需要的时间。
-
空间复杂度:O(n),即为数组 expected 需要的空间。
方法三:计数排序
代码
static class Solution3 {
public static int heightChecker(int[] heights) {
int m = Arrays.stream(heights).max().getAsInt();
System.out.println(m);
int[] cnt = new int[m + 1];
for (int h : heights) {
++cnt[h];
}
int idx = 0, ans = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= cnt[i]; j++) {
if (heights[idx] != i) {
ans++;
}
idx++;
}
}
return ans;
}
}
}
复杂度分析
-
时间复杂度:O(n + C),其中 n 是数组 heights 的长度,C是数组heights 中的最大值。即为计数排序需要的时间。
-
空间复杂度:O©,即为计数排序需要的空间。
转载
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/height-checker/solution/gao-du-jian-cha-qi-by-leetcode-solution-jeb0/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。