leetCode 80.Remove Duplicates from Sorted Array II (删除排序数组中的重复II) 解题思路和方法

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

思路:本题允许数组最多有两个重复,所以需要加一个判断,是否到两个。具体代码如下:

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length <= 2){//长度小于2,直接返回
            return nums.length;
        }
        
        boolean isTwice = false;//是否两次
        int len = 0;//最新长度
        for(int i = 0; i < nums.length; i++){//遍历
        	//不等于最后一个切数字相等
            if(i != nums.length -1 && nums[i+1] == nums[i]){
                if(!isTwice){//还没两次
                    isTwice = true;
                    nums[len++] = nums[i];  //添加到数组最前
                }
            }else{//不相等
            	isTwice = false;//标记为不是两次
                nums[len++] = nums[i];//添加最前
            }
        }
        return len;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值