zoukankan      html  css  js  c++  java
  • Leetcode-215-Kth Largest Element in an Array

    Leetcode-215-Kth Largest Element in an Array

    215. Kth Largest Element in an Array

    Description Submission Solutions Add to List

    • Total Accepted: 109821
    • Total Submissions: 290143
    • Difficulty: Medium
    • Contributors: Admin

    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.

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ array's length.

    Credits:
    Special thanks to @mithmatt for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question.

    Show Tags
    Show Similar Problems
    Have you met this question in a real interview?

    题解:

    (1),二分的用法,真的是哪里用都很奇妙

    class Solution {
    public:
        int QuickSearch(vector<int>& nums, int k, int left, int right){
            int lf = left, rg = right, midval = nums[left + (right-left)/2]; 
            while(lf <= rg){
                if(nums[lf] > midval){
                    lf++; 
                }else if(nums[rg] < midval){
                    rg--; 
                }else{
                    swap(nums, lf, rg); 
                    lf++; 
                    rg--; 
                }
            }
            if(lf < right && lf <= k){
                return QuickSearch(nums, k, lf, right); 
            }
            if(rg > left && rg >= k){
                return QuickSearch(nums, k, left, rg); 
            }
            return nums[k]; 
        }
        void swap(vector<int>& nums, int a, int b){
            int tmp = nums[a]; 
            nums[a] = nums[b]; 
            nums[b] = tmp; 
        }
        int findKthLargest(vector<int>& nums, int k) {
            return QuickSearch(nums, k-1, 0, nums.size()-1); 
        }
    };
    

      

  • 相关阅读:
    .net 第一次请求比较慢
    配置文件读取与修改
    关系型数据库设计
    dynamic动态类型的扩展方法
    软件测试作业(三)
    软件测试作业(二)
    软件项目管理作业(二)
    软件项目管理作业(一)
    软件测试作业(一)
    C#最后一次作业(暂定)
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/6403575.html
Copyright © 2011-2022 走看看