Minimum Moves to Equal Array Elements II

Problem

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

Distance to Two Points Solution: O(nlgn) time

public class Solution {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int res = 0, i = 0, j = nums.length - 1;
        while (i < j) {
            res += nums[j--] - nums[i++];
        }
        return res;
    }
}

Analysis

The solution first sorts the given nums
Then we convert the problem to find a point which has the minimum distance to all other points
Here, the point stands for the element in nums
We know that the minimal distance for point c to a and b is between them, like a c b
Then we calculate the distance by c - a + b - c = b - a
Hence, to get the minimal moves to equal the array, we just need to find all their minimal distances
We first sort the array and use two pointers i and j to get distance from sides to the end

results matching ""

    No results matching ""