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.

    本题开始我用了数组排序的方法做,代码如下:

    public class Solution {

        public int findKthLargest(int[] nums, int k) {

            Arrays.sort(nums);

            int kth = 0;

            for(int i=nums.length-1;i>=0;i--){

                k--;

                if(k==0) kth = nums[i];

            }

            return kth;

        }

    }

    后来我又用了大顶堆的概念来做,代码如下:

    public class Solution {

        public int findKthLargest(int[] nums, int k) {

            PriorityQueue<Integer> q = new PriorityQueue<Integer>(nums.length,new Comparator<Integer>(){

                public int compare(Integer a,Integer b){

                    return b-a;

                }

            });

            for(int i:nums){

                q.offer(i);

            }

            k--;

            while(k>0){

                q.poll();

                k--;

            }

            return q.peek();

        }

    }

    大神用了快速排序法来做,很聪明的解题办法,代码如下:

    public class Solution {

        public int findKthLargest(int[] nums, int k) {

            int n = nums.length;

            int q = quickselect(nums,0,n-1,n-k+1);

            return nums[q];

        }

        public void swap(int[] nums,int i,int j){

            int temp = nums[i];

            nums[i] = nums[j];

            nums[j] = temp;

         }

         public int quickselect(int[] nums,int lo,int hi,int k){

             int pivot = nums[hi];

             int i = lo;

             int j = hi;

             while(i<j){

                 if(nums[i++]>pivot) swap(nums,--i,--j);

             }

             swap(nums,i,hi);

             int order = i-lo+1;

             if(order==k) return i;

             else if(order>k) return quickselect(nums,lo,i-1,k);

             else return quickselect(nums,i+1,hi,k-order);

         }

    }

  • 相关阅读:
    DotNetty网络通信框架学习之初识Netty
    DotNetty网络通信框架学习
    DotNetty网络通信框架学习之源码分析
    MODBUS协议解析中常用的转换帮助类(C#)
    C# 键盘钩子
    C# 实现http不同方法的请求
    C# 中List<T>与DataSet之间的转换
    C# 将文件夹中文件复制到另一个文件夹
    WinForm中 Asp.Net Signalr消息推送测试实例
    redis安装教程
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6360889.html
Copyright © 2011-2022 走看看