Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 题解:1051. 高度检查器,JavaScript,先排序再比较,详细注释 #103

Open
chencl1986 opened this issue Jul 19, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/height-checker/

解题思路:

  1. 先明确题意,该题实际上是问,如果有一个未排序的数组,将其进行由低到高排序,前后最少需要移动多少个数字。
  2. 关键就是在于理解“最少需要移动多少个数字”,也就是说,排序前后数组的元素有多少个不同,那么最少也要移动这几个数字,才能达到排序的结果。
  3. 因此实现步骤诶,先对数组进行排序,然后将排序好的数组和原数组进行比较,统计值不同的元素个数即可。
/**
 * @param {number[]} heights
 * @return {number}
 */
var heightChecker = function(heights) {
  // 先对高度进行排序
  const sortedHeights = [...heights].sort((a, b) => a - b);
  // 储存计数结果
  let result = 0;

  // 遍历高度数组
  heights.forEach((height, index) => {
    // 如果当前高度与排序好的高度不一致,则代表其位置需要进行调整,result加1
    if (height !== sortedHeights[index]) {
      result++;
    }
  });

  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant