Leetcode 26. Remove Duplicates from Sorted Array
You are given a sorted array nums
of integers. Your task is to remove the duplicates in-place such that each element appears only once and returns the new length of the array. The relative order of the elements should be kept the same.
You must implement the solution with O(1) extra memory.
Example:
Input: nums = [1, 1, 2]
Output: 2, nums = [1, 2, _]
(Note: “_” represents an irrelevant element beyond the returned length)
Q: Can the input array be empty? A: Yes, the input array can be empty.
Q: What values can the elements in the array take? A: The elements in the array are integers and can be positive, negative, or zero.
Q: Should the solution alter the input array in any particular way regarding the unused elements? A: No specific values are required for the elements beyond the returned length. They can remain as they are or be replaced by any value.
j
) will iterate over the array, while the other pointer (i
) will track the position of the unique elements.i
will only increment when a new unique element is found by the j
pointer.j
pointer will be copied to the i
position when a unique element is encountered.i + 1
will give us the length of the unique elements.This approach maintains the O(1) extra space constraint.
public 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;
}
}
j
pointer.i
and j
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?