Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicatesin-placesuch that each element appear onlyonceand return the new length.
Do not allocate extra space for another array, you must do this bymodifying the input arrayin-placewith O(1) extra memory.
Example:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.
图解
分析
- two pointers : slow and fast, initially to be 1
- scan the array from index 1 to rightmost using fast pointer, when nums[fast] is not equal to nums[fast-1], we assign nums[fast] to nums[slow] and increment slow
代码
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int slow = 1;
for(int i = 1; i< nums.length ; i++){
if(nums[i]!=nums[i-1]){
nums[slow]=nums[i];
slow ++;
}
}
return slow;
}
}