leetcode:Remove Duplicates from Sorted Array

来源:互联网 发布:照片变成手绘软件 编辑:程序博客网 时间:2024/06/08 15:37

Remove Duplicates from Sorted Array
question:
  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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].


solution 1
analyze:
  对数组遍历一边,并设置一个计数器。只有前后元素不相等的时候计数器才加1,并把计数器对应数组中的位置设置为当前遍历的元素
  

    /*removes duplicates from a sorted array     * @param A a sorted array     * @return the length of array     **/    public int removeDuplicates(int A[]){        if(A==null || A.length==0)            return 0;        int count=1;//设置计数器,第一个元素肯定不会重复,所以从1开始        for (int i = 1; i < A.length; i++) {            if(A[i]==A[i-1])//如果相等,就一直循环到不相等                continue;            else                A[count++] =A[i];//将计数器对应位置的数组值改为当前遍历值        }        return count;//返回数组长度    }

question 2:如果数组不是有序的,则要先排序。

    public int removeDuplicates(int A[]){        if(A==null || A.length==0)            return 0;        quickSort(A, 0, A.length-1);//快速排序        int count=1;//计数器        for (int i = 1; i < A.length; i++) {            if(A[i]!=A[i-1])//如果不相等                A[count++]=A[i];//更新数组,并计数器加一        }        return count;    }    private void  quickSort(int []table,int low ,int high){        if (low<high) {            int i=low,j=high;            int vot=table[i];            while (i!=j) {                while(i<j && vot<=table[j])                    j--;                if(i<j)                    table[i++]=table[j];                while(i<j && table[i]<vot)                    i++;                if(i<j)                    table[j--]= table[i];            }            table[i] =vot;            quickSort(table, low, j-1);            quickSort(table, i+1, high);        }    }

question 3 :如果可以申请额外空间,则可以利用HashSet来高效过滤重复。

    //允许申请额外的空间,利用hashSet的contains方法来过滤重复元素    public int removeDuplicates(int []A){        if(A==null || A.length==0)//如果数组没有new或长度为0            return 0;        int count=1;//计数器,记录不相等的元素个数        HashSet<Integer> hashSet=new HashSet<Integer>();//散列集,判断是否有重复        hashSet.add(A[0]);//第一个元素肯定不会重复        for (int i = 0; i < A.length; i++) {            if(!hashSet.contains(A[i])){//没有和前面重复的                 A[count++]=A[i];//计数器加一,并重置数组的值                hashSet.add(A[i]);            }           }        return hashSet.size();//返回新数组的长度    }
0 0