题目描述
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.length
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
解题思路
【C++】
class Solution {
public:
int minMoves2(vector<int>& nums) {
int move = 0;
int median = findKthSmallest(nums, nums.size() / 2);
for(int num : nums) move += abs(num - median);
return move;
}
int findKthSmallest(vector<int>& 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<int>& 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<int>& nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
用已有sort函数
class Solution {
public:
int minMoves2(vector<int>& 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;
}
}