LeetCode 462. Minimum Moves to Equal Array Elements II

原题链接在这里:https://leetcode.com/problems/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]

题解:

The median minimizes the sum of absolute deviations. There is an article explaining this.

用quick sort找到median. 类似Kth Largest Element in an Array.

每一个元素对于median差值的绝对值的总和就是最小moves. 这里的median可以理解为第nums.length/2小的element.

Time Complexity: O(n), quick select O(n). n = nums.length. 

Space: O(1).

AC Java:

 1 class Solution {
 2     public int minMoves2(int[] nums) {
 3         if(nums == null || nums.length < 2){
 4             return 0;
 5         }
 6         
 7         int n = nums.length;
 8         int median = findK(nums, (n - 1) / 2, 0, n - 1);
 9         int res = 0;
10         for(int num : nums){
11             res += Math.abs(num - median);
12         }
13         
14         return res;
15     }
16     
17     private int findK(int [] nums, int k, int l, int r){
18         if(l >= r){
19             return nums[l];
20         }
21         
22         int m = partition(nums, l, r);
23         if(m == k){
24             return nums[k];
25         }else if(m < k){
26             return findK(nums, k, m + 1, r);
27         }else{
28             return findK(nums, k, l, m - 1);
29         }
30     }
31     
32     private int partition(int [] nums, int l, int r){
33         int pivot = nums[l];
34         while(l < r){
35             while(l < r && nums[r] >= pivot){
36                 r--;
37             }
38             
39             nums[l] = nums[r];
40             
41             while(l < r && nums[l] <= pivot){
42                 l++;
43             }
44             
45             nums[r] = nums[l];
46         }
47         
48         nums[l] = pivot;
49         return l;
50     }
51 }

类似Minimum Moves to Equal Array ElementsBest Meeting Point.

posted @ 2017-01-07 10:07  Dylan_Java_NYC  阅读(247)  评论(0编辑  收藏  举报