LeetCode Week 2

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);
    }

猜你喜欢

转载自blog.csdn.net/Xiouzai_/article/details/82633118
今日推荐