453. Minimum Moves to Equal Array Elements

来源:互联网 发布:日本公安知乎 编辑:程序博客网 时间:2024/06/05 07:25
/*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:3Explanation: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,求最少需要多少步,能使数组中的数字全部相同。分析若使数组尽快满足题目要求,则需要每次给除去最大值的其余数字加1,但这种方法效率过低,可以换一种思路。每次将数组中的n-1个数字加1,相当于将剩余的一个数字减1。所以只需找到数组中的最小值m,计算m与数组中其他数字差的累计和即可。*///16ms  51% int minMoves(int* nums, int numsSize) {    int i, count = 0, min = 2147483647;    for( i=0; i<numsSize; i++)        if(min > nums[i])            min = nums[i];        for( i=0; i<numsSize; i++)        count = count + nums[i] - min;    return count;}