mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 453. Minimum Moves to Equal Array Elements.md
This commit is contained in:
parent
7d65e5f50a
commit
f3fddaeb8b
17
453. Minimum Moves to Equal Array Elements.md
Normal file
17
453. Minimum Moves to Equal Array Elements.md
Normal file
@ -0,0 +1,17 @@
|
||||
# [453. Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/)
|
||||
# 思路
|
||||
这题咋一看很吓人,因为每一步必须改变n-1个数而不是一个数,但是仔细分析发现由于最终的目标只是一个相对的(即所有元素相等)关系,所以将n-1个元素增加1与将1个元素减去1没有任何区别。
|
||||
所以这题就转换成每次将一个元素减1,需要进行多少次才能让所有元素相等。由于只能减,所以最终元素都应该变成原数组的最小值,而所求次数则是所有元素与最小值的差的和。
|
||||
时间复杂度O(n),空间复杂度O(1)
|
||||
# C++
|
||||
```
|
||||
class Solution {
|
||||
public:
|
||||
int minMoves(vector<int>& nums) {
|
||||
int min_num = nums[0], res = 0;
|
||||
for(int num: nums) min_num = min(num, min_num);
|
||||
for(int num: nums) res += (num - min_num);
|
||||
return res;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user