题解 | #寻找第K大(快速排序 java)#
寻找第K大
http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
import java.util.*;
public class Solution {
public int findKth(int[] a, int n, int K) {
// write code here
quickSort (a, 0, a.length - 1);
return a[a.length - K];
}
private void quickSort(int[] arr, int left, int right) {
if (left < right) {
int bound = quick (arr, left, right);
quickSort(arr, left, bound - 1);
quickSort(arr, bound + 1, right);
}
}
private int quick(int[] arr, int left, int right) {
int temp = arr[left]; // 以最左边的数作为基准
while (left < right) {
while (left < right && arr[right] >= temp) {
right--;
}
arr[left] = arr[right];
while (left < right && arr[left] <= temp) {
left++;
}
arr[right] = arr[left];
}
arr[left] = temp;
return left;
}
}