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

    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.

    最简单的想法:先排序,然后倒数k个元素就是

    时间复杂度:O(nlogn)

    public class Solution {
        public int findKthLargest(int[] nums, int k) {
            Arrays.sort(nums);
            return nums[nums.length-k];
        }
    }

    优化:quicksort 中 partition 的思想

    就像quickselect一样,时间复杂度应该是 O(n)

    public class Solution {
        public int findKthLargest(int[] nums, int k) {
            return helper(nums, 0, nums.length-1, k);
        }
        
        public int helper(int[] nums, int lo, int hi, int k) {
            // if (lo == hi)
            //     return nums[lo];
                
            int partition = nums[lo];
            int j = hi;
            for (int i = lo+1; i <= j;) {
                while (i <= hi && nums[i] < partition) i++;
                while (j >= lo && nums[j] > partition) j--;
                if (i <= j) {
                    swap(nums, i, j);
                    i++; j--;
                }
            }
            swap(nums, j, lo);
    
            if (k == hi - j + 1)
                return nums[j];
            if (k < hi - j + 1)
                return helper(nums, j + 1, hi, k);
            else
                return helper(nums, lo, j - 1, k - (hi - j + 1));
        }
        
        public void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

    2015-10-21

  • 相关阅读:
    VUE常用传值方式、父传子、子传父、非父子组件传值
    ios10中禁止用户缩放页面
    TCP MSS
    C++11 之 override
    unordered_set
    c++Lambda
    QUIC实现代码分析
    C++11新特性之十:enable_shared_from_this
    c++11 atomic
    How to Write a QUIC Endpoint Program
  • 原文地址:https://www.cnblogs.com/whuyt/p/4898495.html
Copyright © 2011-2022 走看看