您的位置:首页 > 其它

Leetcode Remove Duplicates from Sorted Array II

2015-04-14 00:03 369 查看
题目地址:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

题目解析:首先需要一个数组下标用于遍历数组元素;同时在遍历的过程中需要把个数大于2的数字只保留2个,也就是说需要把数组后面的元素往前移,也就是说需要维护一个数组下标,表示后面元素的插入位置;在遍历过程中需要保存当前找到的数字,和之前找到的数字,同时记录数字重复出现的次数,如果一个数字重复次数小于两次则将其直接插入到数组前面(插入索引指向的位置),同时插入索引加1,如果大于两次了,则不插入,插入索引同样不变;一旦发现新元素则将计数器置为1。

题目解答:

public class Solution {
public int removeDuplicates(int[] A) {
if(A == null || A.length == 0){
return 0;
}

int count = 1;
int curr = A[0];
int insertIndex = 1;
int foundIndex = 1;
while(foundIndex < A.length){
if(count < 2){
A[insertIndex++] = A[foundIndex];
if (curr == A[foundIndex]) {
count++;
}else {
count = 1;
curr = A[foundIndex];
}
}else {
if (curr != A[foundIndex]){
A[insertIndex++] = A[foundIndex];
curr = A[foundIndex];
count = 1;
}
}
foundIndex++;
}
return insertIndex;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: