您的位置:首页 > 其它

LeetCode--Remove Duplicates from Sorted Array II (数组操作)

2014-06-10 22:45 423 查看

题目Remove Duplicates from Sorted Array II

 Total
Accepted: 11947 Total
Submissions: 39572

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]
.

Have you been asked this question in an interview? 

解题思路:

注意这道题和LeetCode--
Remove Duplicates from Sorted Array (数组操作) 类似,但注意区别。简要分析见上面那个问题。

这里用index代替count,表意更清楚。

如下面源代码:若用A[i-2] != A[i] 来表示是否替换元素就会出问题,

比如例子中,当index=2, A[3] != A[1], 那么A[index] = A[3] (  A[2]==2了)导致A[5] == A[3],判断有误,A[3]的真值被覆盖(元素真值覆盖问题)。

这里就用到上面那道题里面的用需要替换的元素与后面元素比,避免这个问题,详见下面代码。

源代码:

Java源代码:

Perspective: 让前面的元素与后面的元素相比,巧妙避免了“元素真值覆盖问题(在数组内操作常见问题)”

public static int fun(int[] A) {
if (A.length <= 2) {
return A.length;
}
int index = 2;
for (int i = 2; i < A.length; ++i) {
if ( <span style="font-family: Arial, Helvetica, sans-serif;">A[index - 2]  !=  A</span>[i]) { //这里若用 A[i-2] != A[i] 就会出现问题
A[index++] = A[i];
}
}
return index;
}


相关题目:

LeetCode--
Remove Duplicates from Sorted Array (数组操作)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐