1. Evaluate Reverse Polish Notation (Leetcode Number: 150)
Copy the element to the stack if it's operand -> complete the arithmetic operation of the last element and the second last element in the stack when the element of the original list is detected to be an operator. Be aware of the sequence of those two elements extracted from the stack is (the second last operand in the stack)(operator)(last operand in the stack) -> append the result to the stack
For Python, the following function could be used to simplify the codes.
eval(f'{second_num} {item} {first_num}')
General Solution
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for i in range(len(tokens)):
if tokens[i] != "+" and tokens[i] != "-" and tokens[i] != "/" and tokens[i] != "*":
stack.append(tokens[i])
else:
last_val = int(stack.pop())
sec_last_val = int(stack.pop())
if tokens[i] == "+":
pb_val = sec_last_val + last_val
elif tokens[i] == "-":
pb_val = sec_last_val - last_val
elif tokens[i] == "/":
pb_val = sec_last_val / last_val
else:
pb_val = sec_last_val * last_val
stack.append(pb_val)
return False if len(stack) != 1 else int(stack[0])
2. Sliding Window Maximum (Leetcode Number: 239)
TBC
3. Top K Frequent Elements (Leetcode Number: 347)
By applying the heap queue, the smallest value could always be removed first.
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# Create dictionary to store the numbers as keys and respective frequency as the values
dic_freq = {}
for number in nums:
if number in dic_freq:
dic_freq[number] += 1
else:
dic_freq[number] = 0
# Optimize the above loop by using
# dic_freq[number] = dic_freq.get(number, 0) + 1
# Create heap queue
top_fre = []
for num, freq in dic_freq.items():
heapq.heappush(top_fre, (freq, num))
# Remove the element with smallest frequency value to restrict the amount of elements in the heap is k
if len(top_fre) > k:
heapq.heappop(top_fre)
# Take elements out and store them in a list
res = [0] * k
for i in range(k - 1, -1, -1):
res[i] = heapq.heappop(top_fre)[1]
return res