Minimum Moves to Equal Array Elements II

LeetCode Q 462 - Minimum Moves to Equal Array Elements II

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]

Solution:

Find the median of integer array. Sum up absolute values of diffs between each integer and the median.

Code:

public int minMoves2(int[] nums) {
  int median = quickSelect(nums, nums.length / 2 + 1, 0, nums.length - 1);
  int res = 0;
  for (int num: nums) res += Math.abs(num - median);
  return res;
}

private int quickSelect(int[] nums, int target, int left, int right) {
  int l = left, r = right, mid = l + (r - l) / 2, pivot = nums[mid];
  
  while (l <= r) {
    while (l <= r && nums[l] < pivot) l++;
    while (l <= r && nums[r] > pivot) r--;
    if (l >= r) break;
    swap(nums, l++, r--);
  }

  if (l-left+1 > target) return quickSelect(A, target, left, l - 1);
  if (l-leftrt+1 == k && l == r) return A[l];
  return quickSelect(A, k - (r-left+1), r + 1, right);
}

private void swap (int[] nums, int a, int b) {
  int temp = nums[a];
  nums[a] = nums[b];
  nums[b] = temp;
}

   Reprint policy


《Minimum Moves to Equal Array Elements II》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
 Previous
Smallest Range I Smallest Range I
LeetCode Q 908 - Smallest Range IGiven an array A of integers, for each integer A[i] we may choose any x with -K <= x
2019-07-05 Tong Shi
Next 
Integer Replacement Integer Replacement
LeetCode Q 397 - Integer ReplacementGiven a positive integer n and you can do operations as follow: If n is even, repla
2019-07-05 Tong Shi
  TOC