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;
    }

 

上一篇:二分法初学


下一篇:c++数据结构——栈