leetcode 453. 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 array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input: [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
纯数学题,面积法求解!!!
class Solution(object): def minMoves(self, nums): """ :type nums: List[int] :rtype: int """ # [1]=>0 # [1,2]=>[2,2]=>1 # [1,3]=>[2,3]=>[3,3]=>2 # [1,2,3]=>[2,3,3]=>[3,4,3]=>[4,4,4]=>3 # [1,2,4]=>[2,3,4]=>[3,4,4]=>[4,5,4]=>[5,5,5]=>4 # ans = final_max-orig_min # greedy???dp???iter??? """ let’s define sum as the sum of all the numbers, before any moves; minNum as the min number int the list; n is the length of the list; After, say m moves, we get all the numbers as x , and we will get the following equation sum + m * (n - 1) = x * n and actually, x = minNum + m and finally, we will get sum - minNum * n = m So, it is clear and easy now. """ return sum(nums) - min(nums) * len(nums)
另外一种思路就是:逆向思维!
Adding 1
to n - 1
elements is the same as subtracting 1
from one element, w.r.t goal of making the elements in the array equal.
So, best way to do this is make all the elements in the array equal to the min
element.
sum(array) - n * minimum
最后就是DP,先看暴力解法,因为每次move最少的次数为max-min,?
code like below:
public int minMoves(int[] nums) {
int res = 0;
int n = nums.length;
Arrays.sort(nums);
while (nums[n - 1] != nums[0]) {
int dis = nums[n - 1] - nums[0];
for (int i = 0; i < n - 1; i++) {
nums[i] += dis;
}
res += dis;
//insert sort
int max = nums[n - 1];
int i = n - 2;
while (i >= 0) {
if (nums[i] > max) nums[i + 1] = nums[i--];
else break;
}
nums[i + 1] = max;
}
return res;
}
But it still Time Limit Exceeded
.
============== The final solution is as follows ==============
The final flash, I though that should we use dynamic programming
?
[step] is The number of steps arrive at the state of [all equal]
[finalNum] is The value of the state of [all equal]
we can know that
step[i] = (step[i-1] + num[i]) - finalNum[i-1] + step[i-1]
finalNum[i] = num[i] + step[i-1]
public int minMoves(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int step = 0;
int finalNum = nums[0];
for (int i = 1; i < n; i++) {
int tmp = finalNum;
finalNum = nums[i] + step;
if (finalNum == tmp) continue; //attention!!
step = finalNum - tmp + step;
}
return step;
}
标签:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-03-25 es的forcemerge——按照天分割
2017-03-25 facebook Presto SQL分析引擎——本质上和spark无异,分解stage,task,MR计算
2017-03-25 吃CPU的openmp 程序