LeetCode 453. Minimum Moves to Equal Array Elements

来源:互联网 发布:21天学通c语言电子版 编辑:程序博客网 时间:2024/04/30 13:24

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-1个数相加,所以比最小的数min大的那些数,始终比min大相同的值,直到它们相同。所以结果是所有比min大的值累加。

class Solution {public:    int findMinindex(vector<int>& nums){        int len = nums.size();        int min = INT_MAX;        int minindex = 0;        int i;        for(i = 0; i < len; i ++){            if(min > nums[i]){                min = nums[i];                minindex = i;            }        }        return minindex;    }       int minMoves(vector<int>& nums) {        int len = nums.size();        int minindex = findMinindex(nums);        int count = 0;        int i;        for(i = 0; i < len; i ++){            count += nums[i] - nums[minindex];        }        return count;            }};


0 0
原创粉丝点击