题目描述
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.
非分治算法
利用STL map自动排序的特点,对hash表做一个遍历:
---------------自己想的指针的方法,AC但是没有用到分治的思想-----
int findKthLargest(vector<int>& nums, int k) {
if(nums.empty()) return 0;
map<int,int> m;
for(int x:nums)
m[x]++;
map<int,int>::iterator p=m.end();
int count=0;
while(count<k){
--p;
count+=p->second;
}
return p->first;
}
分治算法
这个题目的分治解法中加入了快排的思想,下面是分析的思路:
首先是对于quicksort的理解,这里有一篇很好的博文:
http://blog.csdn.net/morewindows/article/details/6684558为什么要用quicksort,因为每一步选取index的过程和快排的一步循环很像
不同点在哪?因为题目的要求是找出排在第k个的元素,所以每次的merge就是对一部分进行处理,舍弃掉不包括索引是k-1元素的部分进行递归操作:
//类似于快排 将第一个元素在排序后序列中的索引找出来,然后返回其索引
//这样做实际上就是随机选择了一个第?大的元素,然后比较?与k-1的大小关系再判定下一步操作区域
int partition(vector<int>&nums,int left,int right){
int l=left+1,r=right,pivot=nums[left];
while(l<=r){
if(nums[l]<pivot&&nums[r]>pivot) swap(nums[l++],nums[r--]);
if(nums[l]>=pivot) l++;
if(nums[r]<=pivot) r--;
}
swap(nums[left],nums[r]);
return r;
}
int findKthLargest(vector<int>& nums, int k) {
//按照专题要求下面是分治的解法
int left=0,right=nums.size()-1;
while(true){
int pos=partition(nums,left,right);
if(pos==k-1) return nums[pos];
else if(pos>k-1) right=pos-1;
else left=pos+1;
}