数组中第k大的数

排序算法的稳定性

假定在待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变,即在原序列中,r[i]=r[j],且r[i]在r[j]之前,而在排序后的序列中,r[i]仍在r[j]之前,则称这种排序算法是稳定的;否则称为不稳定的。

1. 使用快速排序,然后取出第k大的数字

2. 使用堆排序

基本思路:

  1. 将无序序列构建成一个堆,根据升序降序需求选择大顶堆或小顶堆
  2. 将堆顶元素与末尾元素交换,将最大元素沉到数组末端
    3.重新调整结构,使其满足堆定义,然后继续交换堆顶元素与当前末尾元素,反复执行调整+交换步骤,直到整个序列有序

3. 快速选择算法

这种方法算是对上面方法的一种优化,一般面试如果你使用了上面的方法后,面试官都会问你如何优化。

  • 时间复杂度平均情况为O(n),最坏情况为O(n^2)

代码:

class Solution {
    Random random = new Random();
    public int findKthLargest(int[] nums, int k) {
        return quickSelect(nums, 0, nums.length - 1, nums.length - k);
    }
    public int quickSelect(int[] a, int l, int r, int index) {
        int q = randomPartition(a, l, r);
        if (q == index) {
            return a[q];
        } else {
            return q < index ? quickSelect(a, q + 1, r, index) : quickSelect(a, l, q - 1, index);
        }
    }

    public int randomPartition(int[] a, int l, int r) {
        int pivod_index = random.nextInt(r - l + 1) + l;
        swap(a, pivod_index, r); // 把参考值放到最右边,方便将除了自己之外的值都遍历一遍
        return partition(a, l, r);
    }

    public int partition(int[] a, int l, int r) {
        int x = a[r], pivod_index = l;   // 取出基准值,进行比较
        for (int i = l; i < r; i++) {
            if (a[i] <= x) {   // 小于基准值,进行交换
                swap(a, pivod_index, i);
                pivod_index++;
            }
        }
        swap(a, pivod_index, r);
        return pivod_index;
    }

    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

你可能感兴趣的:(数组中第k大的数)