zoukankan      html  css  js  c++  java
  • lc 数组中的第K个最大元素

    链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/

    代码:

    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            k--;
            return solve(nums, 0, nums.size()-1, k);
        }
        int solve(vector<int>& nums, int low, int high, int k) {
            int privot = nums[low];
            int ll = low;
            int hh = high;
            int index = partition(nums, low, high);
            if(index == k) return nums[k];
            else if(k < index) {
                return solve(nums, ll, index-1, k);
            }
            else {
                return solve(nums, index+1, hh, k);
            }
        }
        int partition(vector<int>& nums, int low, int high) {
            if(low == high) return low;
            int privot = nums[low];
            while(low < high) {
                while(low < high && nums[high] <= privot) high--;
                nums[low] = nums[high];
                while(low < high && nums[low] >= privot) low++;
                nums[high] = nums[low];
                // cout << "======" << endl;
            }
            nums[low] = privot;
            return low;
        }
    };
    View Code

    思路:参考快排partition 思想,再递归,一直到 partition 返回的坐标是 k,复杂度是O(n),因为费时操作是 partition。

  • 相关阅读:
    NIO学习
    XML(二)
    IO和NIO
    Log4j
    异常处理机制
    XML
    数据交互
    分页实现的三种方式
    Idea破解
    数据库连接池
  • 原文地址:https://www.cnblogs.com/FriskyPuppy/p/12907951.html
Copyright © 2011-2022 走看看