본문 바로가기
Leetcode

1441. Build an Array With Stack Operations

by YGSEO 2020. 7. 1.
728x90
class Solution:
    def buildArray(self, target: List[int], n: int) -> List[str]:
        ls = list(range(1, n+1))
        ans = []
        for i in range(n):
            if ls[i] in target:
                ans.append("Push")
            else:
                ans.append("Push")
                ans.append("Pop")
        return ans

헤맷던 점은 target list와 매칭을 어떻게 시켜야할지

잘 안되서 discussion에 가서 다른 사람 풀이를 보니 list를 하다 더 만들어서 매칭시킴

 

여기서 한 가지 더 조건이 있었어야 되는데

test case가

[1,2]
4

일때 이미 target과 매칭이 끝났을때 stack을 멈추고 리턴하는걸 넣어줘야 문제 조건에 부합.

 

따라서 최종 답안

class Solution:
    def buildArray(self, target: List[int], n: int) -> List[str]:
        ls = list(range(1, n+1))
        res = []
        ans = []
        for i in range(n):
            if ls[i] in target:
                ans.append("Push")
                res.append(ls[i])
                if res == target:
                    break
            else:
                ans.append("Push")
                ans.append("Pop")
        return ans

하지만 속도에서는 굉장히 느림.

하위..93%..

for 문이 돌아서 그런거 인거 같다.

 

728x90

'Leetcode' 카테고리의 다른 글

844. Backspace String Compare  (0) 2020.07.21
682. Baseball Game  (0) 2020.07.19
496. Next Greater Element I  (0) 2020.07.06
1047. Remove All Adjacent Duplicates In String  (0) 2020.07.05
1021. Remove Outermost Parentheses  (0) 2020.06.30

댓글