堆排序做的,没有全部排序,找到第k个就结束
public int findKthLargest(int[] nums, int k) { int num = 0; if (nums.length <= 1) return nums[0]; int heapSize = nums.length; //1.构建最大堆 int half = (heapSize-2)/2; for (int i = half;i >= 0;i--) { adjust(nums,heapSize,i); } while (heapSize > 1) { //2.取出最大值 swap(0,heapSize-1,nums); heapSize--; num++; if(num == k) break; //3.调整堆 adjust(nums,heapSize,0); } return nums[nums.length-k]; } public void adjust(int[] nums,int heapSize,int index) { int left = index*2+1; int right = index*2+2; int biggest = index; if (left < heapSize && nums[left] > nums[biggest]) biggest = left; //注意这里都是和nums[biggest]比较,别写成index,因为要找出最大的值 if (right < heapSize && nums[right] > nums[biggest]) biggest = right; if (biggest != index) { swap(index,biggest,nums); adjust(nums,heapSize,biggest); } } public void swap(int a,int b,int[] nums) { int temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; }
时间: 2024-10-06 01:21:58