LeetCode 945. 使数组唯一的最小增量(贪心)

1. 题目

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

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

示例 1:
输入:[1,2,2]
输出:1
解释:经过一次 move 操作,数组将变为 [1, 2, 3]。

示例 2:
输入:[3,2,1,2,1,7]
输出:6
解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。
可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。

提示:
0 <= A.length <= 40000
0 <= A[i] < 40000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-increment-to-make-array-unique
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • map计数,遍历map,计数不为1的,将多余的加入下一个数里面
class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
    	map<int,int> m;
    	int count = 0;
    	for(int& a : A)
    		m[a]++;
    	for(auto& mi : m)
    	{
    		if(mi.second > 1)
    		{
    			count += mi.second-1;
    			m[mi.first+1] += mi.second-1;
    		}
    	}
    	return count;
    }
};

在这里插入图片描述

  • 排序后,需要比前面的大1
class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
        int count = 0;
        sort(A.begin(), A.end());
        for(int i = 1; i < A.size(); ++i)
        {
            if(A[i] <= A[i-1])
            {
                count += A[i-1]-A[i]+1;
                A[i] = A[i-1]+1;
            }
        }
        return count;
    }
};

在这里插入图片描述

发布了755 篇原创文章 · 获赞 939 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/105032960