462 Minimum Moves to Equal Array Elements II

1. Question

Given anon-emptyinteger 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]

2. Implementation

(1) Sort + Two Pointers

思路: 给定两个点A和B, 如果要在它们之间找到一个点C,算出AC和CB的距离,可知Dist(AC): c - a, Dist(CB): b - c, 距离和为 b -a,

所以C点具体在哪不影响结果

(2) Quick Select to Get Median

思路: 证明为什么Median到各点的距离最短 https://discuss.leetcode.com/topic/71068/3-line-c-solution-with-rigorous-math-proof-same-as-problem-best-meeting-point

3. Time & Space Complexity

Sort + Two Pointers:时间复杂度O(nlogn), 空间复杂度O(1)

Quick Select to Get Median: 时间复杂度O(n), 空间复杂度O(logn), 因为quickSelect用了递归

Last updated

Was this helpful?