3.剪绳子,两个栈实现队列

1.剪绳子

https://leetcode-cn.com/problems/jian-sheng-zi-lcof/

	public int cuttingRope(int n) {
         //绳子至少剪2段
        if (n == 2) return 1;
        if (n == 3) return 2;
        //定义状态数组,dp[i]表示长度为i的绳子,分段之后的各段乘积
        //对于每一段绳子长度为1,则对乘积毫无增益。从长度为2开始剪
        int[] dp = new int[n + 1];
        dp[2] = 1;
        dp[3] = 2;
        for (int i = 4; i <= n; i++) {
            // 剪去一段绳子后,其余的绳子可以选择剪或者不减
            // 在定长的绳子中一直循环剪取,找最优解
            for (int j = 2; j <= i - 2; j++) {
                dp[i] = Math.max(Math.max(dp[i - j], i - j) * j, dp[i]);
            }
        }
        return dp[n];
    }

2.两个栈实现队列

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/

class CQueue {
    // 初始化两个栈完成队列功能;
    Stack<Integer> stack1 = null;
    Stack<Integer> stack2 = null;

    public CQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void appendTail(int a) {
        stack1.push(a);
    }

    public int deleteHead() {
        //  stack1中的元素倒序,添加到stack2中
        //  先添加元素,在请求出栈
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        //   元素出栈
        if (stack2.isEmpty()) {
            return -1;
        } else {
            return stack2.pop();
        }
    }
}

2021.11.28 16:09

posted @ 2021-11-28 16:11  哟喝  阅读(45)  评论(0)    收藏  举报