刷题No7. Remove Duplicates from Sorted Array II(java)【数组】

题目:

继续思考题目"Remove Duplicates":

如果数组中元素最多允许重复两次呢?

例如:

给出有序数组 A =[1,1,1,2,2,3],

你给出的函数应该返回length =5,  A 变为[1,1,2,2,3].

package com.company;

public class TestNo7 {
    public static void main(String[] args) {
        TestNo7 t = new TestNo7();
        int[] A1 = {1,1,2,2,2,3,4};
        int[] A2 = {1,2,4,0,0,0};
        System.out.println(t.removeDuplicates(A1));
        System.out.println(t.removeDuplicates(A2));

    }
    public int removeDuplicates(int[] A) {
        if(A == null){
            return 0;
        }else if(A.length <= 2){
            return  A.length;
        }
        int index = 1; //从1(也就是第二个数开始计数)
        boolean canFill = true;
        for(int i =1; i<A.length; i++){
            if(A[i-1] == A[i]){
                if(canFill){
                    A[index++] = A[i];
                    canFill = false;
                }
            }
            else{
                A[index++] = A[i];
                canFill = true;
            }
        }
        return index;

    }
}
发布了46 篇原创文章 · 获赞 11 · 访问量 3597

猜你喜欢

转载自blog.csdn.net/qq_40664693/article/details/103961701