1. 程式人生 > 其它 >擴充套件盧卡斯定理 學習筆記

擴充套件盧卡斯定理 學習筆記

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)); } }