欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode215:Kth Largest Element in an Array

程序员文章站 2022-04-25 11:45:11
...

leetcode215:Kth Largest Element in an Array

思路:参考TopK的Quick Select做法https://blog.csdn.net/Somnus_k/article/details/82724704

代码:

public class KthLargestElementinanArray {

	public static void main(String[] args) {
		int[] arr = { 1, 8, 35, 4, 7 };
		System.out.println(findKthLargest(arr, 4));
	}

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

	private static int quickSelect(int[] nums, int k, int i, int j) {
		if(i>=j)
			return nums[i];
		int index = partion(nums,i,j);
		if(index-i+1==k)
			return nums[index];
		else if(index-i+1>k)
			return quickSelect(nums, k, i, index-1);
		else
			return quickSelect(nums, k-(index-i+1), index+1, j);
	}

	private static int partion(int[] nums, int i, int j) {
		
		int tmp = nums[i];
		while(i<j){
			while(i<j)
				if(nums[j]>tmp)
				{
					nums[i]=nums[j];
					i++;
					break;
				}else
					j--;
			while(i<j)
				if(nums[i]<tmp)
					{
					nums[j]=nums[i];
					j--;
					break;
					}else
						i++;
		}
		nums[i]=tmp;
		return i;
	}

}

输出:

leetcode215:Kth Largest Element in an Array

相关标签: TopK Quick Select