LeetCode #462 - Minimum Moves to Equal Array Elements II

题目描述:

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]

一步操作可以使一个数加一或减一,求需要多少步可以使一个数组中所有数都相等。先将数组排序,选取中位数作为目标,求每个数和中位数的差距再叠加。

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int n=nums.size();
        sort(nums.begin(),nums.end());
        int count=0;
        for(int i=0;i<n;i++) count+=abs(nums[i]-nums[n/2]);
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/LawFile/article/details/81255650