215. 数组中的第K个最大元素

package leetcode;

import java.util.Comparator;
import java.util.PriorityQueue;

public class demo_215 {
    //建立一个大顶堆
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> priorityQueue=new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer a,Integer b) {
                return b-a;
            }
        });
        //如果找出第k个大的元素,即建立一个nums.length-k+1大小的大顶堆
        for(int i=0;i<nums.length-k+1;i++) {
            priorityQueue.offer(nums[i]);
        }
        //找出nums.length-k个小元素,则堆顶就是第k个大的元素
        for(int i=nums.length-k+1;i<nums.length;i++) {
            if(nums[i]<priorityQueue.peek()) {
                priorityQueue.poll();
                priorityQueue.offer(nums[i]);
            }
        }
        return priorityQueue.peek();
    }
    
    
    //用快速排序,找出第K个元素
    public int partition(int[] nums,int low,int high) {
        int temp=nums[low];
        while(low<high) {
            while(low<high&&nums[high]>=temp) {
                high--;
            }
            nums[low]=nums[high];
            while(low<high&&nums[low]<=temp) {
                low++;
            }
            nums[high]=nums[low];
        }
        nums[low]=temp;
        return low;
    }
    
    public int findKthLargest2(int[] nums, int k) {
        int target=nums.length-k;
        int left=0;
        int right=nums.length-1;
        int index;
        while(true) {
            index=partition(nums,left, right);
            if(index<target) {
                left=index+1;
            }
            if(index>target) {
                right=index-1;
            }
            if(index==target) {break;}
        }
        return nums[index];
    }
   
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nums= {3,2,1,5,6,4};
        demo_215 demo=new demo_215();
        System.out.println(demo.findKthLargest2(nums, 2));
    }

}

 

posted on 2022-03-26 16:16  一仟零一夜丶  阅读(30)  评论(0)    收藏  举报