leetcode 462. Minimum Moves to Equal Array Elements II
这道题目和leetcode453是有联系的,虽然这道题难度为中等,但是我感觉初等难度的453绕的弯子更大一些。
题目: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]
中文版:
给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1。 您可以假设数组的长度最多为10000。
例如:输入:[1,2,3]输出:
2 说明: 只有两个动作是必要的(记得每一步仅可使其中一个元素加1或减1): [1,2,3] => [2,2,3] => [2,2,2]
解答思路:首先需要思考将数组中的所有的数都变成一个相同的数,那这个数应该是什么才能使得所有数字移动次数最少?一般脑海中有两种想法:1、中位数 2、平均数。
那就写个小例子看看到底选哪个, 列如 {3,2,1,10} 中位数为2,平均数为4。
如果都移动到中位数需要(3-2)+(2-2)+(2-1)+(10-1)=11次,
如果都移动到中位数需要(4-2)+(4-2)+(4-1)+(10-4)=13次
所以就选中位了。
解答代码:
1 class Solution { 2 public int minMoves2(int[] nums) { 3 Arrays.sort(nums); 4 int length=nums.length; 5 int midNum=nums[length/2]; 6 int moveCnt=0; 7 for (int i = 0; i <length ; i++) { 8 moveCnt+=Math.abs(nums[i]-midNum); 9 } 10 return moveCnt; 11 } 12 }
运行结果:

浙公网安备 33010602011771号