leetcode 462. Minimum Moves to Equal Array Elements II

来源:互联网 发布:部落冲突毒药升级数据 编辑:程序博客网 时间:2024/06/15 14:35

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:2Explanation:Only two moves are needed (remember each move increments or decrements one element):[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

这道题一开始我没想明白,认为将他们都变成他们的平均数就好了,然后wrong answer了。写了几个示例,比如[1,0,0,8,6],发现不应该是平均数,而应该是中位数(至于为什么我也不知道),将数组从小到大排序后,如果奇数个数的数组,就是数组中index为length/2的数,如果偶数个数的数组,也是index为length/2的数,即两个中位数中较后面的那个(至于为什么我也不知道)。所以目前的任务是,找到数组中第k大的数,即从小到大排序后第length/2索引位的元素。

通过查阅资料,(可以看我上一篇blog),快排是找出第k大元素的好办法,于是我就照着写出了代码。

public class Minimum_Moves_to_Equal_Array_Elements_II_462 {public int minMoves2(int[] nums) {int result=0;int length=nums.length;int k=length/2;//看中位数的index索引//接下来就是找数组中第k大的元素是多少了int low=0;int high=length-1;int mid=sort(nums, low, high);while(mid!=k){if(mid>k){high= mid-1;mid=sort(nums, low, high);}else{low=mid+1;mid=sort(nums, low, high);}}int theNumer=nums[k];for(int i=0;i<length;i++){result+=Math.abs(nums[i]-theNumer);}return result;}public int sort(int[] nums,int low,int high){int pivot=nums[low];while (low < high) {while (low < high && nums[high] >= pivot) {high--;}nums[low] = nums[high];while (low < high && nums[low] <= pivot) {low++;}nums[high] = nums[low];}nums[low]=pivot;return low;}public static void main(String[] args) {// TODO Auto-generated method stubMinimum_Moves_to_Equal_Array_Elements_II_462 m=new Minimum_Moves_to_Equal_Array_Elements_II_462();int[] a=new int[]{1,0,0,8,6};System.out.println(m.minMoves2(a));}}
有大神给出了为何是中位数的思路。具体可以到https://discuss.leetcode.com/topic/68762/java-solution-with-thinking-process来看。

假设最终数组为[k,k,k,...,k],那么moves的计算公式为moves = |k - a1| + |k-a2| + ...+|k-ai|+...+|k-an|. 考虑到一些元素比k大,一些元素比k小,所以我们需要知道比k小的元素有几个,比k大的元素有几个,这样公式就变成moves = numLessk-sumLess + sumGreater - numGreaterk.。现在我们需要找到这样的k来使得moves最小。显然k一定要是数组中的元素,这样会至少减少一个move.直觉上来讲,k是排序后数组的中位数。证明很简单(我:简单个头),因为moves = numLessk-sumLess + sumGreater - numGreaterk.,我们对k求导,变成 dmoves/dk = numLess-numGreater. 我们知道当导数为0时,moves最小,所以结果是numLess-numGreater = 0 或者numsLess = numGreater. 这就是k是中位数的原因。
知道结论是中位数之后,有大神直接这样做,也非常简洁。

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

阅读全文
0 0
原创粉丝点击