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]

给定一个非空的整型数组,找到使所有数组元素相等所需的最小移动次数,移动是将所选元素递增1或将选定元素递减1。您可以假设阵列的长度最多为10,000。

例:

输入: 
[1,2,3] 输出: 
2 说明: 
只需要两个移动(记住每个移动增加或减少一个元素):
[1,2,3] => [2,2,3] => [2 ,2,2]

(1)思想1:首先对数组进行排序sort(),然后找到其中间值mid = nums[nums.size()/2],然后再对“其余值减去中间值”进行一个求和,便是最终的结果。

C++:

 1 class Solution {
 2 public:
 3     int minMoves2(vector<int>& nums) {
 4         sort(nums.begin(),nums.end());
 5         int mid=nums[nums.size()/2];
 6         int result=0;
 7         for(int i=0;i<nums.size();i++)
 8             result=result+abs(nums[i]-mid);
 9         return result;
10     }
11 };

python:

1 class Solution:
2     def minMoves2(self, nums):
3         nums.sort()
4         result=0
5         mid=nums[int(len(nums)/2)]
6         for x in nums:
7             result=result+abs(x-mid)
8         return result

 

posted @ 2017-12-14 16:02  西瓜刀刀刀  阅读(222)  评论(0编辑  收藏  举报