每日N+1题 -- 算法练习 Day4

题目主要来源:LeetCode。主要选自剑指offer程序员面试宝典
每日尽可能保持 N+1 道题,N 取 0 到 9。

部分解法是从LeetCode上大佬们的解法中拿过来的,如有侵权,告知立删

0x01 剑指 Offer 06. 从尾到头打印链表

/**
 * JZ6  利用栈的特性
 *
 * @author Anjude
 * @date 2021/7/5 23:25
 */
public class JZ6 {
    public int[] reversePrint(ListNode head) {
        int n = 0;
        Stack<Integer> s = new Stack<>();
        while (head != null){
            n++;
            s.push(head.val);
            head = head.next;
        }
        int[] res = new int[n];
        for (int i = 0; i < n; i++){
            res[i] = s.pop();
        }
        return res;
    }
}

0x02 剑指 Offer 07. 重建二叉树

/**
 * JZ7  TODO
 * 这题还没理解
 *
 * @author Anjude
 * @date 2021/7/5 23:34
 */
public class JZ7 {
    //利用原理,先序遍历的第一个节点就是根。在中序遍历中通过根 区分哪些是左子树的,哪些是右子树的
    //左右子树,递归
    HashMap<Integer, Integer> map = new HashMap<>();//标记中序遍历
    int[] preorder;//保留的先序遍历

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        for (int i = 0; i < preorder.length; i++) {
            map.put(inorder[i], i);
        }
        return recursive(0,0,inorder.length-1);
    }

    /**
     * @param pre_root_idx  先序遍历的索引
     * @param in_left_idx  中序遍历的索引
     * @param in_right_idx 中序遍历的索引
     */
    public TreeNode recursive(int pre_root_idx, int in_left_idx, int in_right_idx) {
        //相等就是自己
        if (in_left_idx > in_right_idx) {
            return null;
        }
        //root_idx是在先序里面的
        TreeNode root = new TreeNode(preorder[pre_root_idx]);
        // 有了先序的,再根据先序的,在中序中获 当前根的索引
        int idx = map.get(preorder[pre_root_idx]);

        //左子树的根节点就是 左子树的(前序遍历)第一个,就是+1,左边边界就是left,右边边界是中间区分的idx-1
        root.left = recursive(pre_root_idx + 1, in_left_idx, idx - 1);

        //由根节点在中序遍历的idx 区分成2段,idx 就是根

        //右子树的根,就是右子树(前序遍历)的第一个,就是当前根节点 加上左子树的数量
        // pre_root_idx 当前的根  左子树的长度 = 左子树的左边-右边 (idx-1 - in_left_idx +1) 。最后+1就是右子树的根了
        root.right = recursive(pre_root_idx + (idx-1 - in_left_idx +1)  + 1, idx + 1, in_right_idx);
        return root;
    }
}

0x03 剑指 Offer 14- I. 剪绳子

/**
 * JZ14  平均分段乘积最大,拆成3的乘积最大
 *
 * @author Anjude
 * @date 2021/7/7 23:46
 */
public class JZ14 {
    public int cuttingRope(int n) {
        if (n <= 3) return n - 1;
        int remain = n % 3;
        int s = n / 3;
        if (remain == 0) return (int) Math.pow(3, s);
        if (remain == 1) return (int) Math.pow(3, s - 1) * 4;
        return (int) Math.pow(3, s) * 2;
    }

    public static void main(String[] args) {
        JZ14 jz14 = new JZ14();
        System.out.println(jz14.cuttingRope(10));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值