題解 | #尋找第K大#
尋找第K大
http://www.fangfengwang8.cn/practice/e016ad9b7f0b45048c58a9f27ba618bf
import java.util.*; public class Solution { /** * 代碼中的類名、方法名、參數(shù)名已經(jīng)指定,請(qǐng)勿修改,直接返回方法規(guī)定的值即可 * * * @param a int整型一維數(shù)組 * @param n int整型 * @param K int整型 * @return int整型 */ public int findKth (int[] a, int n, int K) { if (n == 0) return 0; quickSort(a, 0, n - 1); return a[n - K]; } public void quickSort(int[] arr, int i, int j) { int start = i; int end = j; if (start >= end) return; int pivot = arr[start]; while (start != end) { while (true) { if (end <= start || arr[end] < pivot) { break; } end--; } while (true) { if (end <= start || arr[start] > pivot) { break; } start++; } int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; } int temp = arr[i]; arr[i] = arr[start]; arr[start] = temp; quickSort(arr, i, start - 1); quickSort(arr, start + 1, j); } }