无尽算法之 高度检查器

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

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

示例:

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

思路:

其实题目在放屁, 说白了就是会排序前 和 排序后(升序), 对应位置不同的个数
那么直接冒泡排序, 搞定
注意: 数组是引用类型, 直接赋值的话是引用传递, 需要copy或者clone.

题解:

class Solution {
    public int heightChecker(int[] heights) {
        int[] ori=heights.clone();
        for(int i=0;i<heights.length;i++){
            for(int j=0; j<heights.length-i-1;j++){
                if(heights[j]>heights[j+1]){
                    int temp=heights[j];
                    heights[j]=heights[j+1];
                    heights[j+1]=temp;
                }
            }
        }
        int count=0;
        for(int i=0;i<heights.length;i++){
            if(heights[i]!=ori[i]){
                count++;
            }
        }
        return count;
    }
}

冒泡法直观写法

class Solution {
    public int heightChecker(int[] heights) {
        int[] ori=heights.clone();
        for(int i=heights.length-1;i>=0;i--){
            for(int j=0; j<i;j++){
                if(heights[j]>heights[j+1]){
                    int temp=heights[j];
                    heights[j]=heights[j+1];
                    heights[j+1]=temp;
                }
            }
        }
        int count=0;
        for(int i=0;i<heights.length;i++){
            if(heights[i]!=ori[i]){
                count++;
            }
        }
        return count;
    }
}
发布了125 篇原创文章 · 获赞 236 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_33709508/article/details/103933397