-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMinimum Increment to Make Array Unique.java
54 lines (42 loc) · 1.17 KB
/
Minimum Increment to Make Array Unique.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public int minIncrementForUnique(int[] nums) {
//Approach - 1 : Using a Count array
// TC : O(N)
// SC : O(N)
int max = 0;
for(int i : nums)
max = Math.max(max, i);
int count[] = new int[nums.length + max];
for(int c : nums)
count[c]++;
int answer = 0, choosen = 0;
int len = count.length;
for(int i = 0; i< len; i++)
{
if(count[i] >= 2)
{
choosen += count[i] - 1;
answer -= i * (count[i] - 1);
}
else if(choosen > 0 && count[i] == 0)
{
answer += i;
choosen--;
}
}
return answer;
//Approach - 2:
// TC : O(nlogn)
// SC : O(1)
Arrays.sort(nums);
int answer = 0;
for(int i=1; i<nums.length; i++)
{
if(nums[i-1] >= nums[i]){
answer += nums[i-1]- nums[i] +1;
nums[i] = nums[i-1] + 1;
}
}
return answer;
}
}