标签:
Problem: https://leetcode.com/problems/kth-largest-element-in-an-array/
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.
Thought:
Quick Sort partition
Code C++:
class Solution { public: int findKthLargest(vector<int>& nums, int k) { if (k <= 0 || k > nums.size()) { return 0; } int q = partition(nums); if (q + 1 == k) { return nums[q]; } vector<int>left; vector<int>right; for (int i = 0; i < q; i++) { left.push_back(nums[i]); } for (int i = q + 1; i < nums.size(); i++) { right.push_back(nums[i]); } if (q + 1 < k) { return findKthLargest(right, k - q -1); } else { return findKthLargest(left, k); } } int partition(vector<int>& nums){ srand(unsigned(time(0))); int k = random() % nums.size(); int key = nums[k]; int temp = nums[k]; nums[k] = nums.back(); nums.back() = temp; int j = 0; for (int i = 0; i < nums.size() - 1; i++) { if (nums[i] > key) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; j++; } } temp = nums.back(); nums.back() = nums[j]; nums[j] = temp; return j; } };
LeetCode 215. Kth Largest Element in an Array
标签:
原文地址:http://www.cnblogs.com/gavinxing/p/5656279.html