945. Minimum Increment to Make Array Unique
給一個int array: nums,裡面的數字會重複,一動可以把一個nums[i] +1
return幾動可以讓所有數字不重複
絲路:
sort後比較 [i] <= [i-1]?
yes : [i] = [i-1] +1, ans增加 [i] - [i-1] +1
no : 8888
code:
class Solution {
public:
int minIncrementForUnique(vector<int>& nums) {
int ans = 0;
int len = nums.size();
sort(nums.begin(), nums.end());
for(int i = 1; i < len; i++)
{
if(nums[i] <= nums[i-1])
{
ans += (nums[i-1] - nums[i]) + 1;
nums[i] = nums[i-1] + 1;
}
}
return ans;
}
};