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

      

  • 相关阅读:
    小结
    五种常见的 PHP 设计模式
    php克隆 自动加载
    小知识点
    php抽象 与接口
    php静态
    iOS开发零碎笔记
    iOS开发错误日志
    Objective-C:Foundation框架-常用类-NSObject
    Objective-C:Foundation框架-常用类-NSDate
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/6403575.html
Copyright © 2011-2022 走看看