반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 테스팅 자격증
- 알고리즘
- 연필소묘
- Kriss 재택
- 코딩
- 그림
- csts
- 클린 코드
- 재택근무
- 다비드상
- leetcode
- KSTQB
- Python
- 취미
- react
- IT 자격증
- 연필
- 웹개발
- 프로그래머스
- 코드잇
- IT자격증
- 파이썬
- 토익 환급
- 프로그래밍
- clean code
- 소묘
- 코딩테스트
- PrivateRouter
- 미켈란젤로
- 색연필
Archives
- Today
- Total
글모음
682. Baseball Game [Easy, Python] 본문
728x90
반응형
[ 정답 1 ]
- 카테고리: 스택
- Runtime: 35.97%
- Memory Usage: 48.21%
- 시간 복잡도 : O(n) - for문 하나
- 공간 복잡도 : O(n) - list 하나
class Solution:
def calPoints(self, ops):
record = []
for i in range(len(ops)):
try: record.append(int(ops[i]))
except:
if ops[i] == "C": record.pop()
elif ops[i] == "D": record.append(2* record[-1])
elif ops[i] == "+": record.append(record[-2] + record[-1])
return sum(record)
1. 값들을 저장할 list 하나 생성
2. ops에 들어있는 list 안의 element들이 전부 str 타입으로 들어있어서 숫자 연산(곱셈, 덧셈) 시에 오류가 나서 try-except문을 썼다.
3. 해당하는 문자에 따른 연산 수행
[ 정답 2 ]
class Solution:
def calPoints(self, ops):
record = []
for letter in ops:
if letter == "C": record.pop()
elif letter == "D": record.append(2* record[-1])
elif letter == "+": record.append(record[-2] + record[-1])
else: record.append(int(letter))
return sum(record)
i 를 쓰는 대신에 ops 리스트에 있는 요소들을 바로 반복으로 돌리고,
생각해보니 [C, D, +] 이외에 모든 문자들은 숫자라서 Stack에 숫자를 추가하는 부분을 else로 돌려 번거로웠던 try-except문을 제거했다.
try-except문을 제거하니 35.97%에서 88.87%로 더 빨라졌다.
Baseball Game - 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
반응형
'알고리즘 > Leetcode' 카테고리의 다른 글
[Leetcode] 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree [Python, Medium] (0) | 2021.06.18 |
---|---|
[Leetcode] 733. Flood Fill [Easy, Python] (0) | 2021.06.15 |
[Leetcode] 144. Binary Tree Preorder Traversal [Python, Easy] (0) | 2021.06.12 |
1441. Build an Array With Stack Operations [Easy, Python] (0) | 2021.03.06 |
Leetcode 문제풀이 목록 (0) | 2021.03.06 |
Comments