美文网首页
Remove Duplicate2

Remove Duplicate2

作者: 夏的背影 | 来源:发表于2017-03-28 19:05 被阅读16次

    question:

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

    answer:

    public class removeDuplicateTwo {
    
        public static int removeDuplicateTwo(int[] array) {
            if (array.length == 0) return 0;
            int j =0;
            int count =0;
            for(int i = 1;i<array.length;i++){
                if(array[j]==array[i]){
                    count++;
                    if (count<2){
                        j++;
                        array[j]=array[i];
                    }
                }else {
                    j++;
                    array[j]=array[i];
                    count = 0;
                }
            }
            return j+1;
        }
        
        public static void main(String[] args){
            int[] array1={1,1,1};
            int length =removeDuplicateTwo(array1);
            for (int i=0;i<length;i++){
                System.out.println(array1[i]);
            }
            System.out.println("this array length is "+length);
        }
    
    }
    

    相关文章

      网友评论

          本文标题:Remove Duplicate2

          本文链接:https://www.haomeiwen.com/subject/wvcsottx.html