453. Minimum Moves to Equal Array Elements

 问题来源:https://leetcode.com/problems/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]

我的代码:

1)首先花了几分钟理解题意:给出一个整数非空数组,每次使得其中n-1个数字+1(n为数组长度)问最少几次使得数组中的每个数据相等?

2)其次既然询问最少次数,我们观察例子中如何达到最少:每次选择的n-1个均避开当前数组中最大值。

3)如果在代码中将数组变换的中间结果列出,算法复杂度肯定较大,所以我们逆向思考:目的都是数组中每个数据彼此相等,那么每次使得其中1个数据-1,最终达到目的 与题意的moves相同。

4)3)中的思路可以转换为数组中的每个非最小值到最小值的次数,则moves += !min[i] - min。同样可以转换为数组的sum - min*n

int minMoves(vector<int> &nums){
	int sum = 0;
	int min = INT_MAX;
	for (int i = 0; i < nums.size(); i++){
		if (nums[i] < min){
			min = nums[i];
		}
		sum += nums[i];
	}
	return sum - min*nums.size();
}

  所以遇到较为复杂的问题可以先使用其他方法将其简化,逆向思考是个很不错的选择~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值