1. 程式人生 > 其它 >3.剪繩子,兩個棧實現佇列

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