Original link: leetcode-cn.com/problems/he…

Answer:

  1. If you have an unsorted array, how many digits do you have to move in order to sort it from the lowest to the highest?
  2. The key is to understand the “minimum number of digits to move”, that is, how many different elements of the array before and after sorting, then the minimum number of digits to move in order to achieve the sorting result.
  3. So, sort the array, and then compare the sorted array with the original array, counting the number of different elements.
/** * @param {number[]} heights * @return {number} */ var heightChecker = function(heights) sortedHeights = [...heights].sort((a, b) => a - b); // store count result = 0; ForEach ((height, index) => {// if (height, index) => {result + 1 if (height! == sortedHeights[index]) { result++; }}); return result; };Copy the code