您的位置:首页 > 其它

LeetCode-215. Kth Largest Element in an Array

2017-09-25 14:21 453 查看
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.

For example,

Given [3,2,1,5,6,4] and k = 2, return 5.

Note:

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

查找一个序列中第K大的数字。

可以使用快速选择算法

http://blog.csdn.net/x_iya/article/details/78077933

package solutions._215;

/**
* 215. Kth Largest Element in an Array
*/
class Solution {
private int partition(int[] arr, int left, int right) {
int pivot = arr[left];
while (left < right) {
while (left < right && arr[right] >= pivot) {
right--;
}
arr[left] = arr[right];

while (left < right && arr[left] <= pivot) {
left++;
}
arr[right] = arr[left];
}
arr[left] = pivot;
return left;
}

private int QuickSelect(int[] arr, int left, int right, int k) {
if (left < right) {
int pivot = partition(arr, left, right);
System.out.println("pivot = " + pivot);
if (pivot == k - 1) {
return arr[pivot];
} else if (pivot > k - 1) {
return QuickSelect(arr, left, pivot - 1, k);
} else {
return QuickSelect(arr, pivot + 1, right, k);
}
}
return arr[left];
}

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

public static void main(String[] args) {
Solution solution = new Solution();
int[] arr = {1};
System.out.println(solution.findKthLargest(arr, 1));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: