解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
defpop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if self.empty(): returnNone if self.stack_out: return self.stack_out.pop() else: for i inrange(len(self.stack_in)): self.stack_out.append(self.stack_in.pop()) return self.stack_out.pop()
defpeek(self) -> int: """ Get the front element. """ ans = self.pop() self.stack_out.append(ans) return ans
defempty(self) -> bool: """ 只要in或者out有元素,说明队列不为空 """ returnnot (self.stack_in or self.stack_out)
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
1 2
输入:s = "()" 输出:true
示例 2:
1 2
输入:s = "()[]{}" 输出:true
示例 3:
1 2
输入:s = "(]" 输出:false
思路:
使用栈来表示先进后出的特性
使用record={‘(‘:’)’,’[‘:’]’,’{‘:’}’}来存储键值对
遍历s,取出元素i,如果i存在于record的键中,则用栈来存储i对应的值
如果栈为空或者i不等于栈末尾元素,返回False
否则i等于栈中末尾元素则取出栈末尾元素
最后判断栈是否为空来输出错误与否
代码:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defisValid(s): sta=[] record={'(':')','[':']','{':'}'} for i in s: if i in record.keys(): sta.append(record[i]) elifnot sta or i !=sta[-1]: returnFalse else: sta.pop() returnTrueifnot sta elseFalse
classSolution: defremoveDuplicates(s): stack=[] for i in s: if stack and stack[-1]==i: stack.pop() elifnot stack: stack.append(i) else: stack.append(i) return''.join(stack)
classSolution: defevalRPN(tokens): stack=[] record=['+','-','*','/'] for i in tokens: if i notin record: stack.append(i) else: tmp1,tmp2=stack.pop(),stack.pop() stack.append(int(eval(f'{tmp2}{i}{tmp1}')) ) returnint(stack.pop())
239.滑动窗口最大值
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
classSolution: defmaxSlidingWindow(self, nums: List[int], k: int) -> List[int]: res = [] queue = collections.deque() for i, num inenumerate(nums): if queue and queue[0] == i - k:# 队列中最左侧元素索引不在窗口范围,出列 queue.popleft() while queue and nums[queue[-1]] < num:# 新入列元素,比新的入列小的都出列 queue.pop() queue.append(i)# 入列 if i >= k - 1:# 取出res res.append(nums[queue[0]]) return res
347.前 K 个高频元素
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
1 2
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
示例 2:
1 2
输入: nums = [1], k = 1 输出: [1]
思路:
使用字典统计每个元素出现的次数
对字典中的值进行排序
取前k个高频元素
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: deftopKFrequent(nums, k): record={} result=[] for i in nums: if i in record: record[i]+=1 else: record[i]=1 # 2.使用列表解析方法将学生字典转换为(value, key)的元组格式 tuplelist = [(val, key) for key, val in record.items()] # 3.使用sorted函数对元组列表student_list由分数高低进行排序 tuplelist_sorted = sorted(tuplelist,reverse=True) for j inrange(k): result.append(tuplelist_sorted[j][1]) return result