题目: leetcode链接
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,每次选n-1个小数字+1,问:进行几步所有的数字可以一致。
解题思路:
小的n-1数+1,相当于每次最大的数 -1 ,所有只需要计算每个数和最小的数之差
代码实现:
public class Solution {
public int minMoves(int[] nums) {
int result = 0;
int min_num = Integer.MAX_VALUE;
for (int i : nums) {
if(i < min_num){
min_num = i;
}
}
for (int i : nums) {
result += (i - min_num);
}
return result;
}
}
分析:代码时间复杂度为O(2*n)