26. Remove Duplicates from Sorted Array
Source link: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Design
As the problem stated that the the input array should be modified in-space with O(1) memory, extra space cannot be initiated for storing the data. To solve the problem, the two-pointer pattern can be applied for recording positions.
- Initialize two pointers i, j at the start of the array.
- Travel through the array nums leading by the pointer j and record the number preparing to be modified by the pointer i.
- Start the traverse process, once if the value of nums[j] != nums[i - 1] (the last modified element) or i = 0, modify the value of nums[i] to nums[j] and move the pointer i forward.
Implementation
class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (i == 0 || nums[j] != nums[i - 1]) {
nums[i++] = nums[j];
}
}
return i;
}
}
Complexity Analysis
Time: $O(n)$
Space: $O(1)$