Array---Remove Duplicates from Sorted Array——移除排序数组中重复元素

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],app

Your function should return length = 2, and A is now [1,2].ui

思路:this

(1)这道题其实很简单。主要是由于数组已是排好顺序的。若是不仔细看题目,把数组看成无序数组进行操做,OJ时会显示超时。spa

(2)题目要求是不能申请二额外空间,若是提交时有申请额外空间,也是不经过的。code

(3)还须要注意的一个地方是,数组中元素的位置不能改变。好比对于数组[1,1,1,4,5],移除重复元素后为[1,4,5],起始数字为1,而不能是其它数字。排序

(4)咱们只需对对组遍历一次,并设置一个计数器,每当遍历先后元素不相同,计数器加1,并将计数器对应在数组中位置定位到当前遍历的元素。element

算法代码实现以下:rem

public static int removeDuplicates(int[] A) {
    int len = A.length;
    if (len == 0)
        return 0;
    int count = 1;
    for (int i = 1; i < len; i++) {
        if (A[i] == A[i - 1]) {
            continue;
        }else{
            A[count] = A[i];
            count++;
        }
    }
    return count;
}

上面的解法是针对有序数组,若是是无序数组,应该如何解答?

思路:

(1)若是不容许申请额外空间,则能够先对数组进行排序,为了提升效率通常考虑使用快速排序,而后再参照上面有序数组进行操做;

(2)若是容许申请空间,则只需建立一个HashSet,遍历一次数组,经过contanins()方法进行判断就能获得结果。

(1)和(2)所对应代码以下所示(注:针对本文所示的题目,若是用下面代码进行OJ,(1)会超时,(2)会产生额外空间):

不能够申请额外空间:

public static int removeDuplicates(int[] A) {
    int len = A.length;
    if (len == 0)
        return 0;

    quickSort(A, 0, len - 1);

    int count = 1;
    for (int i = 1; i < len; i++) {
        if (A[i] == A[i - 1]) {
            continue;
        } else {
            A[count] = A[i];
            count++;
        }
    }
    return count;
}

//快速排序

private static 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];
                i++;
            }
            while (i < j && table[i] < vot)
                i++;
            if (i < j) {
                table[j] = table[i];
                j--;
            }
        }
        table[i] = vot;
        quickSort(table, low, j - 1);
        quickSort(table, i + 1, high);
    }
}

能够申请额外空间:(其中,HashSet的contains()方法是用来过滤重复元素的)

public static int removeDuplicates(int[] A) {
    int len = A.length;
    HashSet set = new HashSet();
    for (int i = 0; i < len; i++) {
        if (set.size() == 0) {
            set.add(A[i]);
        }
        if (!set.contains(A[i])) {
            set.add(A[i]);
        }
    }
    return set.size();
}
相关文章
相关标签/搜索