LintCode Remove Duplicates from Sorted Array II 删除排序数组中的重复数字 II

98 篇文章 0 订阅
17 篇文章 0 订阅

中文描述:

跟进“删除重复数字”:
如果可以允许出现两次重复将如何处理?

样例
给出数组A =[1,1,1,2,2,3],你的函数应该返回长度5,此时A=[1,1,2,2,3]。

English Version:

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

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        if(null == nums || nums.length == 0) return 0;
        if(nums.length == 1) return 1;
        int len = nums.length;
        int count = 1;
        for(int i = 0, j = 1; i <= j && j < nums.length; ) {
            if(nums[i] != nums[j]) {//两元素不同时,将后指针指向元素放至前指针指向元素的下一顺位,两指针顺次后移,count置为1。
                nums[i+1] = nums[j];
                i++;
                j++;
                count = 1;
            }else if(nums[i] == nums[j] && ++count > 2){//两元素相同且加上后指针指向元素,连续相同元素个数大于2,后指针后移,总长度减一。
                j++;
                count--;//恢复count值
                len--;
            }else {//两元素相同,但加上后指针指向元素,连续相同元素个数小于等于2,count加一,后指针指向元素放至前指针指向元素的下一位置,两指针顺次后移。
                count++;
                nums[i+1] = nums[j];
                i++;
                j++;
            }
        }
        return len;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值