判断字符数组中是否所有的字符都只出现过一次

    // 要求:在保证额外空间复杂度为O(1)的前提下,使得时间复杂度最低

    // 思路:先排序,再遍历数组

    // 考点:各个排序算法的时间,空间复杂度——>堆排序

    public boolean isUnique(char[] chas) {
        if (chas == null || chas.length == 0) {
            return true;
        }
        System.out.println(1);
        // 建堆
        buildStack(chas);
        for (int i = 1; i < chas.length; i++) {
            System.out.println(chas[i]);
        }
        // 排序
        stackSort(chas);

        for (int i = 1; i < chas.length; i++) {
            if (chas[i] == chas[i - 1])
                return false;
        }
        return true;

    }

    // 将原数组从小到大排序

    // 因为是在原数组的基础上建堆,因此根节点下标为0
    public void buildStack(char[] input) {
        int len = input.length;
        for (int i = (len - 1) / 2; i >= 0; i--) {
            sink(input, i, len);
        }
        System.out.println(1);
    }

    public void stackSort(char[] input) {
        int len = input.length - 1;
        for (int i = 0; i < len; i++) {
            char temp = input[0];
            input[0] = input[len];
            sink(input, 0, --len);
        }
    }

    // modify head from Node n to leaf Node
    public void sink(char[] input, int n, int length) {
        int left = 2 * n + 1;
        int right = 2 * n + 2;
        while (right < length) {
            int maxIndex = input[left] < input[right] ? right : left;
            if (input[maxIndex] > input[n]) {
                exch(input, n, maxIndex);
            }
            // 将n更新为进行交换节点的index
            n = maxIndex;
            left = 2*n + 1;
            right = 2*n + 2;
        }

        if(left < length && input[left] > input[n]) {
            exch(input,n,left);
        }
    }

    public void exch(char[] input, int index1, int index2) {
        char temp = input[index1];
        input[index1] = input[index2];
        input[index2] = temp;
    }

猜你喜欢

转载自blog.csdn.net/niukai1768/article/details/80726908