left is left pointer, i is right pointer
外循环为扩张,内循环为收缩。收缩条件为固定字符种数(必须固定或者少于k)或者(以及)固定字符频数。若字符种数不固定,要试1-26种字符,才能单调,详见L395
求最短串
Python代码:
1 2 3 4 5 6 7 8
deftwo_pointers(self, nums): for i inrange(len(nums)): <calculate condition such as char_to_count> while <meets condition>: res = min(res, i - left + 1) <求最短子列> <anti-calculate condition such as char_to_count> left += 1 return <result>
求最长串
Python代码:
1 2 3 4 5 6 7 8
deftwo_pointers(self, nums): for i inrange(len(nums)): <calculate condition such as char_to_count> while <does not meet condition>: <anti-calculate condition such as char_to_count> left += 1 res = max(res, i - left + 1) <求最短子列> return <result>
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray[nums<sub>l</sub>, nums<sub>l+1</sub>, ..., nums<sub>r-1</sub>, nums<sub>r</sub>] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
<pre>Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
</pre>
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example 1:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]
<pre> 0
|
1
/
2 3
</pre>
return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
<pre> 0 1 2
\ | /
3
|
4
|
5
</pre>
return [3, 4]
Note:
(1) According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
(2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
deffindMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: ifnot edges: return [0] # remember graph = collections.defaultdict(list) in_degree = [0] * n for li in edges: graph[li[0]].append(li[1]) graph[li[1]].append(li[0]) in_degree[li[0]] += 1 in_degree[li[1]] += 1 queue = collections.deque([i for i inrange(len(in_degree)) if in_degree[i] == 1]) res = list(queue) # remember while queue: for _ inrange(len(queue)): node = queue.popleft() for neighbor in graph[node]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 1: queue.append(neighbor) if queue: # remember res = list(queue) return res