215. Kth Largest Element in an Array找出数组中第k大的值

Posted stAr_1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了215. Kth Largest Element in an Array找出数组中第k大的值相关的知识,希望对你有一定的参考价值。

堆排序做的,没有全部排序,找到第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;
    }

 

以上是关于215. Kth Largest Element in an Array找出数组中第k大的值的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-215. Kth Largest Element in an Array

#Leetcode# 215. Kth Largest Element in an Array

LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

LN : leetcode 215 Kth Largest Element in an Array

215. Kth Largest Element in an Array

215. Kth Largest Element in an Array