【LeetCode 945】 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:

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

思路

用一個cur標記當前增長到的位置,到下一個數字的時候,如果大於當前位置,更新cur。否則說明之前的數字增長到當前數字以後了,當前數字增長到cur,累加res。

代碼

class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
        if (A.empty()) return 0;
        
        int res = 0;
        sort(A.begin(), A.end());
        int n = A.size();
        
        int cur = A[0]+1;
        for (int i=1; i<n; ++i) {
            if (A[i] > cur) {
                cur = A[i] + 1;
            }else {
                res += cur - A[i];
                cur += 1;
            }
        }
        
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章