LeetCode刷题实战462:最少移动次数使数组元素相等 II
程序IT圈
共 1088字,需浏览 3分钟
·
2021-12-14 01:13
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.
示例
输入:
[1,2,3]
输出:
2
说明:
只有两个动作是必要的(记得每一步仅可使其中一个元素加1或减1):
[1,2,3] => [2,2,3] => [2,2,2]
解题
class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(),nums.end());
int i = 0,j = nums.size() - 1,ans = 0;
while(i < j) ans += nums[j--] - nums[i++];
return ans;
}
};
评论