Leetcode1167 棍棒拼接最少成本

题意:You have some sticks with positive integer lengths.
You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. You perform this action until there is one stick remaining.
Return the minimum cost of connecting all the given sticks into one stick in this way.

思路:由于越开始拼接的棍棒使用次数越多,被累加的次数也越多,从而会让整体成本上升,我们可以每次拼接时,选取当前棍棒里长度最短的,这样成本会相对最低。
代码思路:构建最小堆(堆顶为最小元素), 每次弹出的都是堆中的最小值。
算法复杂度分析:N*logN

代码:

private static int findMinCost(int[] a) {
        for (int i = 0; i < a.length; i++) {
            heapInsert(a, i);              //构建堆,从尾部插入
        }
        int size = a.length, res = 0, precious = a[0];
        boolean used = false;
        swap(a, 0, --size);//将根节点与最后一个节点交换,size--,相当于删去根节点
        //逐步删除根节点
        while (size > 0) {
            heapify(a, 0, size); // 堆重构
            if (used) {
                precious = a[0];
                swap(a, 0, --size);//将根节点与最后一个节点交换,size--,相当于删去根节点
            } else {
                res += precious + a[0]; // 当前最小的两个数求和
                a[0] = precious + a[0]; // 替换
            }
            used = !used;
        }
        return res;
    }
    //重构堆(index为起始位置,size为节点数目,相当于终止位置的后一位置)
    public static void heapify(int[] arr, int index, int size) {
        int left = index * 2 + 1;//当前节点的左孩子,left+1为右节点index
        while (left < size) {
            int smallest = left + 1 < size && arr[left + 1] < arr[left] ? left + 1 : left;//左右孩子中较小孩子的下标
            smallest = arr[smallest] < arr[index] ? smallest : index;//当前节点与最小孩子比较,找到最小值的下标
            if (smallest == index) {
                break;//当前节点就是最小值,不用继续重构堆了,直接返回
            }
            swap(arr, smallest, index);//有比自己xiao的孩子,交换
            index = smallest;//当前节点变为比自己xiao的孩子
            left = index * 2 + 1;//更新左孩子index
        }
    }

    public static void heapInsert(int[] arr, int index) {
        while (arr[index] < arr[(index - 1) / 2])//节点值大于父节点
        {
            swap(arr, index, (index - 1) / 2);
            index = (index - 1) / 2;//节点变为父节点
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值