题目链接: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.
思路:这题是利用了quick-select的算法,也就是快速排序的partition,这个方法的理论时间复杂度是O(n),是一种非常有用的工具.
使用分治每次将数组划分为两段,并且返回划分点的位置,如果这个位置恰好是我们要的第k大的数,那么返回这个数即可,
否则如果返回的位置小于要找的位置,则向右边的一半数组继续寻找
如果返回的位置大于要找的位置,则向左边寻找.
class Solution {
public:
int findKthLargest(vector<int>& nums, int k)
{
int L = 0, R = nums.size() - 1;
while (L < R)
{
int left = L, right = R;
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[k - 1];
else if (left > k - 1)
R = left - 1;
else
L = left + 1;
}
return nums[k - 1];
}
};
求数组中第K大的数可以基于快排序思想,步骤如下:
1、随机选择一个支点
2、将比支点大的数,放到数组左边;将比支点小的数放到数组右边;将支点放到中间(属于左部分)
3、设左部分的长度为L,
当K < L时,递归地在左部分找第K大的数
当K > L时,递归地在有部分中找第(K - L)大的数
当K = L时,返回左右两部分的分割点(即原来的支点),就是要求的第K大的数
以上思想的代码实现如下:
求第K个最大值
//基于快速排序思想,求数组a中第k大的数,low和high分别为数组的起始和结束位置
//时间复杂度为o(n),n为数组的长度
//1<=k<=n
//如果存在,返回第k大数的下标,否则返回-1
int selectk(int a[], int low, int high, int k)
{
if(k <= 0)
return -1;
if(k > high - low + 1)
return -1;
int pivot = low + rand()%(high - low + 1); //随即选择一个支点
swap(a[low], a[pivot]);
int m = low;
int count = 1;
//一趟遍历,把较大的数放到数组的左边
for(int i = low + 1; i <= high; ++i)
{
if(a[i] > a[low])
{
swap(a[++m], a[i]);
count++; //比支点大的数的个数为count-1
}
}
swap(a[m], a[low]); //将支点放在左、右两部分的分界处
if(count > k)
{
return selectk(a, low, m - 1, k);
}
else if( count < k)
{
return selectk(a, m + 1, high, k - count);
}
else
{
return m;
}
}
class Solution{
public:
int findKthLargest(vector<int>& nums,int k)
{
return selectK(nums,k,0,nums.size()-1);
}
int selectK(vector<int>& nums,int k,int low,int high)
{
if (k<=0)
return -1;
if(k>high-low+1)
return -1;
int pivot=low+rand()%(high-low+1);
swap(nums[low],nums[pivot]);
int m=low;
int count=1;
for(int i=low+1;i<=high;i++)
{
if(nums[i]>nums[low])
{
swap(nums[++m],nums[i]);
count++;
}
}
swap(nums[m],nums[low]);
if(count>k)
return selectK(nums,k,low,m-1);
else if(count<k)
return selectK(nums,k-count,m+1,high);
else
return
nums[m];
}
};
求第k个最小值
int selectk(int a[], int low, int high, int k)
{
if(k <= 0)
return -1;
if(k > high - low + 1)
return -1;
int pivot = low + rand()%(high - low + 1); //随即选择一个支点
swap(a[low], a[pivot]);
int m = low;
int count = 1;
//一趟遍历,把较小的数放到数组的左边
for(int i = low + 1; i <= high; ++i)
{
if(a[i]<a[low])
{
swap(a[++m], a[i]);
count++; //比支点小的数的个数为count-1
}
}
swap(a[m], a[low]); //将支点放在左、右两部分的分界处
if(k < count)
{
return selectk(a, low, m - 1, k);
}
else if( k > count)
{
return selectk(a, m + 1, high, k - count);
}
else
{
return m;
}
}