Leetcode: The minimum number of moves makes the array elements equal | | "462" title description
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, with each move adding 1 or minus 1 to the selected element. You can assume that the array has a maximum length of 10000.
For example:
Input: [A] output:2 Description: only two actions are necessary (remember that each step only adds 1 or minus 1 to one of the elements): [three-to-one] and [2,2,3] = [ 2,2,2]
Problem analysis
An intuitive understanding is this, if we have only two numbers, then what is the minimum number of steps we make them into equal elements? Of course, the difference between the two .
We know that the difference between the two is enough, as far as turning them into something doesn't really affect the outcome . For example, 1, 5, if the two are equal, can become 5, 5, 4, 4, and so on, the steps are 4 steps, that is, poor.
We just apply this logic to the two extreme elements of a sorted array. Once we are equal (no need to set explicitly, because we are just calculating), we discard the two outer, moving inward.
Java
public int minMoves2 (int[] nums) { arrays.sort (nums); int i=0, j=nums.length-1, count=0; while (I < j) { count + = Nums[j]-nums[i]; ++i; --j; } return count; }
Leetcode: The minimum number of moves makes the array elements equal | | "462"