Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9068d1b

Browse files
authored
Merge pull requestneetcode-gh#1476 from connoralydon/python-682-baseball-game
Create: python/682-baseball-game.py
2 parents9ed0176 +4219bb9 commit9068d1b

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution:
2+
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
3+
4+
# O (n + m)
5+
nums1Idx = { n:i for i, n in enumerate(nums1) }
6+
res = [-1] * len(nums1)
7+
8+
stack = []
9+
for i in range(len(nums2)):
10+
cur = nums2[i]
11+
12+
# while stack exists and current is greater than the top of the stack
13+
while stack and cur > stack[-1]:
14+
val = stack.pop() # take top val
15+
idx = nums1Idx[val]
16+
res[idx] = cur
17+
18+
if cur in nums1Idx:
19+
stack.append(cur)
20+
21+
return res
22+
23+
24+
# O (n * m)
25+
nums1Idx = { n:i for i, n in enumerate(nums1) }
26+
res = [-1] * len(nums1)
27+
28+
for i in range(len(nums2)):
29+
if nums2[i] not in nums1Idx:
30+
continue
31+
for j in range(i + 1, len(nums2)):
32+
if nums2[j] > nums2[i]:
33+
idx = nums1Idx[nums2[i]]
34+
res[idx] = nums2[j]
35+
break
36+
37+
return res

‎python/682-Baseball-Game.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
classSolution:
2+
defcalPoints(self,operations:List[str])->int:
3+
4+
score_stack= []
5+
6+
foroinoperations:
7+
8+
# it is +, D, or C
9+
# if stack isn't of sufficient length, then operation is voided
10+
ifo=="+"andlen(score_stack)>=2:
11+
summed=score_stack[-2]+score_stack[-1]
12+
score_stack.append(summed)
13+
14+
elifo=="D"andlen(score_stack)>=1:
15+
doubled=score_stack[-1]*2
16+
score_stack.append(doubled)
17+
18+
elifo=="C"andlen(score_stack)>=1:
19+
score_stack.pop()
20+
21+
else:
22+
score_stack.append(int(o))
23+
24+
returnsum(score_stack)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp