您的位置:首页 > 其它

Leetcode: Kth Largest Element in an Array

2015-08-02 18:14 253 查看

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(n)。朴素的快排:

class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return partition(nums, 0, nums.size(), k);
}

int partition(vector<int>& nums, int start, int end, int k) {
if (start + 1 == end) {
return nums[start];
}

int cur = start + 1;
int less = start;
while (cur < end) {
if (nums[cur] <= nums[start]) {
swap(nums, ++less, cur);
}
++cur;
}
swap(nums, start, less);

int largerNum = end - less;
if (largerNum == k) {
return nums[less];
}
else if (largerNum < k) {
return partition(nums, start, less, k - largerNum);
}
else {
return partition(nums, less + 1, end, k);
}
}

void swap(vector<int>& nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
};

稍微高级一点的快排。怎么感觉这个更容易理解呢。。。

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

return nums[start];
}

int partition(vector<int>& nums, int start, int end) {
int pivot = nums[start];
int i = start;
int j = end;
while (i < j) {
while (i < j && nums[j] > pivot) {
--j;
}
if (i < j) {
swap(nums[i++], nums[j]);
}

while (i < j && nums[i] < pivot) {
++i;
}
if (i < j) {
swap(nums[i], nums[j--]);
}
}

nums[i] = pivot;

return i;
}
};

也可以用堆,不过时间复杂度是O(nlogK)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 快排