Minimum Moves to Equal Array Elements II (M)
题目
Given an integer array nums
of size n
, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1
.
Example 1:
Input: nums = [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]
Example 2:
Input: nums = [1,10,2,9]
Output: 16
Constraints:
n == nums.length
1 <= nums.length <= 10^5
-109 <= nums[i] <= 10^9
题意
给定一个数组,每次可以对其中一个元素进行+1或-1,问最少需要几步能将所有元素变为一样。
思路
找到中位数,将所有元素变为中位数所需要的步数就是最少步数。其中的原理可以参考Leetcode 462. Minimum Moves to Equal Array Elements II(L1范数性质)。
代码实现
Java
class Solution {
public int minMoves2(int[] nums) {
int ans = 0;
Arrays.sort(nums);
int mid = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2;
for (int num : nums) {
ans += Math.abs(num - mid);
}
return ans;
}
}