题目:
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.
思路:
题目要求我们求一个数组当中第k大的元素。首先,根据快速排序的思想,以数组第一个元素为参考元素将数组分为两部分,第一部分中的元素都大于参考元素,第二部分中的元素都小于参考元素。然后根据分治的思想,如果参考元素所处的位置等于k-1,则此参考元素就是我们要求的结果,如果位置大于k-1,则求数组前半部分中第k大的元素,如果位置小于k-1,则求数组后半部分第k-n大的元素(n为前半部分元素的数量)。
程序:
int partition(int *nums,int low,int high)
{
int pivot = *nums;
while(low < high)
{
while(low < high&&pivot >= *(nums + high))
high--;
*(nums + low) = *(nums + high);
while(low < high&&pivot < *(nums + low))
low++;
*(nums + high) = *(nums + low);
}
*(nums + low) = pivot;
return low;
}
int findKthLargest(int* nums, int numsSize, int k) {
if(numsSize == 1)
return *nums;
int location = partition(nums,0,numsSize - 1);
if(location + 1 == k)
return *(nums + location);
else if(location + 1 > k)
return findKthLargest(nums,location + 1,k);
else
return findKthLargest(nums + location + 1,numsSize - location - 1,k - location - 1);
}