Kth Largest Element in an Array

LintCode Q 215 - 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.

Example 1:
Input: [3,2,1,5,6,4] and k = 2 ; Output: 5

Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4 ; Output: 4

Note: You may assume k is always valid, 1 ≤ k ≤ array’s length.

Solution

Solution 1 : Heap

Code:


public int findKthLargest(int[] nums, int k) {
	
	Queue<Integer> pq = new PriorityQueue<>();
	
	for (int num: nums) {
		pq.offer(num);
		if (pq.size() > k) 
			pq.poll();
	} 

	return pq.peek();
}

Solution 2 : Sort

Code:


public int findKthLargest(int[] nums, int k) {
	
	Arrays.sort(nums);

	return nums[nums.length - k];
}

Solution 3 : Sort

Code:


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

private int quickSort(int[] nums, int k, int left, int right) {
	
	if (left <= right) {
		
		int pivotIndex = partition(int[nums], left, right);

		if (pivotIndex == nums.length - k)
			return nums[pivotIndex];
		else if (pivotIndex > k)
			return quickSort(nums, k, left, pivotIndex - 1);
		else
			return quickSort(nums, k, pivotIndex + 1, right);
	}

	return -1;
}

private int partition(int[] nums, int left, int right ) {
	
	int pivot = nums[left];
	
	while (left < right) {
	
		while (left < right && nums[right] >= pivot)
			right--;
	
		nums[left] = nums[right];

		while (left < right && nums[left] <= pivot)
			left++;
	
		nums[right] = nums[left];
	}

	nums[left] = pivot;

	return left;
}

   Reprint policy


《Kth Largest Element in an Array》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC