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]

这道题是之前那道Minimum Moves to Equal Array Elements的拓展,现在我们可以每次对任意一个数字加1或者减1,让我们用最少的次数让数组所有值相等。一般来说这种题目是不能用暴力方法算出所有情况,因为OJ一般是不会答应的。那么这道题是否像上面一道题一样,有巧妙的方法呢?答案是肯定的。下面这种解法实际上利用了之前一道题Best Meeting Point的思想,是不感觉很amazing,看似完全不相干的两道题,居然有着某种内部联系。我们首先给数组排序,那么我们最终需要变成的相等的数字就是中间的数,如果数组有奇数个,那么就是最中间的那个数字;如果是偶数个,那么就是中间两个数的区间中的任意一个数字。而两端的数字变成中间的一个数字需要的步数实际上就是两端数字的距离,讲到这里发现是不是就和这道题Best Meeting Point的思路是一样了。那么我们就两对两对的累加它们的差值就可以了,参见代码如下:

解法一:

class Solution {
public:
int minMoves2(vector<int>& nums) {
int res = , i = , j = (int)nums.size() - ;
sort(nums.begin(), nums.end());
while (i < j) {
res += nums[j--] - nums[i++];
}
return res;
}
};

既然有了上面的分析,我们知道实际上最后相等的数字就是数组的最中间的那个数字,那么我们在给数组排序后,直接利用坐标定位到中间的数字,然后算数组中每个数组与其的差的绝对值累加即可,参见代码如下:

解法二:

class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end());
int res = , mid = nums[nums.size() / ];
for (int num : nums) {
res += abs(num - mid);
}
return res;
}
};

上面的两种方法都给整个数组排序了,时间复杂度是O(nlgn),其实我们并不需要给所有的数字排序,我们只关系最中间的数字,那么这个stl中自带的函数nth_element就可以完美的发挥其作用了,我们只要给出我们想要数字的位置,它就能在O(n)的时间内返回正确的数字,然后算数组中每个数组与其的差的绝对值累加即可,参见代码如下:

解法三:

class Solution {
public:
int minMoves2(vector<int>& nums) {
int res = , n = nums.size(), mid = n / ;
nth_element(nums.begin(), nums.begin() + mid, nums.end());
for (int i = ; i < n; ++i) {
res += abs(nums[i] - nums[mid]);
}
return res;
}
};

下面这种方法是改进版的暴力破解法,它遍历了所有的数字,让每个数字都当作最后相等的值,然后算法出来总步数,每次和res比较,留下较小的。而这种方法叼就叼在它在O(1)的时间内完成了步数统计,那么这样整个遍历下来也只是O(n)的时间,不过由于还是要给数组排序,所以整体的时间复杂度是O(nlgn),这已经能保证可以通过OJ啦。那么我们来看看如何快速计算总步数,首先我们给数组排序,我们假设中间某个位置有个数字k,那么此时数组就是:nums[0], nums[1], ..., k, ..., nums[n - 1], 如果i为数字k在数组中的坐标,那么有k = nums[i],那么总步数为:

Y = k - nums[0] + k - nums[1] + ... + k - nums[i - 1] + nums[i] - k + nums[i + 1] - k + ... + nums[n - 1] - k

= i * k - (nums[0] + nums[1] + ... + nums[i - 1]) + (nums[i] + nums[i + 1] + ... + nums[n - 1]) - (n - i) * k

= 2 * i * k - n * k + sum - 2 * curSum

那么我们只要算出sum和curSum就可以快速得到总步数了,数组之和可以通过遍历数组计算出来,curSum可以在遍历的过程中累加,那么我们就可以算出总步数,然后每次更新结果res了,参见代码如下:

解法四:

class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end());
long long sum = accumulate(nums.begin(), nums.end(), );
long long res = LONG_MAX, curSum = ;
int n = nums.size();
for (int i = ; i < n; ++i) {
long long k = nums[i];
curSum += k;
res = min(res, * k * (i + ) - n * k + sum - * curSum);
}
return res;
}
};

类似题目:

Minimum Moves to Equal Array Elements

Best Meeting Point

参考资料:

https://discuss.leetcode.com/topic/68764/5-line-solution-with-comment

https://discuss.leetcode.com/topic/68884/c-average-o-n-nth_element-solution

https://discuss.leetcode.com/topic/68736/java-just-like-meeting-point-problem

https://discuss.leetcode.com/topic/68900/simple-c-sort-and-find-solution-with-detailed-explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Minimum Moves to Equal Array Elements II 最少移动次数使数组元素相等之二的更多相关文章

  1. 462 Minimum Moves to Equal Array Elements II 最少移动次数使数组元素相等 II

    给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1. 您可以假设数组的长度最多为10000.例如:输入:[1,2,3]输出:2说明:只有两个动作是必 ...

  2. LeetCode Minimum Moves to Equal Array Elements II

    原题链接在这里:https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ 题目: Given a non-empt ...

  3. LeetCode Minimum Moves to Equal Array Elements

    原题链接在这里:https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ 题目: Given a non-empty i ...

  4. Leetcode-462 Minimum Moves to Equal Array Elements II

    #462.   Minimum Moves to Equal Array Elements II Given a non-empty integer array, find the minimum n ...

  5. 【LeetCode】462. Minimum Moves to Equal Array Elements II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:排序 方法二:直接找中位数 日期 题目地址: ...

  6. 【LeetCode】462. Minimum Moves to Equal Array Elements II

    Given a non-empty integer array, find the minimum number of moves required to make all array element ...

  7. [LeetCode] Minimum Moves to Equal Array Elements 最少移动次数使数组元素相等

    Given a non-empty integer array of size n, find the minimum number of moves required to make all arr ...

  8. [Swift]LeetCode462. 最少移动次数使数组元素相等 II | Minimum Moves to Equal Array Elements II

    Given a non-empty integer array, find the minimum number of moves required to make all array element ...

  9. 462. Minimum Moves to Equal Array Elements II

    Given a non-empty integer array, find the minimum number of moves required to make all array element ...

随机推荐

  1. 在mongoose中使用$match对id失效的解决方法

    Topic.aggregate( //{$match:{_id:"5576b59e192868d01f75486c"}}, //not work //{$match:{title: ...

  2. 如果你也会C#,那不妨了解下F#(4):了解函数及常用函数

    函数式编程其实就是按照数学上的函数运算思想来实现计算机上的运算.虽然我们不需要深入了解数学函数的知识,但应该清楚函数式编程的基础是来自于数学. 例如数学函数\(f(x) = x^2+x\),并没有指定 ...

  3. 解决MyEclipe出现An error has occurred,See error log for more details的错误

    今晚在卸载MyEclipse时出现An error has occurred,See error log for more details的错误,打开相应路径下的文件查看得如下: !SESSION 2 ...

  4. js验证输入的是否是数字,小数保留几位小数

    1.验证方法 validationNumber(e, num)  e代表标签对象,num代表保留小数位数 function validationNumber(e, num) { -]+\.?[-]*$ ...

  5. VS2010 VS2012 VS2013 VS2015启动调试时老是提示正在下载公共符号

    VS2010 VS2012 VS2013 VS2015启动调试时老是提示正在下载公共符号,下载一些.dll文件,点取消后也能继续调试,但特别慢.解决方法:工具-选项,或者调试-选项和设置,将调试下的& ...

  6. 在docker容器中vi指令找不到

    在使用docker容器时,有时候里边没有安装vi,敲vi命令时提示说:vi: command not found,这个时候就需要安装vi,可是当你敲apt-get install vi命令时,提示: ...

  7. ActiveMQ(li)

    一.ActiveMQ 首先,ActiveMQ不是一个框架,它不是struct,webx,netty这种框架,它更像是tomcat服务器,因为你使用它之前必须启动它,activeMQ和JMS的关系有点类 ...

  8. Java多线程整理(li)

    目录: 1.volatile变量 2.Java并发编程学习 3.CountDownLatch用法 4.CyclicBarrier使用 5.BlockingQueue使用 6.任务执行器Executor ...

  9. iOS 中的 HotFix 方案总结详解

    相信HotFix大家应该都很熟悉了,今天主要对于最近调研的一些方案做一些总结.iOS中的HotFix方案大致可以分为四种: WaxPatch(Alibaba) Dynamic Framework(Ap ...

  10. [C#6] 1-using static

    0. 目录 C#6 新增特性目录 1. 老版本的代码 1 using System; 2 3 namespace csharp6 4 { 5 internal class Program 6 { 7 ...