复试leetcode刷题(1):215

215 Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.


解题思路:之前这一题是使用快排来做,今天刚复习了堆排序,所以使用堆排序来做,因为堆排序是重复调整n次二叉树的根节点和最后一个非有序节点,那么我们只需要做k次这个循环就可以找到。核心代码如下,在必要地方已经加上注释


//堆的调整操作,自上而下,调整的是[start,end]之间的节点
void heap_adjust(vector<int>& nums,int start,int end){
    int change=nums[start];//此次调整将要交换的值(若发生交换一定是该值和它的后代进行交换)
    int left_child=start*2+1;//当前节点的左孩子
    int current=start;//标记当前调整根节点

    //每次遍历当前调整根节点的左右孩子
    for(;left_child<=end;current=left_child,left_child=left_child*2+1){

    	//选出左右孩子值较大的 因为有left_child+1所以要注意判断是否越界
        if(left_child<end&&nums[left_child]<nums[left_child+1]){
            left_child+=1;
        }
        //若大于当前节点值就进行修改
        if(change<nums[left_child]){
            nums[current]=nums[left_child];
            nums[left_child]=change;
        }
        //不大于表示已经符合最大堆
        else
            break;
    }
}

int heap_sort(vector<int>& nums, int k){
    int size=nums.size();
    int last_node=size/2-1;
    int ans=-1000000;
    //初始化非有序堆(从最后一个非叶子节点开始,倒着来)
    for(;last_node>=0;last_node--)
        heap_adjust(nums,last_node,size-1);

    //进行n此调整,每次把根节点移到最后,然后调整剩余非有序堆
    for(int i=size-1;i>=size-k;i--){
        //ans=nums[0];
        int temp=nums[i];
        nums[i]=nums[0];
        nums[0]=temp;
        heap_adjust(nums,0,i-1);
    }
    ans=nums[size-k];
    return ans;
}

开始刷题的第一天,加油!坚持就是胜利!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值