26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being1 and
2 respectively. It doesn't matter what you leave beyond the new length.
注意考虑清楚为啥循环else先pre++??
最后为啥返回pre+1???
public int removeDuplicates(int[] A) {
if (A.length <= 1)
return A.length;
int prev = 0; // point to previous
int curr = 1; // point to current
while (curr < A.length) {
if (A[curr] == A[prev]) {
curr++;
} else {
prev++;
A[prev] = A[curr];
curr++;
}
}
return prev + 1;
}改进版
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int i = 0;
for (int n : nums) {
// i<1代表第一个元素,
// 当n>nums[i-1]代表不等,可以赋值,并且i++
if (i < 1 || n > nums[i - 1])
nums[i++] = n;
}
return i;
}
80. Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
Given sorted array nums = [1,1,1,2,2,3],
For example,
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.
同上一题的方法一
public int removeDuplicates(int[] A) {
if (A.length <= 2)
return A.length;
int prev = 1; // point to previous
int curr = 2; // point to current
while (curr < A.length) {
if (A[curr] == A[prev]
&& A[curr] == A[prev - 1]) {
curr++;
} else {
prev++;
A[prev] = A[curr];
curr++;
}
}
return prev + 1;
}
同上一题的方法二
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int i = 0;
for (int n : nums) {
//////////////////////
//不同点
if (i < 2 || n > nums[i - 2])
nums[i++] = n;
}
return i;
}
本文探讨了LeetCode中的26题和80题,涉及如何在有序数组中移除重复元素。在原地操作数组,不使用额外空间,详细解释了解题思路和代码实现,包括两种不同情况:重复元素最多出现两次的情况。

373

被折叠的 条评论
为什么被折叠?



