Leetcode-462 Minimum Moves to Equal Array Elements II(最少移动次数使数组元素相等 II)

 1 class Solution
 2 {
 3     public:
 4         int minMoves2(vector<int>& nums)
 5         {
 6             sort(nums.begin(),nums.end(),less<int>());
 7             int result = 0;
 8             if((nums.size()&0x1)==1)
 9             {
10                 for(auto d:nums)
11                     result += abs(d-nums[nums.size()/2]);
12             }
13             else
14             {
15                 for(auto d:nums)
16                     result += abs(d-nums[nums.size()/2]);
17                 int tmp = result;
18                 result = 0;
19                 for(auto d:nums)
20                     result += abs(d-nums[nums.size()/2-1]);
21                 result = min(result,tmp);
22             }
23             return result;
24         }
25 };

 

posted @ 2018-11-13 18:23  Asurudo  阅读(124)  评论(0编辑  收藏  举报