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.

    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的元素,代码如下:

    1 public class Solution {
    2     public int findKthLargest(int[] nums, int k) {
    3         Arrays.sort(nums);
    4         return nums[nums.length-k];
    5     }
    6 }

    第二种方法使用小顶堆来做,代码如下:

     1 public class Solution {
     2     public int findKthLargest(int[] nums, int k) {
     3         PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
     4         for(int num:nums){
     5             pq.add(num);
     6             if(pq.size()>k) pq.poll();
     7         }
     8         return pq.peek();
     9     }
    10 }

    本题比较高明的做法是使用快速选择,通过本题可以了解快速选择有个特点,就是可以从大到小排列,也可以从小到大排列,需要注意的是与target相等的情况;快速选择的思想是,设置一个target值,这里面默认最左面的值,然后设置两个指针,一个在最左面(除去target的位置),另一个在最右面,然后进行比较,把大于target的放在左面,把小于target放在右面,然后隔开。代码如下:

     1 public class Solution {
     2     public int findKthLargest(int[] nums, int k) {
     3         int len = nums.length;
     4         int kindex = len-k;
     5         int lo = 0;
     6         int hi = len-1;
     7         while(lo<hi){
     8             int j = quicksort(nums,lo,hi);
     9             if(j>kindex){
    10                 hi = j-1;
    11             }else if(j<kindex){
    12                 lo = j+1;
    13             }else{
    14                 break;
    15             }
    16         }
    17         return nums[kindex];
    18         
    19     }
    20     public int quicksort(int[] nums,int lo,int hi){
    21         int i = lo;
    22         int j = lo;
    23         int pivot = nums[hi];
    24         while(i<hi){
    25             if(pivot>nums[i]){
    26                 swap(nums,i,j);
    27                 j++;
    28             }
    29             i++;
    30         }
    31         swap(nums,hi,j);
    32         return j;
    33     }
    34     public void swap(int[] nums,int i,int j){
    35         int temp = nums[i];
    36         nums[i] = nums[j];
    37         nums[j] = temp;
    38     }
    39 }
    40 // the run time complexity of this algorithm could be O(n), the worst case could be O(n^2),the space complexity could be O(1);

     快速选择有一些需要注意的细节,网址如下:

    https://comzyh.com/blog/archives/713/

  • 相关阅读:
    redis 之redis集群与集群配置
    redis 之redis-sentinel主从复制高可用
    Python 基础之函数的嵌套与nonlocal修改局部变量及闭包函数
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6592617.html
Copyright © 2011-2022 走看看