LeetCode------Kth Largest Element in an Array
程序员文章站
2022-03-07 18:40:43
...
快排partition
这道题最好的解法应该是用快速排序Quick Sort的思想,这里排序的方向是从大往小排,核心思想是每次都要先找一个中枢点Pivot,然后遍历其他所有的数字,这里要求第k大,就把大于中枢点的数字放到左半边,把小于中枢点的放在右半边,这样中枢点是整个数组中第几大的数字就确定了,虽然左右两部分不一定是完全有序的,但是并不影响本题要求的结果,所以我们求出中枢点的位置,如果正好是k-1,那么直接返回该位置上的数字;如果大于k-1,说明要求的数字在左半部分,更新右边界,再求新的中枢点位置;反之则更新右半部分,求中枢点的位置;实例代码如下:
package com.zhumq.lianxi;
import org.junit.Test;
public class FindKthLargest {
public int findKthLargest(int arr[],int k) {
int left = 0,right = arr.length-1;
while(true) {
//位置调整
int pos = partition(arr,left,right);
if(pos==k-1) return arr[pos];
else if(pos>k-1) right = pos-1;
else left = pos+1;
}
}
private int partition(int[] arr, int left, int right) {
int pivot = arr[left],l = left + 1,r = right;
while(l<=r) {
//从大到小排序,小于中枢的放在右边,大于中枢的放在左边
if(arr[l]<pivot&&arr[r]>pivot) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
++l;
--r;
}
if(arr[l]>=pivot) ++l;
if(arr[r]<=pivot) --r;
}
int temp = arr[left];
arr[left] = arr[r];
arr[r] = temp;
return r;
}
@Test
public void test1() {
int arr[] = {1,5,2,3,4,7,6,9,0};
System.out.println(findKthLargest(arr, 4));
}
}
推荐阅读
-
element vue Array数组和Map对象的添加与删除
-
5. Kth Largest Element
-
Split Array Largest Sum 二分查找应用 C实现
-
2018 Bytedance AI Camp 编程题2: Split Array Largest Sum
-
410. Split Array Largest Sum
-
LeetCode 410. Split Array Largest Sum
-
Leetcode 410. Split Array Largest Sum
-
moviepy AudioClip帧处理ValueError: The truth value of array with more than one element is ambiguous
-
python报错ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()
-
Python报错:The truth value of an array with more than one element is ambiguous