Leetcode Remove Duplicates from Sorted Array II

题目地址: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;
    }
}

 

posted @ 2015-04-14 00:03  buptubuntu  阅读(102)  评论(0)    收藏  举报