글모음

1441. Build an Array With Stack Operations [Easy, Python] 본문

알고리즘/Leetcode

1441. Build an Array With Stack Operations [Easy, Python]

Nova_61 2021. 3. 6. 10:29
728x90
반응형

 

1부터 n까지의 숫자들을 list에 넣고, 넣을 때 "Push"

만약 target에 해당하는 숫자가 없다면 제거하면서 "Pop"

기초적인 stack 문제다.

 

 

 

[ 코드 1 ]

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

Push, Pop을 넣어줄 정답 리스트 ans 

굳이 추가로 list를 만들어주지 않아도 괜찮지만  숫자들이 Push, Pop 되는 과정을 보고 싶어서 숫자를 넣을 stack list인 temp를 만들었다.

생각해보니 temp와 target이 같으면 지워주는 라인은 필요가 없는 듯..

 

[ 코드 2 ]

    def buildArray_2(self, target, n):
        ans = []
        for i in range(1,n+1):
            ans.append("Push")
            if i not in target:
                ans.append("Pop")
        return ans

temp 리스트도 지우고 좀 더 깔끔하게 다듬어봤다.

 

 

 

 

Build an Array With Stack Operations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

728x90
반응형
Comments