前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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]这个题目挺有意思的,也挺简单的,找到整个数组的中位数,然后求所有数到中位数的距离就行了。 Your runtime beats 26.05% of java submissions.
public class Solution {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int mid = 0;
if((nums.length%2) == 0) mid = nums[nums.length /2];
else mid = nums[(nums.length)/ 2];
int result = 0;
for(int item : nums){
result += Math.abs(mid - item);
}
return result;
}
}