您的位置:首页 > 其它

算法(三)找出数组中第K大元素

2017-09-18 15:35 363 查看
题目描述:

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.


解法如下:

1. 用选择排序,冒泡法这类的排序,对前K个元素进行排序。这三种算法也许不是最快的排序算法。但是都有个性质:计算出最大(小)的元素的算法复杂度是O(N)。这个过程不能中断,要计算第三大的元素必须建立在已经算出第二大的元素的基础上(因为每次都是计算当前数组最大)。所以它的算法复杂度是O(N*K);

2. 使用类似快排的方法,选择一个元素,使得左边元素都比他小,右边元素都比他大。记录此时元素位置,若小于k,则在右边重新快排,否则在左边重新快排。时间复杂度为O(N)。代码如下:

class Solution {
public:
int findKthLargest(vector<int> & nums, int k) {
int aim = nums.size() - k;
int position = quickSort(nums,0, nums.size() - 1);
int start = 0;
int end = nums.size() - 1;
while (position != aim) {
if (position < aim) {
start = position + 1;
}
else {
end = position - 1;
}
position = quickSort(nums, start, end);
}
return nums[position];
}

int quickSort(vector<int> & nums,int start, int end) {
int flag = rand() % (end - start + 1) + start;
int temp = nums[flag];
nums[flag] = nums[start];
nums[start] = temp;
int last_small = start;
for (int i = start + 1; i <= end; ++i) {
if (nums[i] < nums[start]) {
last_small++;
temp = nums[last_small];
nums[last_small] = nums[i];
nums[i] = temp;
}
}
temp = nums[last_small];
nums[last_small] = nums[start];
nums[start] = temp;
return last_small;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐