题解 | #寻找第K大#

寻找第K大

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param a int整型一维数组 
     * @param n int整型 
     * @param K int整型 
     * @return int整型
     */
    public int findKth (int[] a, int n, int K) {
        // write code here
        // 方法一:冒泡排序后取第K个数的值即可
        // this.bubbleSort(a);
        // return a[n-K];

        // 方法一:使用PriorityQueue优先级队列进行自动大根堆排序,然后从对头poll出第K个数即可
        Queue<Integer> que = new PriorityQueue<Integer>((o1,o2) -> {
            return o2.compareTo(o1);
        });
        for(int i=0;i<n;i++) {
            que.add(a[i]);
        }
        for(int i=0;i<K-1;i++) {
            que.poll();
        }

        return que.poll();
    }



     public void bubbleSort(int[] input) {
        for(int i=0;i<input.length-1;i++) {
            for(int j=i+1;j<input.length;j++) {
                
                if(input[i] > input[j]) {
                    int tmp = input[i];
                    input[i] = input[j];
                    input[j] = tmp;
                }
            }
        }
         
    }

    public void printArr(int[] input) {
        for(int i=0;i<input.length;i++) {
            System.out.print(input[i] + ",");
        }
        System.out.println();
    }


}

全部评论

相关推荐

09-17 17:09
门头沟学院 Java
雨忄:有人给出过解法,拖晚点去,然后到时候再找其他理由商量,既增加他们的筛人成本,不一定会给你收回offer ,也能占位避免工贼
秋招的嫡长offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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