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

    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.

    思路:

      快速排序,最大堆

    我的代码:

    public class Solution {
        public int findKthLargest(int[] nums, int k) {
            return helper(nums, nums.length-k);
        }
        public int helper(int[]nums, int k)
        {
            int low = 0; 
            int high = nums.length-1;
            int key = nums[0];
            while(low < high)
            {
                while(low<high && nums[high]>=key) high--;
                nums[low] = nums[high];
                while(low<high && nums[low]<key) low++;
                nums[high] = nums[low];
            }
            nums[low] = key;
            if(low == k) return nums[low];
            return low < k ? helper(Arrays.copyOfRange(nums, low+1, nums.length), k-(low+1)) : helper(Arrays.copyOfRange(nums, 0, low), k);
        }
    }
    View Code

    他人代码:

    public int findKthLargest(int[] nums, int k) {
            PriorityQueue<Integer> queue = new PriorityQueue<Integer>(k,new Comparator<Integer>(){
                public int compare(Integer a, Integer b) {
                    return a-b;
                }
            });
            for(int i=0;i<nums.length;i++) {
                if(queue.size()<k) queue.add(nums[i]);
                else {
                    if(nums[i]>queue.peek()) {
                        queue.remove();
                        queue.add(nums[i]);
                    }
                }
            }
            return queue.remove();
        }
    View Code

    学习之处:

    • 比较常规的问题了,之前这个问题就知道两种思路,一种是快速排序的Partition,另外一种是最小堆,关键的地方在于实现Partition,java中如何调用最小堆。
  • 相关阅读:
    Libev源码分析01:Libev中的监视器结构(C结构体实现继承)
    字符串处理函数
    sqrt函数实现
    Text Justification
    Minimum Path Sum
    Linux下如何查看系统启动时间和运行时间
    通过GDB重新获得进程的输出
    linux时间
    jmeter java请求:java.lang.VerifyError: Cannot inherit from final class
    面试——请带简历
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4535352.html
Copyright © 2011-2022 走看看