编程练习(第四周)

来源:互联网 发布:图文广告软件下载 编辑:程序博客网 时间:2024/06/05 18:56

215. Kth Largest Element in an Array

DescriptionSubmissionsSolutions
  • Total Accepted: 117471 
  • Total Submissions: 307801 
  • Difficulty: Medium 
  • Contributors: Admin

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.

分析:利用快排每次将数组划分为两组加一个枢纽元素,每一趟划分只需要将k与枢纽元素的下标进行比较,如果比枢纽元素下标大就从右边的子数组中找,如果比枢纽元素下标小从左边的子数组中找,如果一样则就是枢纽元素,找到,如果需要从左边或者右边的子数组中再查找的话,只需要递归一边查找即可。

代码如下:

int Sort(vector<int>& a, int low, int high){    int pivot = a[low];     if(low < high)    {        while(a[high] >= pivot && low < high)            high --;        a[low] = a[high];        while(a[low] <= pivot && low <high)            low ++;        a[high] = a[low];    }    a[low] = pivot;    return low;}int QuickSort_K_MAX(vector<int>& a, int low, int high, int k){    if(low >= high)        return a[low];    else    {        int mid = Sort(a,low,high);        if(mid > k)            QuickSort_K_MAX(a,low,mid-1,k);        else if(mid < k)            QuickSort_K_MAX(a,mid+1,high,k);         else            return a[mid];    }}int findKthLargest(vector<int>& nums, int k){return QuickSort_K_MAX(nums,0,nums.size()-1,nums.size()-k);} 

0 0