首页 > 其他 > 详细

Leetcode Remove Duplicates from Sorted Array II

时间:2015-04-14 00:40:32      阅读:213      评论:0      收藏:0      [点我收藏+]

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

 

Leetcode Remove Duplicates from Sorted Array II

原文:http://www.cnblogs.com/xiongyuesen/p/4423713.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!