方法一:采用笨法,进行排序,然后依次对比。
class Solution {
public int heightChecker(int[] heights) {
int[] a=heights.clone();#clone方法
Arrays.sort(heights);//快速排序
int sum=0;
for(int i=0;i<heights.length;i++){
if(heights[i]!=a[i]){
sum++;
}
}
return sum;
}
}
方法二:采用桶排序的思想,然后自然有序,进行比较,过程记住,好多地方可以用到,而且在元素值范围小的情况下,牺牲空间换取时间,很有效。
class Solution {
public int heightChecker(int[] heights) {
int [] temp=new int[101];
for(int height:heights){
temp[height]++;
}
int j=0;
int sum=0;
for(int i=1;i<=100;i++){
while(temp[i]>0){//这个while循环就是用来处理重复值的
if(i!=heights[j]){
sum++;
}
j++;//他的位置别错
temp[i]--;//不要忘了--
}
}
return sum;
}
}
当然最后的那个for循环也可以从heights数组比较,而不是从新数组,也是可以的,代码是下面的
class Solution {
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;
}
}