0462.cpp (625B)
1 class Solution { 2 public: 3 int minMoves2(vector<int> &nums) const { 4 int res = 0, i = 0, j = nums.size() - 1; 5 sort(begin(nums), end(nums)); 6 while (i < j) 7 res += nums[j--] - nums[i++]; 8 return res; 9 } 10 }; 11 12 // Optimized solution 13 class Solution { 14 public: 15 int minMoves2(vector<int> &nums) const { 16 const int n = nums.size(), mid = n / 2; 17 nth_element(begin(nums), begin(nums) + mid, end(nums)); 18 const int median = nums[mid]; 19 int res = 0; 20 for (int i = 0; i < n; i++) 21 res += abs(nums[i] - median); 22 return res; 23 } 24 };