题解 | #寻找第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;
    }
}
全部评论

相关推荐

真烦好烦真烦:豆包润色了自己没看看吗,再说了,都说豆包是愚蠢且勤快的大学生,ds才是聪明的研究生,怎么敢让豆包写论文的
点赞 评论 收藏
分享
06-20 21:22
已编辑
门头沟学院 Java
纯真的河老师在喝茶:答应了就跑啊,实习随便跑啊,别被pua了,md就是找个廉价劳动力,还平稳过度正式工,到时候跟你说没转正
点赞 评论 收藏
分享
是每个人事都这样与找工作的人这样沟通吗?正常询问不可以吗
据说名字越长别人越关注你的昵称我觉得我要被关注了:excal 我还真不会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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