462. Minimum Moves to Equal Array Elements II
原创
©著作权归作者所有:来自51CTO博客作者wx62ea2466cca9a的原创作品,请联系作者获取转载授权,否则将追究法律责任
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]
思路:
要寻找最后所有数字都是一样的那个数字N。 为了移动的次数最小,显然应该是中位数。
class Solution
public int minMoves2(int[] nums) {
if(nums == null || nums.length ==0)
return 0;
Arrays.sort(nums);
int median = nums[nums.length/2];
int sum = 0;
for(int i = 0;i < nums.length;i++){
sum += Math.abs(nums[i] - median);
}
return sum;
}
}