解释: 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: self.size -= 1 out = self.queue[0] self.queue = self.queue[1:] return out
defpeek(self) -> int: return self.queue[0]
defempty(self) -> bool: if self.size != 0: returnFalse returnTrue
# Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
defempty(self) -> bool: if self.in_queue or self.out_queue: returnFalse returnTrue
# Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
defempty(self) -> bool: if self.size: returnFalse returnTrue
# Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
# Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
def__init__(self): """ Initialize your data structure here. """ self.queue = collections.deque()
defpush(self, x: int) -> None: """ Push element x onto stack. """ n = len(self.queue) self.queue.append(x) for _ inrange(n): self.queue.append(self.queue.popleft())
defpop(self) -> int: """ Removes the element on top of the stack and returns that element. """ return self.queue.popleft()
deftop(self) -> int: """ Get the top element. """ return self.queue[0]
defempty(self) -> bool: """ Returns whether the stack is empty. """ returnnot self.queue
/** Removes the element on top of the stack and returns that element. */ func(s *MyStack) Pop() int { v := s.queue1[0] s.queue1 = s.queue1[1:] return v }
/** Get the top element. */ func(s *MyStack) Top() int { return s.queue1[0] }
/** Returns whether the stack is empty. */ func(s *MyStack) Empty() bool { returnlen(s.queue1) == 0 }
#本人解法 classSolution: defisValid(self, s: str) -> bool: iflen(s)%2: returnFalse stack = [] for v in s: if v == ")": if stack and stack[-1] == "(": stack.pop() else: returnFalse elif v == "]": if stack and stack[-1] == "[": stack.pop() else: returnFalse elif v == "}": if stack and stack[-1] == "{": stack.pop() else: returnFalse else: stack.append(v) returnnot stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defisValid(self, s: str) -> bool: iflen(s) % 2 == 1: returnFalse pairs = { ")": "(", "]": "[", "}": "{", } stack = list() for ch in s: if ch in pairs: ifnot stack or stack[-1] != pairs[ch]: returnFalse stack.pop() else: stack.append(ch) returnnot stack
#栈 classSolution: defremoveDuplicates(self, s: str) -> str: stk = list() for ch in s: if stk and stk[-1] == ch: stk.pop() else: stk.append(ch) return"".join(stk)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#双指针 classSolution: defremoveDuplicates(self, s: str) -> str: b = list(s) slow = fast = 0 l = len(b) while fast < l: b[slow] = b[fast] if slow and b[slow] == b[slow - 1]: slow -= 1 else: slow += 1 fast += 1 return"".join(b[:slow])
Go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//双指针 funcremoveDuplicates(s string)string { b := []byte(s) slow, fast := 0, 0 l := len(s) for fast < l { b[slow] = b[fast] if slow > 0 && b[slow] == b[slow-1] { slow-- } else { slow++ } fast++ } returnstring(b[0:slow]) }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//本人解法 funcremoveDuplicates(s string)string { var stack []rune outer: for _, v := range s { l := len(stack) for l != 0 && stack[l-1] == v { stack = stack[:l-1] continue outer } stack = append(stack, v) } returnstring(stack) }
1 2 3 4 5 6 7 8 9 10 11
funcremoveDuplicates(s string)string { stack := []byte{} for i := range s { iflen(stack) > 0 && stack[len(stack)-1] == s[i] { stack = stack[:len(stack)-1] } else { stack = append(stack, s[i]) } } returnstring(stack) }
//自己写的一种很傻的解法 funcremoveDuplicates(s string)string { iflen(s) >= 2 { b := []byte(s) for { f := false for i := 0; i < len(b)-1; i++ { if b[i] == b[i+1] { b = append(b[:i], b[i+2:]...) f = true } } if f == false { break } } returnstring(b) } return s }
funcevalRPN(tokens []string)int { var stack []int operators := map[string]func(int, int)int{ "+": func(x, y int)int { return x + y }, "-": func(x, y int)int { return x - y }, "*": func(x, y int)int { return x * y }, "/": func(x, y int)int { return x / y }, }
for _, token := range tokens { if operator, ok := operators[token]; ok { operand2 := stack[len(stack)-1] operand1 := stack[len(stack)-2] stack = stack[:len(stack)-2] result := operator(operand1, operand2) stack = append(stack, result) } else { num, _ := strconv.Atoi(token) stack = append(stack, num) } } return stack[0] }
funcevalRPN(tokens []string)int { stack := make([]int, (len(tokens)+1)/2) index := -1
operators := map[string]func(int, int)int{ "+": func(x, y int)int { return x + y }, "-": func(x, y int)int { return x - y }, "*": func(x, y int)int { return x * y }, "/": func(x, y int)int { return x / y }, }
for _, token := range tokens { if val, err := strconv.Atoi(token); err == nil { index++ stack[index] = val } else { index-- stack[index] = operators[token](stack[index], stack[index+1]) } }
# 处理前k个元素,维护一个递减队列 for i inrange(k): while q and nums[i] >= nums[q[-1]]: q.pop() # 如果新来的数比队尾元素要大,则队尾元素出队 q.append(i) # 默认新来的数入队
ans = [nums[q[0]]] # 把队首元素加入结果中,因为它是当前最大的元素
for i inrange(k, n): # 对数组剩余元素执行上述操作 while q and nums[i] >= nums[q[-1]]: q.pop() q.append(i) while q[0] <= i - k: # 如果队首元素不在滑动窗口范围内,要移除 q.popleft() ans.append(nums[q[0]]) # 把队首元素加入结果
# 首次形成窗口 for i inrange(k): push(i) # 取首个窗口的最大值 ans = [nums[q[0]]] # 滑动窗口并更新结果 for i inrange(k, len(nums)): push(i) # 如果队列头部的值已经离开了窗口,那么将其从队列中移除 while q[0] <= i - k: q = q[1:] # 将当前窗口最大值放入结果数组 ans.append(nums[q[0]]) # 返回结果数组 return ans
defpop(self, value): """ 每次弹出的时候,比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出。 同时pop之前判断队列当前是否为空。 """ if self.queue and value == self.queue[0]: self.queue.popleft()
defpush(self, value): """ 如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。 这样就保持了队列里的数值是单调从大到小的了。 """ while self.queue and value > self.queue[-1]: self.queue.pop() self.queue.append(value)
// Pop 方法用于从堆中移除元素 func(h *hp) Pop() interface{} { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v }
// maxSlidingWindow 是滑动窗口最大值的具体实现 funcmaxSlidingWindow(nums []int, k int) []int { // 赋值 a a = nums // 创建 hp 结构体实例 q := &hp{make([]int, k)} // 初始堆 for i := 0; i < k; i++ { q.IntSlice[i] = i } // 初始整理堆 heap.Init(q)
n := len(nums) // 开始滑动窗口操作 ans := make([]int, 1, n-k+1) ans[0] = nums[q.IntSlice[0]] for i := k; i < n; i++ { heap.Push(q, i) for q.IntSlice[0] <= i-k { heap.Pop(q) } ans = append(ans, nums[q.IntSlice[0]]) } return ans }
给你一个整数数组 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]
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
Python:
1 2 3 4 5 6
classSolution: deftopKFrequent(self, nums: List[int], k: int) -> List[int]: m = defaultdict(int) for i in nums: m[i] += 1 returnsorted(m, key=lambda x: m[x], reverse=True)[:k]
1 2 3 4 5 6 7
classSolution: deftopKFrequent(self, nums: List[int], k: int) -> List[int]: m = defaultdict(int) for i in nums: m[i] += 1 top = sorted(m.values(), reverse=True)[:k] return [k for k in m if m[k] in top]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: deftopKFrequent(self, nums: List[int], k: int) -> List[int]: # 统计每个数字出现的频次 occurrences = {} for num in nums: occurrences[num] = occurrences.get(num, 0) + 1
# 建立最小堆 min_heap = [] for key, value in occurrences.items(): heapq.heappush(min_heap, (value, key)) iflen(min_heap) > k: heapq.heappop(min_heap)
# 将堆中的元素取出,放入返回结果 result = [heapq.heappop(min_heap)[1] for _ inrange(k)]
# 返回最频繁的k个元素 return result
Go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//本人解法,简单暴力 functopKFrequent(nums []int, k int) []int { m := make(map[int]int) for _, v := range nums { m[v]++ } keys := make([]int, 0, len(m)) for key := range m { keys = append(keys, key) } sort.Slice(keys, func(i, j int)bool { return m[keys[i]] > m[keys[j]] }) return keys[:k] }