Programming Camp – Algorithm Training Camp – Day 13

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
            
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值