hihoCoder#1133 二分·二分查找之k小数

原题地址

 

经典问题了,O(n)时间内找第k大的数

代码:

 1 #include <iostream>

 2 

 3 using namespace std;

 4 

 5 int N, K;

 6 int *a;

 7 

 8 int search(int left, int right, int k) {

 9   if (left > right)

10     return -1;

11   int l = left;

12   int r = right;

13   int p = a[left];

14   while (l < r) {

15     while (l < r && a[r] > p)

16       r--;

17     a[l] = a[r];

18     while (l < r && a[l] < p)

19       l++;

20     a[r] = a[l];

21   }

22   a[l] = p;

23   if ((l - left + 1) == k)

24     return a[l];

25   else if ((l - left + 1) < k)

26     return search(l + 1, right, k - (l - left + 1));

27   else

28     return search(left, l - 1, k);

29 }

30 

31 int main() {

32   scanf("%d%d", &N, &K);

33   a = new int[N];

34   for (int i = 0; i < N; i++)

35     scanf("%d", &(a[i]));

36   printf("%d\n", search(0, N - 1, K));

37   delete a;

38   return 0;

39 }

 

你可能感兴趣的:(code)