题目:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
解题思路:
设置两个指针i和j,i记录去掉重复后的位置,j记录当前移动位置。时间复杂度O(n).
代码:
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int i = 1;
int j = 1;
while (j < nums.length) {
if (nums[j] != nums[j - 1]) {
nums[i++] = nums[j++];
} else {
j++;
}
}
return i;
}
题目2:
还是上面的,不同的是允许元素最多出现两次,多于两次的把其余的删除掉。
解题思路:
还是设置两个指针i和j,含义不变,只是设置一个cnt值,当值重复的时候用来计算值重复的次数。这是时间复杂度为O(n)的解法,
代码:
public int removeDuplicates(int[] nums) {
if (nums == null ) {
return 0;
}
if (nums.length == 0 || nums.length == 1) {
return nums.length;
}
int i = 1; //记录实际位置
int j = 1; //记录前面移动的位置
int cnt = 1;
while (j < nums.length) {
if (nums[j] != nums[j - 1]) {
cnt = 1;
nums[i++] = nums[j];
} else {
//判断重复的个数是否超过2
if (cnt < 2) {
//没有超过,继续按照上面的方法移动
//同时cnt 值增加
nums[i++] = nums[j++];
cnt += 1;
} else {
j++;
}
}
}
//因为上面一直是i++,所以返回i
//而不是i+1
return i;
}
-----------EOF-----------