Easy
You are given an integer array nums
. You need to ensure that the elements in the array are distinct. To achieve this, you can perform the following operation any number of times:
Note that an empty array is considered to have distinct elements. Return the minimum number of operations needed to make the elements in the array distinct.
Example 1:
Input: nums = [1,2,3,4,2,3,3,5,7]
Output: 2
Explanation:
[4, 2, 3, 3, 5, 7]
.[3, 5, 7]
, which has distinct elements.Therefore, the answer is 2.
Example 2:
Input: nums = [4,5,6,4,4]
Output: 2
Explanation:
[4, 4]
.Therefore, the answer is 2.
Example 3:
Input: nums = [6,7,8,9]
Output: 0
Explanation:
The array already contains distinct elements. Therefore, the answer is 0.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int minimumOperations(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
int dupct = 0;
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
if (map.get(num) == 2) {
dupct++;
}
}
int n = nums.length;
int i = 0;
int op = 0;
while (dupct > 0) {
op++;
int limit = Math.min(n, i + 3);
for (; i < limit; i++) {
int val = map.get(nums[i]);
if (val == 2) {
dupct--;
}
map.put(nums[i], val - 1);
}
}
return op;
}
}