lintcode-medium-Heapify

本文介绍了一个将整数数组转换为最小堆数组的方法。通过使用调整操作确保每个节点都小于其子节点,从而形成一个合法的最小堆结构。

Given an integer array, heapify it into a min-heap array.

For a heap array A, A[0] is the root of heap, and for each A[i], A[i * 2 + 1] is the left child of A[i] and A[i * 2 + 2] is the right child of A[i].

 

 Given [3,2,1,4,5], return [1,2,3,4,5] or any legal heap array.

public class Solution {
    /**
     * @param A: Given an integer array
     * @return: void
     */
    public void heapify(int[] A) {
        // write your code here
        
        if(A == null || A.length == 0)
            return;
        
        for(int i = A.length / 2; i >= 0; i--){
            adjust(A, i);
        }
        
        return;
    }
    
    public void adjust(int[] A, int i){
        int left = i * 2 + 1;
        int right = i * 2 + 2;
        
        int min = i;
        
        if(left < A.length && A[left] < A[min])
            min = left;
        if(right < A.length && A[right] < A[min])
            min = right;
        
        if(i == min)
            return;
        
        swap(A, i, min);
        adjust(A, min);
        
        return;
    }
    
    public void swap(int[] A, int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
        
        return;
    }
    
}

 

转载于:https://www.cnblogs.com/goblinengineer/p/5305993.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值