There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:
There are no self-edges (graph[u] does not contain u).
There are no parallel edges (graph[u] does not contain duplicate values). If v is in graph[u], then u is in graph[v] (the graph is undirected).
The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
Return trueif and only if it is bipartite.
Example 1:
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]] Output: false Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
Example 2:
Input: graph = [[1,3],[0,2],[1,3],[0,2]] Output: true Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
Constraints:
graph.length == n1 <= n <= 100 0 <= graph[u].length < n0 <= graph[u][i] <= n - 1 graph[u] does not contain u.
All the values of graph[u] are unique. * If graph[u] contains v, then graph[v] contains u.
defisBipartite(self, graph: List[List[int]]) -> bool: node_to_color = collections.defaultdict(int) for i in range(len(graph)): if i in node_to_color: # disconnected nodes continue node_to_color[i] = 0 ifnot self.bfs(graph, i, node_to_color): returnFalse returnTrue
defbfs(self, graph, n, node_to_color): queue = collections.deque([n]) while queue: node = queue.popleft() for neighbor in graph[node]: if neighbor in node_to_color and node_to_color[neighbor] != 1 - node_to_color[node]: returnFalse if neighbor in node_to_color: continue queue.append(neighbor) node_to_color[neighbor] = 1 - node_to_color[node] returnTrue
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]
An expression alternates chunks and symbols, with a space separating each chunk and symbol.
A chunk is either an expression in parentheses, a variable, or a non-negative integer. A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".
Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.
For example, expression = "1 + 2 * 3" has an answer of ["7"].
The format of the output is as follows:
For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
For example, we would never write a term like "b*a*c", only "a*b*c". Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
For example, "a*a*b*c" has degree 4. The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
An example of a well-formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]. Terms (including constant terms) with coefficient 0 are not included.
For example, an expression of "0" has an output of [].
Constraints:1 <= expression.length <= 250 expression consists of lowercase English letters, digits, '+', '-', `’‘,‘(‘,‘)’,‘ ‘.
*expressiondoes not contain any leading or trailing spaces.
* All the tokens inexpressionare separated by a single space.
*0 <= evalvars.length <= 100*1 <= evalvars[i].length <= 20*evalvars[i]consists of lowercase English letters.
*evalints.length == evalvars.length*-100 <= evalints[i] <= 100`
def__mul__(self, other): product = MyCounter() for x in self: for y in other: xy = tuple(sorted(x + y)) product[xy] += self[x] * other[y] return product
var_to_val = dict(zip(evalvars, evalints))
deff(s): token = s s = str(var_to_val[token] if token in var_to_val else token) return MyCounter({(s, ): 1}) if s.isalpha() else MyCounter({(): int(s)})
converted_expr = re.sub(r'(\w+)', r'f("\1")', expression) # (f("x") + f("8")) * (f("x") - f("8")) res = eval(converted_expr) # # C({('x', 'x'): 1, ('x',): 0, (): -64}) return ['*'.join((str(res[x]), ) + x) for x in sorted(res, key=lambda x: (-len(x), x)) if res[x]]
# dp[i][j] = dp[i - 1][j - 1] + 1 if text1[i - 1] == text2[j - 1] # = 0 deflongestCommonContinuous(self, text1: str, text2: str) -> int: dp = [[0for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)] res = 0 for i in range(1, len(dp)): for j in range(1, len(dp[0])): if text1[i - 1] == text2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 res = max(res, dp[i][j]) return res
优化空间:
1 2 3 4 5 6 7 8 9
deflongestCommonContinuous(self, text1: str, text2: str) -> int: dp = [[0for _ in range(len(text2) + 1)] for _ in range(2)] res = 0 for i in range(1, len(text1) + 1): for j in range(1, len(dp[0])): if text1[i - 1] == text2[j - 1]: dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1 res = max(res, dp[i % 2][j]) return res
回到原题,输入是列表而不是字符串,但原理一样。还有需要输出公共结果,而不是数字
Python代码:
1 2 3 4 5 6 7 8 9 10 11
deflongestCommonContinuousSubarray(self, history1, history2): dp = [[0for _ in range(len(history2) + 1)] for _ in range(len(history1) + 1)] max_len, res = 0, [] for i in range(1, len(dp)): for j in range(1, len(dp[0])): if history1[i - 1] == history2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 if dp[i][j] > max_len: max_len = dp[i][j] res = history1[i - dp[i][j]:i] return res
Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
Example 1:
Input: nums = [-2,0,1,3], target = 2 Output: 2 Explanation: Because there are two triplets which sums are less than 2: [-2,0,1] [-2,0,3]
Example 2:
Input: nums = [], target = 0 Output: 0
Example 3:
Input: nums = [0], target = 0 Output: 0
Constraints:
n == nums.length0 <= n <= 3500 -100 <= nums[i] <= 100-100 <= target <= 100
题目大意:
找三数和小于target的组合个数
解题思路:
类似于三数和等于target,但当小于target时,直接求个数,类似于LeetCode 315 Count of Smaller Numbers After Self。
解题步骤:
N/A
注意事项:
res不是+1而是right - left
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
defthreeSumSmaller(self, nums: List[int], target: int) -> int: if len(nums) < 3: return0 nums.sort() res = 0 for i in range(len(nums) - 2): left, right = i + 1, len(nums) - 1 while left < right: if nums[i] + nums[left] + nums[right] < target: res += right - left # remember left += 1 else: right -= 1 return res