题解 | #寻找第K大# [S-P0]

寻找第K大

http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf

import java.util.*;

public class Solution {
    int M;
    int[] aa;
    public int findKth(int[] a, int n, int K) {
      M = n - K;
      aa = a;
      quickSortM(0, n-1);
      return aa[M];
    }

    private void quickSortM(int start, int end) {
      if (start >= end) return;
      
      int pivot = partition(start, end);
      if (pivot == M) return;
      if (pivot < M) quickSortM(pivot+1, end);
      else quickSortM(start, pivot-1);
    }
  
    private int partition(int start, int end) {
      int pVal = aa[start];
      int x = start, y = end;
      while (x < y) {
        while (aa[x] <= pVal && x < end) x++;
        while (aa[y] >= pVal && y > start) y--;
        if (x < y) swap(x, y);
      }
      swap(start, y);
      return y;
    }
  
    private void swap(int x, int y) {
      int tmp = aa[x];
      aa[x] = aa[y];
      aa[y] = tmp;
    }
}
全部评论

相关推荐

10-14 12:20
门头沟学院 Java
迷茫的大四🐶:摊牌了,我是25届的,你们也不招我
点赞 评论 收藏
分享
孙艹肘:校招不给三方直接让实习我都去了,,主打一个在学校呆着也是闲着,不如出来实习一下
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务