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;
    }
}



你可能感兴趣的:(leetCode)