462. Minimum Moves to Equal Array Elements II 难度:medium

来源:互联网 发布:smart白板软件下载 编辑:程序博客网 时间:2024/06/05 17:28

题目:

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:2Explanation: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 len = nums.size(), ans = 0;          nth_element(nums.begin(), nums.begin()+len/2, nums.end());          for(auto val: nums) ans += abs(val - nums[len/2]);          return ans;      }};


0 0