其他分享
首页 > 其他分享> > 215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

作者:互联网

The first solution, the easiest one, time complexity: O(nlog(n))

    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        if(k<=nums.length)
            return nums[nums.length-k];
        else
            return -1;
    }

The second solution, using priority queue, time complexity: O(n*klog(k))

    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for(int i:nums){
            q.offer(i);
            if(q.size()>k)
                q.poll();
        }
        return q.peek();
    }

The third soltuion, quick sort the nums, and then return the kth largest num, average time complexity: O(n), the following is a typical quick sort template:

    public int findKthLargest(int[] nums, int k) {
        quicksort(nums, 0, nums.length - 1);
        return nums[nums.length - k];
    }

    public void quicksort(int[] nums, int start, int end) {
        if (start >= end)
            return;
        int i = start, j = end, mid = (i + j) / 2;
        int midNum = nums[mid];
        while (i <= j) {
            while (i <= j && nums[i] < midNum) {
                i++;
            }
            while (i <= j && nums[j] > midNum) {
                j--;
            }
            if (i <= j) {
                swap(nums, i, j);
                i++;
                j--;
            }
        }
        quicksort(nums, start, j);
        quicksort(nums, i, end);
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

 

标签:215,return,nums,int,start,Kth,end,Array,public
来源: https://www.cnblogs.com/feiflytech/p/15873550.html