这周上课的内容主要是讲了分治算法
挑选的题目:在一个未排序的数组里面找到第K大的元素。
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个元素即可。
一个是排序可以用快速排序,然后用二分查找。在进行快速排序的时候,在指定范围内找到该值的下标,如果该下标与K值相比比较大,则结束end=index-1,相反的话 start=index+1即可
代码:
int QSort(int* a,int low,int high)
{
if(low<high)
{
int start=low,end=high;
int key=a[start];
while(start<end)
{
while(start<end&&a[end]<key)
{
end--;
}
a[start]=a[end];
while(start<end&&a[start]>key)
{
start++;
}
a[end]=a[start];
}
a[start]=key;
return start;
}
return -1;
}
int main()
{
int start=0,end=sizeof(a)/sizeof(int)-1;
int index=0;
while(index!=K)
{
index=QSort(a,start,end);
if(index<K)
{
start=index+1;
}
else if(index>K)
{
end=index-1;
}
}
cout<<a[index]<<"即为所求\n";
}