zoukankan      html  css  js  c++  java
  • 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.

    解题思路:

    这很容易想到,可以对数组进行排序,然后直接取k个最大的数字。

    这样的时间复杂度为O(nlogn)

    而使用partition来进行分割,可以达到均摊时间O(n)的时间复杂度。

    代码:

    class Solution {
    public:
        int partition(vector<int> &nums, int left, int right){
            int l = left, r = right;
            int pivot = nums[left];
            while(l < r){
                while(nums[r] <= pivot && r > l) r--;
                nums[l] = nums[r];
                while(nums[l] > pivot && r > l) l++;
                nums[r] = nums[l];
            }
            nums[l] = pivot;
            return r;
        }
        int findKthLargest(vector<int>& nums, int k) {
            int p = -1, l = 0, r = nums.size()-1;
            while(true){
                p = partition(nums, l, r);
                if(p == k-1) break;
                else if(p > k-1) r = p - 1;
                else l = p + 1;
            }
            return nums[p];
        }
    };
  • 相关阅读:
    java前三章总结
    Java入门第二章
    java编程入门小结
    Java入门第二章
    java预习易错点
    计算机基础
    切换卡
    ajax
    水印4
    shuiyin3
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9339530.html
Copyright © 2011-2022 走看看