[LeetCode] 453. Minimum Moves to Equal Array Elements

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.

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

Constraints:

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

最小移动次数使数组元素相等。

给你一个长度为 n 的整数数组,每次操作将会使 n - 1 个元素增加 1 。返回让数组所有元素相等的最小操作次数。

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

这道题给的是一个数组,里面的数字不尽相同。假设数组里有N个数字,有一个最大数字 max。找到让数组所有元素相等的最小移动次数。每次移动将会使 N - 1 个元素增加 1。

首先讲一下直观的思路。首先找出数组中最大的数字这不难,然后直接将剩下的数字每次 +1。同时,还需要在每一轮 +1之后再次检查最大值是否有变化。这样做虽然直观但是会超时。

一个巧妙的思路是,给 n - 1 个数字加 1,效果等同于给那个未被选中的数字减 1。所以问题也可转化为,将所有数字都减小到最小值需要几步。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int minMoves(int[] nums) {
 3         int min = Integer.MAX_VALUE;
 4         int res = 0;
 5         for (int num : nums) {
 6             min = Math.min(min, num);
 7         }
 8         for (int num : nums) {
 9             res += num - min;
10         }
11         return res;
12     }
13 }

 

LeetCode 题目总结

posted @ 2020-09-04 04:36  CNoodle  阅读(227)  评论(0编辑  收藏  举报