def removeDuplicates(nums):
if not nums:
return 0
i = 0
for j in range(1, len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
return i + 1
nums = [1, 1, 2, 2, 2, 3, 4, 5, 5]
print(removeDuplicates(nums))
Explanation (Python):
In Python, we can use two pointers, i and j, to keep track of the current and next distinct elements.
Initialize i to 0 since the first element is always unique.
Iterate through the array with j starting from index 1.
If nums[j] is different from nums[i], it means we have found a new distinct element. Increment i and update nums[i] with nums[j].
Continue the iteration until j reaches the end of the array.
Finally, return i + 1, which represents the length of the modified array with duplicates removed.
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
public static void main(String[] args) {
int[] nums = {1, 1, 2, 2, 2, 3, 4, 5, 5};
Solution solution = new Solution();
System.out.println(solution.removeDuplicates(nums));
}
}
Explanation (Java):
In Java, we use the same two-pointer approach as in Python.
Check if the length of nums is 0. If so, return 0 since there are no elements to remove.
Initialize i to 0.
Iterate through the array with j starting from index 1.
If nums[j] is different from nums[i], increment i and update nums[i] with nums[j].
Continue the iteration until j reaches the end of the array.
Finally, return i + 1, which represents the length of the modified array with duplicates removed.
#include <iostream>
#include <vector>
using namespace std;
int removeDuplicates(vector& nums) {
if (nums.empty()) {
return 0;
}
int i = 0;
for (int j = 1; j < nums.size(); j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
int main() {
vector nums = {1, 1, 2, 2, 2, 3, 4, 5, 5};
cout << removeDuplicates(nums) << endl;
return 0;
}
Explanation (C++):
In C++, we also follow the same two-pointer approach as in Python and Java.
Check if the nums vector is empty. If so, return 0 since there are no elements to remove.
Initialize i to 0.
Iterate through the vector with j starting from index 1.
If nums[j] is different from nums[i], increment i and update nums[i] with nums[j].
Continue the iteration until j reaches the end of the vector.
Finally, return i + 1, which represents the length of the modified vector with duplicates removed.
I hope this explanation helps! Let me know if you have any further questions.