[LeetCode] 215. Kth Largest Element in an Array

来源:互联网 发布:张玉宁维特斯数据 编辑:程序博客网 时间:2024/06/16 02:10

[LeetCode] 215. Kth Largest Element in an Array

题目描述

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.

注意

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

分析

寻找数组第K大的数解决方法和对数组排序类似,区别在于寻找第K大的数不需要对数组的全部元素进行排序。对于这道题目,在各种排序方法中,比较适合的为快速排序,快速排序的重点在于分治的算法。
- 在数组中随机选择一个元素作为pivot,把比pivot大的放在左边,比pivot小的放在右边。
- 如果k=pivot的位置,那么pivot就是最后的结果。如果k < pivot的位置,那么对pivot左边的元素重复进行第一步操作。如果k > pivot的位置,那么对pivot右边的元素重复进行第一步操作。

代码

class Solution {public:  int findKthLargest(vector<int>& nums, int k) {    --k;    int l = 0, r = nums.size() - 1;    while (true) {      int i = partition(nums, l, r);      if (i == k) {        return nums[i];      } else if (i < k) {        l = i + 1;      } else {        r = i - 1;      }    }  }  int partition(vector<int>& nums, int l, int r) {    int pivot = nums[l];    while (l < r) {      while (l < r && nums[r] < pivot) {        r--;      }      if (l < r) {        nums[l] = nums[r];      }      while (l < r && nums[l] >= pivot) {        l++;      }      if (l < r) {        nums[r] = nums[l];      }    }    nums[l] = pivot;    return l;  }};
原创粉丝点击