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.

Note: 

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

剛開始用冒泡o(k*n),時間550ms,網上一人的快拍算法,55ms,後我用堆排做,o(n*logn),16ms,代碼如下:

class Solution {
public:
 void sift(vector<int>& nums,int low,int high){
	int i=low,j=2*i;
	while (j<=high)
	{
		if(j<high&&nums[j]<nums[j+1])
			j++;
		if(nums[i]<nums[j]){
			swap(nums[i],nums[j]);
			i=j;
			j=2*i;
		}
		else
			break;	
	}
}
 int findKthLargest(vector<int>& nums, int k) {
     int i;
	 int n=nums.size()-1;
	for(i=n/2+1;i>=0;i--){
		sift(nums,i,n);
	}
	for(i=0;i<k-1;i++){
 		swap(nums[0],nums[n-i]);
		sift(nums,0,n-i-1);
	}
	return nums[0];
}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章