LeetCode/453. Minimum Moves to Equal Array Elements.md

18 lines
933 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```