LeetCode215. Kth Largest Element in an Array

来源:互联网 发布:部落冲突龙宝宝数据 编辑:程序博客网 时间:2024/04/29 20:04

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.

实现代码:

public class Solution {    public int findKthLargest(int[] nums, int k) {        int start = 0;        int end = nums.length-1;        int temp = 0;        int result = 0;        while(start <= end) {            int p = start - 1;            for (int i = start; i < end; i++) {                //倒叙,大数往前放                if (nums[i] > nums[end]) {                    temp = nums[++p];                    nums[p] = nums[i];                    nums[i] = temp;                }            }            temp = nums[++p];            nums[p] = nums[end];            nums[end] = temp;            int c = p + 1 - start;            if (c == k) {                return nums[p];            } else if (c < k){                //需要往后找                k = k - c;                start = p + 1;            } else {                //c > k                //需要往左找                end = p - 1;            }        }        return result;    }}
0 0
原创粉丝点击