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:
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