112th LeetCode Weekly Contest Minimum Increment to Make Array Unique

Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1.

Return the least number of moves to make every value in A unique.

Example 1:

Input: [1,2,2]
Output: 1
Explanation:  After 1 move, the array could be [1, 2, 3].

Example 2:

Input: [3,2,1,2,1,7]
Output: 6
Explanation:  After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.

Note:

  1. 0 <= A.length <= 40000
  2. 0 <= A[i] < 40000

问的是把数组的数字+1,几次后,数组的数字唯一了。

这里有个解法,把重复的拿出来,从小到大排序。从[min,max](max不一定就是代码的那个),哪个位置缺了就填哪个,然后算sum +=(i-ans);

其实优雅的解法应该是第二个

class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
        int sum = 0;
        int ans = 0;
        int pos = 0;
        int Min = 40000;
        map<int,int> mp;
        stack<int>st;
        vector<int>ve;
        for(int i=0;i<A.size();i++){
            Min = min(Min,A[i]);
            mp[A[i]]++;
            
            if(mp[A[i]]>=2){
                ve.push_back(A[i]);
            }
        }
        sort(ve.begin(),ve.end());
        for(int i=ve.size()-1;i>=0;i--){
            st.push(ve[i]);
        }
        for(int i=0;i<400000;i++){
            if(st.empty()){
                break;
            }
            if(mp[i]==0){
                ans = st.top();
                if(i<ans){
                    continue;
                }
                sum +=(i-ans);
                st.pop();
                mp[i]=1;
            }
        }
        return sum;
    }
};
class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
        sort(A.begin(), A.end());
        int lowest = -1, total = 0;

        for (int a : A) {
            lowest = max(lowest, a);
            total += lowest - a;
            lowest++;
        }

        return total;
    }
};

猜你喜欢

转载自www.cnblogs.com/yinghualuowu/p/10020188.html