Kth Largest Element II

Find K-th largest element in an array. and N is much larger than k. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example

Example 1:

Input:[9,3,2,4,8],3
Output:4

Example 2:

Input:[1,2,3,4,5,6,8,9,10,7],10
Output:1

Notice

You can swap elements in the array

思路:可以用quick select模板,注意模板是两个while一个if,另外条件是i <= j

public class Solution {
    /**
     * @param nums: an integer unsorted array
     * @param k: an integer from 1 to n
     * @return: the kth largest element
     */
    public int kthLargestElement2(int[] nums, int k) {
        if(nums == null || nums.length == 0) {
            return -1;
        }
        
        return findKth(nums, k, 0, nums.length-1);
    }
    
    private int findKth(int[] nums, int k, int start, int end) {
        if(start == end) {
            return nums[start];
        }
        
        int mid = start + (end - start) / 2;
        int pivot = nums[mid];
        int i = start; int j = end;
        while(i <= j) {
            while(i <= j && nums[i] > pivot) {
                i++;
            }
            while(i <= j && nums[j] < pivot) {
                j--;
            }
            if(i <= j) {
                swap(nums, i, j);
                i++;
                j--;
            }
        }
        
        if(start + k - 1 <= j) {
            return findKth(nums, k, start, j);
        }
        if(start + k - 1 >= i) {
            return findKth(nums, k - (i-start), i, end);
        }
        return nums[j+1];
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

思路2:如果按照题目意思,如果num很大很大的话,那么用priorityqueue,nlogk

public class Solution {
    /**
     * @param nums: an integer unsorted array
     * @param k: an integer from 1 to n
     * @return: the kth largest element
     */
    public int kthLargestElement2(int[] nums, int k) {
        if(nums == null || nums.length == 0) {
            return -1;
        }
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(pq.size() < k) {
                pq.add(nums[i]);
            } else {
                if(nums[i] > pq.peek()){
                    pq.poll();
                    pq.add(nums[i]);
                }
            }
        }
        
        return pq.peek();
    }
}
发布了562 篇原创文章 · 获赞 13 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/103802786