首页 > 代码库 > Remove Duplicates from Sorted Array II leetcode java
Remove Duplicates from Sorted Array II leetcode java
题目:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
题解:
之前是不允许有重复的。
现在是可以最多允许2个一样的元素。
然后删除duplicate,返回长度。
删除duplicate的方法就是指针的操作。具体方法见代码。
代码如下:
1 public int removeDuplicates(int[] A) {
2 if (A.length <= 2)
3 return A.length;
4
5 int prev = 1; // point to previous
6 int curr = 2; // point to current
7
8 while (curr < A.length) {
9 if (A[curr] == A[prev] && A[curr] == A[prev - 1]) {
10 curr++;
11 } else {
12 prev++;
13 A[prev] = A[curr];
14 curr++;
15 }
16 }
17
18 return prev + 1;
19 }
2 if (A.length <= 2)
3 return A.length;
4
5 int prev = 1; // point to previous
6 int curr = 2; // point to current
7
8 while (curr < A.length) {
9 if (A[curr] == A[prev] && A[curr] == A[prev - 1]) {
10 curr++;
11 } else {
12 prev++;
13 A[prev] = A[curr];
14 curr++;
15 }
16 }
17
18 return prev + 1;
19 }
Reference:http://www.programcreek.com/2013/01/leetcode-remove-duplicates-from-sorted-array-ii-java/
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。