453. Minimum Moves to Equal Array Elements
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]
Seen this question in a real interview before?
Yes
题意:
给你一个有n个数的数组。每次给n-1个数加一,直到所有的数相等,求这个最小的步数
算法思路:
为了求最小的步数,所以每次肯定是给除了最大的那个数+1,这就相当于每次给最大的数-1,直到大家都和最小的数相等
所以遍历数组中的元素,求出来最小值,然后数组中每个数和最小值之间的差值的和就是最短的步数
代码:
package easy;
public class MinimumMovestoEqualArrayElements {
public int minMoves(int[] nums) {
int min = nums[0];
int sum = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] < min){
min = nums[i];
}
sum += nums[i];
}
return sum - min*nums.length;
}
}