classSolution: defmaxInWindows(self , num: List[int], size: int) -> List[int]: # write code here res = [] #窗口大于数组长度的时候,返回空 if size <= len(num) and size != 0: #数组后面要空出窗口大小,避免越界 for i inrange (len(num) - size + 1): #寻找每个窗口最大值 max = 0; for j inrange(i, i + size): if num[j] > max: max = num[j] res.append(max) return res
滑动窗口的最大和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Solution: def maxInWindows(self, num: List[int], size: int) -> List[int]: res = [] n = len(num) # 如果窗口大小大于数组长度或为0,直接返回空列表 ifsize > n or size == 0: return res # 初始化第一个窗口的和 window_sum = sum(num[:size]) res.append(window_sum) # 滑动窗口,计算每个窗口的和 for i in range(size, n): window_sum = window_sum - num[i - size] + num[i] res.append(window_sum) return res
#O(nlogn) O(logn)
合并区间 排序 + 一次遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defmerge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ intervals.sort(key=lambda x: x[0]) res = [intervals[0]] # 将第一个区间加入答案,然后依次考虑之后的每个区间: for i inrange(1, len(intervals)): # 如果答案数组中最后一个区间的右端点小于当前考虑区间的左端点,说明两个区间不会重合,因此我们可以直接将当前区间加入答案数组末;否则,说明两个区间重合,我们需要用当前区间的右端点更新答案数组中最后一个区间的右端点,将其置为二者的较大值。最后,我们返回答案数组即可。 if intervals[i][0] <= res[-1][1]: res[-1][1] = max(intervals[i][1], res[-1][1]) else: res.append(intervals[i]) return res
defnumSubarrayProductLessThanK(nums, k): if k == 0: return0 ans, s, j = 0, 1, 0 for i, v inenumerate(nums): s *= v while j <= i and s >= k: s //= nums[j] j += 1 if s < k: for m inrange(j, i+1): temp = nums[m:i+1] print(temp) ans += i - j + 1 return ans defmain(): nums = list(map(int, input().split())) k = int(input()) result = numSubarrayProductLessThanK(nums, k) return result print(main())
classSolution: defgetIntersectionNode(self, headA, headB): # 检测链表是否存在环 defhasCircle(head): slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: # 存在环 p = head q = slow while p != q: p = p.next q = q.next return q # 返回环入口 returnNone# 不存在环
""" # Definition for a Node. class Node: def __init__(self, x, next=None, random=None): self.val = int(x) self.next = next self.random = random """ classSolution(object): defcopyRandomList(self, head): """ :type head: Node :rtype: Node """ ifnot head: returnNone # 复制链表节点 cur = head while cur isnotNone: next = cur.next cur.next = Node(cur.val) cur.next.next = next cur = next # 复制random指针 cur = head while cur != None: curNew = cur.next curNew.random = cur.random.nextif cur.random elseNone cur = cur.next.next # 拆分链表 cur = head head_new = head.next curNew = head.next while cur: cur.next = cur.next.next cur = cur.next curNew.next = cur.nextif cur elseNone curNew = curNew.next