这是一道分治的题目,去面网易的机器学习岗位的时候问了我这个问题,我那时候第一反应就是桶排序。。
先附上桶排序的代码如下,应该注意两个地方:1、排序的数有可能是负数;2、排序的数有可能是重复的,比如[99 99],要找出第一大的数,这种情况对于判断第几大的时候要采用大于等于而不是直接用等于来判断。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int array[20000];
int i;
for(i = 0; i < 20000; i++){
array[i] = 0;
}
for(i = 0; i < nums.size(); i++){
array[nums[i]+10000]++;
}
int count = 0;
for(i = 19999; i >= 0; i--){
if(array[i] >= 1){
count = count + array[i];
}
if(count >= k)
break;
}
return i-10000;
}
};
接下来用分治的思想,跟快排差不多的思想,代码如下:
class Solution {
public:
int partition(vector<int>& nums, int low, int high){
int pivot = nums[low];
while(low < high){
while(low < high && nums[high] <= pivot) high--;
nums[low] = nums[high];
while(low < high && nums[low] >= pivot) low++;
nums[high] = nums[low];
}
nums[low] = pivot;
return low;
}
int findKthLargest(vector<int>& nums, int k) {
int start = 0;
int end = nums.size()-1;
k--;
while(1){
int pivot = partition(nums, start, end);
if (pivot == k){
return nums[pivot];
}
else if(pivot < k){
start = pivot+1;
}
else
end = pivot-1;
}
}
};