LeetCode 二分查找第K大的数215. Kth Largest Element in an Array

来源:互联网 发布:pycharm和python 编辑:程序博客网 时间:2024/05/16 18:08

题目链接

https://leetcode.com/problems/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.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

代码

class Solution {public: int findKthLargest(vector<int>& nums, int k) //思想 第k大的数  在 数组中的下标的位置是 pos-1 判断k与pos-1 大小即可 {    int left = 0;    int right = nums.size() - 1;while(true){int pos = partition(nums,left,right);if(pos = k-1) return nums[pos];if(pos < k-1) left = pos + 1;if(pos > k-1) right = pos -1;}    }  int partition(vector<int>&v,int left,int right)//一次快速排序 { int pivot = v[left]; int low = left; int high = right; while(low < high)//此处超时 { while(low < high && v[high] >= pivot) high--;                    swap(v[low],v[high]); while(low < high && v[low] <= pivot) low++; swap(v[high],v[low]); } v[low] = pivot; return high; }};


阅读全文
0 0
原创粉丝点击