LeetCode 215. Kth Largest Element in an Array

区块链

575人已加入

描述

LeetCode 215. Kth Largest Element in an Array Description

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 index = quickSelect(nums, 0, nums.length-1, k-1); return nums[index]; } private int quickSelect(int[] nums, int lo, int hi, int k) { int lt = lo; int gt = hi + 1; int i = lo + 1; int pivot = nums[lo]; while (i < gt) { if (nums[i] > pivot) { swap(nums, i, lt + 1); lt++; i++; } else if (nums[i] < pivot) { swap(nums, i, gt - 1); gt--; } else { i++; } } swap(nums, lo, lt); if (lt == k) { return lt; } else if (lt < k) { return quickSelect(nums, lt + 1, hi, k); } else { return quickSelect(nums, lo, lt - 1, k); } } private void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } Complexity analysis

Time complexity : O(n).
Space complexity : O(log(n

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 相关推荐

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分