Minimum Moves to Equal Array Elements II
Description
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input: [1,2,3]Output: 2
Explanation: Only two moves are needed (remember each move increments or decrements one element):
[1,2,3] => [2,2,3] => [2,2,2]
Solution(javascript)
/*
* @lc app=leetcode id=462 lang=javascript
*
* [462] Minimum Moves to Equal Array Elements II
*/
// @lc code=start
// /** O(N^2)
// * @param {number[]} nums
// * @return {number}
// */
// const minMoves2 = function (nums) {
// let min = Infinity
// for (let i = 0; i < nums.length; i++) {
// let current = 0
// for (let j = 0; j < nums.length; j++) {
// current += Math.abs(nums[j] - nums[i])
// }
// min = Math.min(
// min,
// current,
// )
// }
// return min
// }
/** O(nlog(n))
* @param {number[]} nums
* @return {number}
*/
const minMoves2 = function (nums) {
let min = 0
nums.sort((a, b) => a - b)
let i = 0
let j = nums.length - 1
while (i <= j) {
min += nums[j] - nums[i]
i++
j--
}
return min
}
// @lc code=end