453. Minimum Moves to Equal Array Elements

1. Question

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment n - 1 elements of the array by 1.

2. Examples

Example 1:

Input: nums = [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]

Example 2:

Input: nums = [1,1,1]
Output: 0

3. Constraints

  • n == nums.length
  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • The answer is guaranteed to fit in a 32-bit integer.

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

n-1个元素增加1,相当于1个元素减少1.

那么,找到数组中最小的数,将每个元素的值和这个最小的数做差,和的结果就是题解。

class Solution {
  public int minMoves(int[] nums) {
    int min = Arrays.stream(nums).min().getAsInt();
    int res = 0;
    for (int i = 0; i < nums.length; i++) {
      res += nums[i] - min;
    }
    return res;
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2022-05-18 16:24:00

results matching ""

    No results matching ""