您的位置:首页 > 其它

[LeetCode]Remove Duplicates from Sorted Array II

2014-05-07 14:57 471 查看

题目描述

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的部分删除,返回新数组的长度

解题思路

我们只需分段求解,记录每一段元素的个数,对个数>=2和<2进行讨论,同时使用一个变量lastPos(初始值为0)来记录上一个无重复元素的位置:

Duplicates>=2: A[lastPos] = compareVal; A[lastPos + 1] = compareVal; lastPos += 2;

Duplicates<2: A[lastPos] = compareVal; lastPos += 1;

代码

public static int removeDuplicates(int[] A) {
if (A == null || A.length == 0)
return 0;
if (A.length == 1)
return 1;

int dup = 0;
int lastPos = 0;
int compareVal;
for (int i = 0; i < A.length;) {
dup = 0;
compareVal = A[i];
while (i < A.length && A[i] == compareVal) {
i++;
dup++;
}

if(dup >= 2){
A[lastPos] = compareVal;
A[lastPos + 1] = compareVal;
lastPos += 2;
} else {
A[lastPos] = compareVal;
lastPos += 1;
}
}

return lastPos;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: