题目链接
解题思路
- 首先将原数组复制一份为
tmp
- 然后对数组
tmp
进行排序 - 比较原数组和排序后的
tmp
每个位置的不同个数即为答案
AC代码
class Solution {
public int heightChecker(int[] heights) {
int ans = 0;
int len = heights.length;
int[] tmp = new int[len];
System.arraycopy(heights, 0, tmp, 0, len);
Arrays.sort(tmp);
for (int i = 0; i < len; i++) {
if (heights[i] != tmp[i])
ans++;
}
return ans;
}
}
本地测试代码
package com.company;
import java.util.Arrays;
public class Solution_1051 {
public static int heightChecker(int[] heights) {
int ans = 0;
int len = heights.length;
int[] tmp = new int[len];
System.arraycopy(heights, 0, tmp, 0, len);
Arrays.sort(tmp);
for (int i = 0; i < len; i++) {
if (heights[i] != tmp[i])
ans++;
}
return ans;
}
public static void main(String[] args) {
System.out.println(heightChecker(new int[]{1, 1, 4, 2, 1, 3}));
System.out.println(heightChecker(new int[]{5, 1, 2, 3, 4}));
}
}