Leetcode 之 Kth Largest Element in an Array

636.Kth Largest Element in an Array

1.Problem

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.

题意很简单,找到一个一维数组中的第K大的数并返回。数组中第K大的数也是面试中经常考察的问题。现在就借Leetcode上的这题来详细总结下这个问题的几种解法。

2.Solution

//排序 时间复杂度为O(N*logN) 空间复杂度O(1)
class
Solution { public int findKthLargest(int[] nums, int k) { Arrays.sort(nums); return nums[nums.length - k ]; } }
//优先队列来维护数据的有序性,超出k的部分移除出优先队列 时间复杂度O(N*logK),空间复杂度O(K)
class
Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> p = new PriorityQueue<>(); for ( int a : nums ) { p.offer(a); if ( p.size() > k ) { p.poll(); } } return p.peek(); } }
//快速排序思想,平均时间复杂度O(N),最坏的情况下会是O(N^2),空间复杂度为O(1)
class
Solution { public int findKthLargest(int[] nums, int k) { int Left = 0,Right = nums.length - 1; while (Left < Right ) { int left = Left; int right = Right; int key = nums[left]; while ( left < right ) { while ( left < right && nums[right] < key ) { right--; } nums[left] = nums[right]; while ( left < right && nums[left] >= key ) { left++; } nums[right] = nums[left]; } nums[left] = key; if ( left == k - 1 ) { return nums[left]; } else if ( left > k - 1 ) { Right = left - 1; } else { Left = left + 1; } } return nums[k - 1]; } }
原文地址:https://www.cnblogs.com/fangpengchengbupter/p/7423018.html