day11-stack&Queue-part02-7.13

tasks for day

1. 150逆波兰表达式求值.

2. 239. 滑动窗口最大值 (*有难度)

3. 前k个高频元素 (*有难度)

-----------------------------------------------------------

1. 150逆波兰表达式求值.

This practice is a typical one for stack.

In this practice, it is important to discriminate the left and right on two sides of a operator, which is subject to the .pop(), the first pop should be right, while the second pop should be left.

Besides, the round to zero is worth noting, because there is a special condition when the result is minus but also not integer.

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        pending = []
        for i in range(len(tokens)):
            if tokens[i] not in ['+', '-', '*', '/']:
                pending.append(int(tokens[i]))

            elif tokens[i] == "+":
                right = pending.pop()
                left = pending.pop()
                pending.append(left+right)

            elif tokens[i] == "-":
                right = pending.pop()
                left = pending.pop()
                pending.append(left-right)

            elif tokens[i] == "*":
                right = pending.pop()
                left = pending.pop()
                pending.append(left*right)

            elif tokens[i] == "/":
                right = pending.pop()
                left = pending.pop()
                # method 1
                # if left*right >= 0:
                #     pending.append(left//right)
                # else:
                #     if left % right == 0:
                #         pending.append(left//right)
                #     else:
                #         pending.append(left//right + 1)

                # method 2
                pending.append(int(left/right) if left*right >= 0 else - (abs(left)//abs(right)))

        return pending[0]
            

Go version. in go, the round to zero is easier and less complicated.

func evalRPN(tokens []string) int {
    pending := []int{}
    for _, token := range tokens {
        // this means transfer the token to integer, if err == nil which means the the transfer is correct, the val would be the integer  changed from the str
        val, err := strconv.Atoi(token)
        if err == nil {
            pending = append(pending, val)
        } else {
            num1, num2 := pending[len(pending) - 2], pending[len(pending) - 1]
            pending = pending[: len(pending) - 2]
            switch token{
                case "+":
                    pending = append(pending, num1+num2)
                case "-":
                    pending = append(pending, num1-num2)
                case "*":
                    pending = append(pending, num1*num2)
                case "/":
                    pending = append(pending, num1/num2)
            }
        }
    }
    return pending[0]
}

2. 239. 滑动窗口最大值 (*有难度)-- queue application

本题不可使用优先级队列(对于slide窗口的pop无法方便的进行操作),而要使用单调队列,单调队列的长度与维护的窗口的长度不同,这与顶堆是不一样的,可以保证更方便的pop操作进行维护,也同样可以像大顶堆一样实现最左侧为最大值

for example, for a slide window [3,5,-1]

the corresponding max-heap (大顶堆) might be [5,3,-1], while the corresponding 单调队列 would be [5, -1]

class MyQueue:
    def __init__(self):
        self.que = deque()
    def popQ(self, val):
        if self.que and val == self.que[0]:
            self.que.popleft() 
    
    def pushQ(self, val):
        while self.que and val > self.que[-1]:
            self.que.pop()
        self.que.append(val)
    
    def getBiggest(self):
        return self.que[0]

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        result = []
        QQQ = MyQueue()

        for i in range(k):
            QQQ.pushQ(nums[i])
        
        result.append(QQQ.getBiggest())

        for i in range(k, len(nums)):
            out_num = nums[i-k]
            in_num = nums[i]
            QQQ.popQ(out_num)
            QQQ.pushQ(in_num)
            result.append(QQQ.getBiggest())

        
        return result


3. 前k个高频元素 (*有难度)优先级队列:大小顶堆 (max/min-heap)

本体目标获取前k个高频元素,最适合的方式是大/小顶堆的方式,本质上就是一个二叉树;那么如何选择,由于想要的是前k个高频元素,所以应该选用小顶堆,保证每一次pop出的顶端元素都是当前最小的,所以到最后留下的k个顶堆中的元素就是前k个高频的结果,此时顶堆就是第k个结果

pay attention to how to use heapq module in python, this is used to operate on the min/max-heap, one thing worth to noting is the heap can restore tuple at each node, then the sequence for the heap would adhere to the first value in the tuple.

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        calcu = defaultdict(int)
        for i in range(len(nums)):
            calcu[nums[i]] += 1

        # method 1
        reverse_dict = defaultdict(list)
        for key in calcu:
            reverse_dict[calcu[key]].append(key)

        key_list = list(reverse_dict.keys())
        key_list.sort()

        count = 0
        result = []

        while key_list and count < k:
            result += reverse_dict[key_list[-1]]
            count += len(reverse_dict[key_list[-1]])
            key_list.pop()
        
        return result[:k]

        # method 2 with min-heap
        pri_list = []
        for key, val in calcu.items():
            heapq.heappush(pri_list, (val,key))
            if len(pri_list) > k:
                heapq.heappop(pri_list)
        
        result = [0]*k
        for i in range(k-1, -1, -1):
            result[i] = heapq.heappop(pri_list)[1]
        
        return result

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值