LeetCode-462. Minimum Moves to Equal Array Elements IIhttps://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/
题目描述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.
Test cases are designed so that the answer will fit in a 32-bit integer.
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.length1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
解题思路【C++】
class Solution {
public:
int minMoves2(vector& nums) {
int move = 0;
int median = findKthSmallest(nums, nums.size() / 2);
for(int num : nums) move += abs(num - median);
return move;
}
int findKthSmallest(vector& nums, int k) {
int l = 0, h = nums.size() - 1;
while (l < h) {
int j = partition(nums, l, h);
if(j == k) break;
if(j < k) l = j + 1;
else h = j - 1;
}
return nums[k];
}
int partition(vector& nums, int l, int h) {
int i = l, j = h + 1;
while(true) {
while(nums[++i] < nums[l] && i < h) ;
while(nums[--j] > nums[l] && j > l) ;
if(i >= j) break;
swap(nums, i, j);
}
swap(nums, l, j);
return j;
}
void swap(vector& nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
用已有sort函数
class Solution {
public:
int minMoves2(vector& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
int res = 0;
for (auto i : nums) {res += abs(i-nums[n/2]);}
return res;
}
};
【Java】
class Solution {
public int minMoves2(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
int res = 0;
for (int i : nums) {res += Math.abs(i-nums[n/2]);}
return res;
}
}


![LeetCode-462. Minimum Moves to Equal Array Elements II [C++][Java] LeetCode-462. Minimum Moves to Equal Array Elements II [C++][Java]](http://www.mshxw.com/aiimages/31/778139.png)
