把二叉树打印成多行&&子数组最大乘积&&把数字翻译成字符串

133 阅读1分钟

NC80 把二叉树打印成多行

题目链接

1、解题思路

借助队列,实现树的层次遍历。

2、代码
import java.util.*;


/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        if(pRoot == null){
            return lists;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(pRoot);
        while (!queue.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
                list.add(poll.val);
            }
            lists.add(list);
        }
        return lists;
    }
    
}

NC83 子数组最大乘积

题目链接

1、解题思路

定义两个变量,分别保存此下标之前的子数组乘积的最大值和最小值,for循环依次更新就好。

2、代码
public class Solution {
    public double maxProduct(double[] arr) {
        double ans = arr[0];
        double max = arr[0];
        double min = arr[0];
        for (int i = 1; i < arr.length; i++) {
            double temp = max;
            max = Math.max(Math.max(arr[i], arr[i] * max), arr[i] * min);
            min = Math.min(Math.min(arr[i], temp * arr[i]), min * arr[i]);
            if (ans < max) {
                ans = max;
            }
        }
        return ans;
    }
}

NC116 把数字翻译成字符串

题目链接

1、解题思路

简单dp,需要处理一下边界问题。

2、代码
import java.util.*;


public class Solution {
    /**
     * 解码
     * @param nums string字符串 数字串
     * @return int整型
     */
    public int solve (String nums) {
        char[] chars = nums.toCharArray();
        int len = nums.length();
        int[] dp = new int[len];
        for (int i = 0; i < nums.length(); i++) {
            if (chars[i] == '0') {
                dp[i] = 0;
            } else {
                dp[i] = i - 1 < 0 ? 1 : dp[i - 1];
            }
            if (i != 0 && chars[i - 1] != '0') {
                int val = (chars[i - 1] - 48) * 10 + chars[i] - 48;
                if (val <= 26) {
                    dp[i] += i >= 2 ?dp[i - 2]:1;
                }
            }
        }
        return dp[len - 1];
    }
}