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 };
Leetcode-462 Minimum Moves to Equal Array Elements II(最少移动次数使数组元素相等 II)