Friday, September 4, 2020

LeetCode [946] Validate Stack Sequences

 946. Validate Stack Sequences

Medium

Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

 

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

 

Constraints:

  • 0 <= pushed.length == popped.length <= 1000
  • 0 <= pushed[i], popped[i] < 1000
  • pushed is a permutation of popped.
  • pushed and popped have distinct values.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stk = new Stack<>();
        int i = 0, j = 0, n = pushed.length;
        while(i<n || j<n){
            if(!stk.isEmpty() && popped[j]==stk.peek()){
                stk.pop();
                j++;
            }else if(i<n){
                stk.push(pushed[i++]);
            }else{
                return false;
            }
        }
        return true;
    }
}


YMSF

4. 酒似遛的变体,stack的模拟操作,这个stack push的rule是必须先放k, 才能放k+1,输入是0到n的permutation,代表pop出stack的顺序,问你给定的输入是否能实现

一个valid的输入例子是(4,3,5,2,1,0),从0一值push到4,然后pop 4,3,然后push 5,然后pop 5,继续pop 2,1,0

第四题,提供一个思路,因为输入的array A代表pop的order,当traverse A的时候,想要A能pop,则比A小且>= 0的数字都必须在这之前都push到stack上,所以对于A的判断,是要么需要push,要么需要pop

我觉得是这样:push的rule是必须先放k, 才能放k+1,意思就是push的顺序就是0,1 2 3.。。然后输入是0到n的permutation, 那自然就变成的楼主说的那道题

请教LZ 第四题的思路。感觉跟利口那题还是不太一样。或者我确实没想明白,能否大概share 下思路,或者 判断 不合理 输入的pattern。

我能想到一些不合理的,但是不太能 归纳起来成为 规律。


YMSF

第二轮,给一串input,一串output,判断output是否有可能是input用stack输出的结果。followup:只能使用O(1)space。

楼主第二题,这个是distinct的value吗?还是可以有重复值?

没有重复值


FOLLOW UP,INPUT和OUTPUT都是存在一个类似ARRAY的结构里面吗?如果是这样的话,O(1)是不是只要拿存INPUT的ARRAY模拟STACK操作就好


好像只用O1 space无法用array模拟stack吧…

我最后做出来是n^2time complexity,在outputinputindex的情况下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
//o(n) space
class Solution {
    //pushed is working as a stack
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int n = pushed.length;
        int i = 0, j = 0;
        for(int x : pushed){
            pushed[i] = x;
            while(i>=0 && pushed[i]==popped[j]){
                i--;
                j++;
            }
            i++;
        }
        
        return i==0;
    }
}

No comments:

Post a Comment