LeetCode 215. Kth Largest Element in an Array

来源:互联网 发布:mac怎么强制退出软件 编辑:程序博客网 时间:2024/06/05 10:50

问题描述

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

题目分析

给定一个数组,找出其中第K大的数。这个题目可以先对当前数组进行排序,然后返回第K个数。也可以使用类似于快排的实现方法,快排交换都是将当一个数定位到当前数组中的某一个位置,如果这个位置就是第K大的数直接返回,如果比k大就在左边,如果比k小就在右边。

代码实现

 /**     * 找出nums中第k大的数     *     * @param nums 当前数组     * @param k     * @return     */    public int findKthLargest(int[] nums, int k) {        //使用快排的方式找出当前nums中第k大的数        int left = 0;        int right = nums.length - 1;        int index = -1;        int target = k - 1;        do {            index = findIndexOfLeft(nums, left, right);            if (index > target) {                right = index - 1;            } else {                left = index + 1;            }        } while (index != target);        return nums[k - 1];    }    /**     * nums[left]的升序放置在当前的nums中。     *     * @param nums  数组     * @param left  左坐标     * @param right 右坐标     * @return 返回nums[left]在nums中升序的位置     */    protected int findIndexOfLeft(int[] nums, int left, int right) {        int temp = nums[left];        while (left < right) {            while (left < right && nums[right] <= temp) {                right--;            }            if (left < right) {                nums[left] = nums[right];            }            while (left < right && nums[left] > temp) {                left++;            }            if (left < right) {                nums[right] = nums[left];            }        }        nums[left] = temp;        return left;    }

总结

快速排序中,每一轮的执行都会将一个数最终放到最终结果中的某一个位置。

原创粉丝点击