美文网首页
[Day1]26. Remove Duplicates from

[Day1]26. Remove Duplicates from

作者: Shira0905 | 来源:发表于2017-01-30 23:54 被阅读0次

    Problem Description:
    Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
    Do not allocate extra space for another array, you must do this in place with constant memory.
    For example,Given input array nums = [1,1,2]
    Your function should return length = 2, with the first two elements of nums being 1
    and 2 respectively. It doesn't matter what you leave beyond the new length.

    At first, I didn't notice that the given array is "sorted", so it is a bit harder. My solution of sorted array use 17ms, while top solution takes 13ms.
    But, learn more from my "mistake", it is more helpful to solve the unsorted one.

    public static int removeDuplicatesUnsorted(int[] nums) {
        int l=nums.length;
        for(int i=0;i<nums.length-1;){
            int same=0;
            for(int j=i+1;j<nums.length;j++){
                if(nums[i]==nums[j]){
                    int temp=nums[j];
                    nums[j]=nums[i+1+same];
                    nums[i+1+same]=temp;
                    same++;
                    l--;
                }
            }
            i=i+same+1;
        }
        return l;
    }
    
    public static int removeDuplicates(int[] nums) {
        int l=1;
        if(nums.length==0)
            return 0;
        for(int i=1;i<nums.length;i++){
            if(nums[i]!=nums[i-1]){
                nums[l]=nums[i];
                l++;
            }
        }
        return l;
    }
    

    top solution :

    public int removeDuplicatesTop(int[] A) {
        if (A.length==0) return 0;
        int j=0;
        for (int i=0; i<A.length; i++)
            if (A[i]!=A[j]) A[++j]=A[i];
        return ++j;
    }

    相关文章

      网友评论

          本文标题:[Day1]26. Remove Duplicates from

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