LeetCode 945. 使数组唯一的最小增量

问题描述:

给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1

返回使 A 中的每个值都是唯一的最少操作次数。

class Solution {
public:
	int minIncrementForUnique(vector<int>& A) {
		int L = A.size();
		if (L == 0 || L == 1)
			return 0;
		int num_unmoved = 0; //需要移动但还没有移动的数量
		int unmoved_total = 0; 
		int can_moved_total = 0; 
		sort(A.begin(), A.end());
		int temp;
		int num_move;
		for (int i = 1; i < L; i++) {
			temp = A[i] - A[i - 1] - 1;
			if (temp == -1) {//如果上一个数相等,就累计num_umoved和unmoved_total
				num_unmoved++;
				unmoved_total += A[i];
			}
			if (temp > 0) { //如果和上一个数有间隙,就减少num_unmoved并累计can_moved_total
				if (num_unmoved > 0) {
					num_move = min(num_unmoved, temp);
					num_unmoved -= num_move;
					can_moved_total += (A[i - 1] + num_move + A[i - 1] + 1) * num_move / 2;
				}
			}
		}
		return can_moved_total - unmoved_total + (A[L-1] + num_unmoved + A[L-1] + 1) * num_unmoved / 2;
	}
};

  P.S. 需要注意的是一定要单独处理一下输入vector为空的情况,否则最后调用A[L-1]计算结果时会出错。

猜你喜欢

转载自www.cnblogs.com/airfy/p/12544490.html