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]
这题就是在453基础上多了个+操作,思路大体是一样的,那个是减到最小那个数,
因为可以有两个操作,我们就全部都操作到中位数就行了
class Solution { public int minMoves2(int[] nums) { int sum = 0; Arrays.sort(nums); int temp = nums[nums.length / 2]; for (int i = 0; i < nums.length; i++) { if (i < nums.length / 2) sum += temp - nums[i]; else sum += nums[i] - temp; } return sum; } }