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 are at 10,000.
Example:
Input:[1,2,3]output:2explanation:only moves is needed (remember each move increments or decrements one element): [1, 2, 3] = [2,2,3] [ 2,2,2]
"Thinking Analysis"
This topic is similar to the minimum Moves to Equal Array elements. In the previous topic, we changed the idea of solving a problem by converting an operation that adds 1 on the number of n-1 to one operation per number, until each number is reduced to its minimum value. In this topic each of our operations is a number in the array plus 1 or minus 1, until all the numbers are the same. One idea is that the larger number decreases, and the smaller number increases until they are equal to the median value.
1. First sort the array
2. Find mid-value mid
3. Iterate through the array to find the Nums[i]-mid and
Because there is no guarantee that the number of array elements is odd, there is not necessarily an intermediate value. The general solution is as follows:
1. First sort the array
2. Match the number 22, and find out the sum of their difference.
The code is as follows:
1 Public classSolution {2 Public intMinMoves2 (int[] nums) {3 Arrays.sort (nums);4 inti = 0, j = nums.length-1;5 intCount = 0;6 while(I <j) {7Count + = nums[j--]-nums[i++];8 }9 Ten returncount; One } A}
Leetcode 462. Minimum Moves to Equal Array Elements II