Given a sorted array, remove the duplicates in place such that each element appear only onceand 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 A =[1,1,2],
Your function should return length =2, and A is now[1,2].
1)使用set进行一重筛选后将数组中元素进行修改
class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int count = 0;
Set<Integer> set = new HashSet<>();
for(int i = 0 ; i < nums.length ; i++){
if(!set.contains(nums[i])){
nums[count++] = nums[i];
set.add(nums[i]);
}
}
return count;
}
}
2)使用双指针进行标记,比较奇妙(100%)
public class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
for(int j = 1; j < nums.length;j++){
if(nums[j] != nums[i]){
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
}