LeetCode Week 2
阿新 • • 發佈:2018-12-08
215. 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.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
solution:
本題意是在一個無序陣列中找到第K大的數。一開始很容易想到可以將陣列排序,接著我們就能得到第K大的陣列元素了。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int i, j;
for(i = 0; i < nums.size() - 1; i++) {
for (j = 0; j < nums.size() - 1 - i; j++) {
if(nums[j] < nums[j+1]) {
int tem = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tem;
}
}
}
return nums[k-1];
}
};
但是題目並沒有要求我們將陣列排序,只是找到第K大的陣列元素,而且這種方法的時間複雜度太大。所以我們可以採取分治的方法,設定一個key,將陣列分為三部分。比key大的在key的左邊,比key小的在key的右邊。當K比key的索引小時,我們在左邊去找;當K比key的索引大時,我們去右邊去找。當K等於key時,返回這個key值。
int findKLargestElement(int k, vector<int>& nums, int low, int high) {
int left = low;
int right = high;
int key = nums[left];
while (left < right) {
while (left < right && nums[right] < key) --right;
nums[left] = nums[right];
while (left < right && nums[left] >= key) ++left;
nums[right] = nums[left];
}
nums[left] = key;
if (left < (k-1)) {
return findKLargestElement(k, nums, left+1, high);
}
else if (left > (k-1)) {
return findKLargestElement(k, nums, low, left-1);
}
else {
return key;
}
}
int findKthLargest(vector<int>& nums, int k) {
return findKLargestElement(k, nums, 0, nums.size()-1);
}