Dare2Solve
Given a sorted array, the task is to remove some duplicates in-place such that each unique element appears at most twice. Since the array is already sorted, duplicates will be adjacent. We need to ensure that we keep at most two occurrences of each element while maintaining the order of elements.
k
to 2, as the first two elements can always remain in the array.k - 2
. If they are different, it means we can include this element in the result.k
and increment k
.k
, which represents the number of elements in the modified array.The time complexity is O(n), where n
is the length of the array. This is because we iterate through the array once.
The space complexity is O(1) since we are modifying the array in place and not using any extra space that scales with the input size.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int count = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (nums[i] == nums[j] && j != i) {
++count; }}
if (count > 1) {
nums.erase(nums.begin() + i + 1, nums.begin() + i + count);
n -= count - 1; // Adjust the size of the array
}count = 0;
}
return nums.size();
}};
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
count = 0
n = len(nums)
i = 0
while i < n:
for j in range(n):
if nums[i] == nums[j] and j != i:
count += 1
if count > 1:
del nums[i + 1 : i + count]
n -= count - 1 # Adjust the size of the array
count = 0
i += 1
return len(nums)
class Solution {
public int removeDuplicates(int[] nums) {
int count = 0;
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (nums[i] == nums[j] && j != i) {
count++;
}}
if (count > 1) {
for (int k = i + 1; k + count - 1 < n; k++)
{nums[k] = nums[k + count - 1];}
n -= count - 1;
}count = 0;
}
return n;
}}
var removeDuplicates = function(nums) {
let count = 0
console.log(nums)
for(let i = 0; i< nums.length; i++) {
for(let j = 0; j<nums.length; j++){
if(nums[i]==nums[j] && j !=i){
count++
}
}
if(count>1){
nums.splice(i+1,count-1)
}
count = 0
}
return nums.length
};