26. Remove Duplicates from Sorted Array (Easy) Facebook Microsoft Bloomberg
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 by modifying the input array in-place with 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.
Solution 1: 同向Two Pointers O(n); O(1) Template
/**
* Template 同向Two Pointers O(n);O(1)
* Use the length to be returned as a pointer to the next position to be filled.
* For each number n in nums:
* | If length is 0 or n > nums[length - 1]:
* | Update nums[length] to n. Increment length by 1.
* Return length.
*/
public int removeDuplicates(int[] nums) {
if (nums == null) {
return -1;
}
int len = 0;
for (int num : nums) {
if (len < 1 || num > nums[len - 1]) {
nums[len++] = num;
}
}
return len;
}
Template can also be used in 27. Remove Element
public int removeElement(int[] nums, int val) {
if (nums == null) {
return -1;
}
int len = 0;
for (int num : nums) {
if (num != val) {
nums[len++] = num;
}
}
return len;
}
Follow Up:
- Erase duplicate in an unsorted array
hash map和sort两种方法都可以 O(n);O(n), O(nlogn);O(1)