數組去重(時間複雜度nlgn,時間複雜度o(1))

public static void quickSort(int[] numArr, int left, int right) {
    //若是left等於right,即數組只有一個元素,直接返回
    if (left >= right) {
        return;
    }
    //設置最左邊的元素爲基準值
    int key = numArr[left];
    //數組中比key小的放在左邊,比key大的放在右邊,key值下標爲i
    int i = left;
    int j = right;
    while (i < j) {
        //j向左移,直到遇到比key小的值
        while (numArr[j] >= key && i < j) {
            j--;
        }
        //i向右移,直到遇到比key大的值
        while (numArr[i] <= key && i < j) {
            i++;
        }
        //i和j指向的元素交換
        if (i < j) {
            int temp = numArr[i];
            numArr[i] = numArr[j];
            numArr[j] = temp;
        }
    }
    numArr[left] = numArr[i];
    numArr[i] = key;
    // 遞歸調用
    quickSort(numArr, left, i - 1);
    quickSort(numArr, i + 1, right);
}
public static void main(String args[]) {
    // 初始化數組
    int[] numArry = {1, 1, 6, 2, 1, 6, 3, 3, 5, 7};
    int start = 0;
    int end = numArry.length - 1;
    quickSort(numArry, start, end);
    int tempNum = numArry[0];
    for (int i = 0; i < numArry.length; i++) {
        if (i == 0) {
            System.out.println(tempNum);
            continue;
        }
        if (tempNum != numArry[i]) {
            System.out.println(numArry[i]);
        }
        tempNum = numArry[i];
    }
}
相關文章
相關標籤/搜索