# 453.Minimum Moves to Equal Array Elements

**453.Minimum Moves to Equal Array Elements**

难度:Easy

> 给定一个长度为 n 的非空整数数组，找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。

示例:

```
输入:
[1,2,3]

输出:
3
```

解释: 只需要3次移动（注意每次移动会增加两个元素的值）：

\[1,2,3] => \[2,3,3] => \[3,4,3] => \[4,4,4]

直观方法是将数组排序，然后每次将前面n-1个元素加1，如果碰到倒数第二个值大于最后一个值，则交换两个数，直到第一个数和最后一个数相等。但是会显示超时。\
另一个比较好的解决方法是从反面考虑，每次将n-1个元素加1，相当于将一个元素-1，之后整体相对大小关系不变。所以每个数减到和最小值相等即可。可以在线性时间内完成，时间复杂度是O(N)。

```
class Solution {
public:
    int minMoves(vector<int>& nums) {
        if(nums.size()==1) return 0;
        int res=0;
       int  minimum=*min_element(nums.begin(),nums.end());
        for(auto i: nums)
            res +=i-minimum;
        return res;
    }
};
```

> 执行用时 : 52 ms, 在Minimum Moves to Equal Array Elements的C++提交中击败了93.27% 的用户\
> 内存消耗 : 10.8 MB, 在Minimum Moves to Equal Array Elements的C++提交中击败了85.59% 的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/453.minimum_moves_to_equal_array_elements.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
