Skip to content

Commit 002bed0

Browse files
authored
Merge pull request #1198 from imrushi/leetcode-239
Create Go: solution for 239-Sliding-Window-Maximum.go and 150-Evaluate-Reverse-Polish-Notation.go
2 parents c73f583 + d82b49b commit 002bed0

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

Diff for: go/150-Evaluate-Reverse-Polish-Notation.go

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
func evalRPN(tokens []string) int {
2+
var stack []int
3+
var a, b int
4+
for _, c := range tokens {
5+
switch c {
6+
case "+":
7+
a, b, stack = getAndPopLastOperand(stack)
8+
stack = append(stack, (a + b))
9+
case "-":
10+
a, b, stack = getAndPopLastOperand(stack)
11+
stack = append(stack, (a - b))
12+
case "*":
13+
a, b, stack = getAndPopLastOperand(stack)
14+
stack = append(stack, (a * b))
15+
case "/":
16+
a, b, stack = getAndPopLastOperand(stack)
17+
stack = append(stack, (a / b))
18+
default:
19+
i, _ := strconv.Atoi(c)
20+
stack = append(stack, i)
21+
}
22+
}
23+
return stack[0]
24+
}
25+
26+
func getAndPopLastOperand(stack []int) (int, int, []int) {
27+
a := stack[len(stack)-2]
28+
b := stack[len(stack)-1]
29+
stack = stack[:len(stack)-2]
30+
31+
return a, b, stack
32+
}

Diff for: go/239-Sliding-Window-Maximum.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
func maxSlidingWindow(nums []int, k int) []int {
2+
// get top/last element of queue: q[len(q)-1]
3+
// pop/remove from the top/last element of queue: q[:len(q)-1]
4+
// remove left value from queue: q[1:]
5+
output := []int{}
6+
q := make([]int, 0)
7+
l, r := 0, 0
8+
9+
for r < len(nums) {
10+
// pop smaller values from q
11+
for len(q) != 0 && nums[q[len(q)-1]] < nums[r] {
12+
q = q[:len(q)-1]
13+
}
14+
q = append(q, r)
15+
16+
// remove left val from window
17+
if l > q[0] {
18+
q = q[1:]
19+
}
20+
21+
if (r + 1) >= k {
22+
output = append(output, nums[q[0]])
23+
l++
24+
}
25+
r++
26+
}
27+
return output
28+
}

0 commit comments

Comments
 (0)