前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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]这个题目其实就是每次每个数只可以减1,然后求最小步数。时间复杂度O(n)遍历一次即可。 Your runtime beats 67.89% of java submissions.
public class Solution {
public int minMoves(int[] nums) {
if(nums.length == 0) return 0;
int minNumber = nums[0],result = 0;
for(int i = 0 ; i < nums.length ; i++){
int item = nums[i];
if(item < minNumber) {result += (minNumber - item) * i;minNumber = item; }
else result += item - minNumber;
}
return result;
}
}