快排、归并、堆排序 三种方法解决 LeetCode912. 排序数组 问题

912. 排序数组

//快排
class Solution {
    public int[] sortArray(int[] nums) {
        quickSort(nums, 0 , nums.length - 1);
        return nums;
    }
    public void quickSort(int[] nums, int left, int right) {
        if(left >= right) {
            return;
        }
        int x = nums[left];
        int i = left - 1;
        int j = right + 1;
        while(i < j) {
            do {
                i++;
            } while(nums[i] < x);
            do {
                j--;
            } while(nums[j] > x);
            if(i < j) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
        quickSort(nums, left, j);
        quickSort(nums, j + 1, right);
    }
}

//归并
class Solution {
    int[] temp;
    public int[] sortArray(int[] nums) {
        temp = new int[nums.length];
        mergeSort(nums, 0, nums.length - 1);
        return nums;
    }

    public void mergeSort(int[] nums, int left, int right) {
        if(left >= right) {
            return;
        }
        int mid = left + right >> 1;
        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);
        int i = left;
        int j = mid + 1;
        int k = 0;
        while(i <= mid && j <= right) {
            temp[k++] = nums[i] < nums[j] ? nums[i++] : nums[j++];
        }
        while(i <= mid) {
            temp[k++] = nums[i++];
        }
        while(j <= right) {
            temp[k++] = nums[j++];
        }
        for(i = left, k = 0; i <= right; i++, k++) {
            nums[i] = temp[k];
        }
    }
}

//堆排序
class Solution {
    int[] temp;
    public int[] sortArray(int[] nums) {
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        for(int i = 0; i < nums.length; i++) {
            queue.offer(nums[i]);
        }
        int[] res = new int[nums.length];
        int idx = 0;
        while(queue.size() > 0) {
            res[idx++] = queue.poll();
        }
        return res;
    }
}

你可能感兴趣的:(leetcode,算法,数据结构)