Remove Duplicates from Sorted Array
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.
难度:easy
Solution: Two Pointers
检查每一个元素,看是否和上个元素重复。
public class Solution {
public int removeDuplicates(int[] nums) {
int j = 0;
for(int i = 1; i < nums.length; ++i) {
if(nums[i] != nums[j]) {
nums[++j] = nums[i];
}
}
return ++j;
}
}
Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
在允许存在k个copy的情况下,用一个变量暂存元素出现的次数,当次数达到时,不要在存重复的元素。
难度:medium
Solution: Two Pointers
public class Solution {
public int removeDuplicates(int[] nums) {
int duplicates = 1; // there is a copy already
int j = 0;
for(int i = 1; i < nums.length; ++i) {
if(nums[i] == nums[j]) {
if(duplicates != 2) {
nums[++j] = nums[i];
duplicates += 1;
}
} else {
nums[++j] = nums[i];
duplicates = 1; // there is a copy already
}
}
return ++j;
}
}
Remove Element
Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length.
难度:easy
Solution: Two Pointers
这道题的解法和上道题一样,遍历每个元素,检查是否和目标元素相等。
public class Solution {
public int removeElement(int[] nums, int val) {
int j = -1;
for(int num : nums) {
if(num != val) {
nums[++j] = num;
}
}
return ++j;
}
}