Remove Duplicates from Sorted Array
1 min readMar 18, 2019
Question: Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may view the full question here.
Approach:
Today, let’s just dive straight into the code.
//Approach
//Runtime: 5ms
//Memory usage: 40.4MBclass Solution {
public int removeDuplicates(int[] nums) {
if(nums.length==0){
return 0;
}
int currVacant = 1;
for(int i = 1; i<nums.length; i++){
if(nums[currVacant-1]!=nums[i]){
//Don't have to move the element,
//if it's already in the right position
if(currVacant!=i){
nums[currVacant] = nums[i];
}
currVacant++;
}
//Can skip redundantly checking
//the last set of duplicates all together
if(nums[i]==nums[nums.length-1]){
break;
}
}
return currVacant;
}
}
Find more posts here.
Cheers & Chao!