题解 | #寻找第K大#

寻找第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[n-K];
    }
    public void quickSort(int[] a,int start,int end){
        if(end-start<=0)
            return;
        int index = change(a,start,end);
        quickSort(a,start,index-1);
        quickSort(a,index+1,end);
    }
    public int change(int[] a,int start,int end){
        int base = a[start];
        int left = start;
        int right = end;
        while(left<right){
            while(left<end && a[left]<=base)
                left++;
            while(right>start && a[right]>base)
                right--;
            if(left<right)
                swap(a,left,right);
        }
        if (right!=start)
            swap(a,right,start);
        return right;
    }
    public void swap(int[] nums,int i,int j){
        int temp = nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }
}
全部评论

相关推荐

ming_ri:“很抱歉,您的简历和我们当前的职位需求不是很匹配”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务