问题描述
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input: [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]
测试用例
- n的长度为1
- n所有元素相等
- [1,2,3]
问题分析
- 第一遍:将所有的n-1个元素加一等价于将另一个元素减一,故而最小步骤即为所有元素与最小值元素之差的和。
class Solution { public int minMoves(int[] nums) { if(nums.length <= 1) return 0; int min = Integer.MAX_VALUE; for(int i = 0; i < nums.length; i++){ if(nums[i] < min){ min = nums[i]; } } int res = 0; for(int i = 0; i < nums.length; i++){ res += nums[i] - min; } return res; } }
-
class Solution { public int minMoves(int[] nums) { if(nums.length <= 1) return 0; int min = Integer.MAX_VALUE; int sum = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] < min){ min = nums[i]; } sum += nums[i]; } return sum - nums.length * min; } }