LeetCode 1051. Height Checker

1051. Height Checker(高度检查器)

链接

https://leetcode-cn.com/problems/height-checker

题目

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

请你返回能让所有学生以 非递减 高度排列的最小必要移动人数。

示例:

输入:heights = [1,1,4,2,1,3]
输出:3

提示:

1 <= heights.length <= 100
1 <= heights[i] <= 100

思路

不是很懂这题的意义,直接排序然后和原数组比较,每一个不同的就加一,直接输出即可。

代码

public static int heightChecker(int[] heights) {
    int[] other = heights.clone();
    Arrays.sort(other);
    int ans = 0;
    for (int i = 0; i < heights.length; i++) {
      if (other[i] != heights[i]) {
        ans++;
      }
    }
    return ans;
  }
原文地址:https://www.cnblogs.com/blogxjc/p/12250500.html