Leetcode[26, 80] Remove Duplicates from Sorted Array
06 Nov 2015###Task1 Given a sorted array, 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 in place with constant memory.
For example, Given input array 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.
###Python
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums)
ind = 1
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
continue
nums[ind] = nums[i]
ind += 1
return ind
###Java
public class Solution {
public int removeDuplicates(int[] nums) {
//edge cases
if (nums.length < 2) return nums.length;
int index = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]) {
nums[index] = nums[i];
index++;
}
}
return index;
}
}
###Task2 Follow up for “Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
###Python
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == None or len(nums) == 0:
return
cur = nums[0]
count = 1
ind = 1
for i in range(1, len(nums)):
if nums[i] == cur and count >= 2:
continue
elif nums[i] == cur and count == 1:
count += 1
nums[ind] = nums[i]
ind += 1
else:
cur = nums[i]
nums[ind] = nums[i]
count = 1
ind += 1
return ind
###Java
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int idx = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
count++;
if (count > 2) {
continue;
}
} else {
count = 1;
}
nums[idx++] = nums[i];
}
return idx;
}
}
###Points
- Two pointers
- Check for duplicate first and continue, otherwise copy the number pointed by second pointer to the position pointed by first pointer