• 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中如何调用最小堆。
  • 相关阅读:
    chrome sarfri form.submit bug
    ruby首字母大写
    ubuntu 10.04 中文设置
    添加centos用户
    农行的短信提醒很滞后
    从github删除敏感数据
    从github删除敏感数据
    国内有不有做虚拟化或是叫云平台的朋友
    设置rails header编码
    centos5.5
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4535352.html
Copyright © 2020-2023  润新知