LeetCode1051高度检查器

方法一:采用笨法,进行排序,然后依次对比。

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值