Special binary strings are binary strings with the following two properties:
The number of 0‘s is equal to the number of 1‘s.
Every prefix of the binary string has at least as many 1‘s as 0‘s.
You are given a special binary string s.
A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.
Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.
Example 1:
Input: s = “11011000” Output: “11100100” Explanation: The strings “10” [occuring at s[1]] and “1100” [at s[3]] are swapped. This is the lexicographically largest string possible after some number of swaps.
Example 2:
Input: s = “10” Output: “10”
Constraints:
1 <= s.length <= 50s[i] is either '0' or '1'. * s is a special binary string.
题目大意:
Special string由0和1组成,数目一样且每个前缀1的数目大于等于0的数目。可以交换其内部的子特别字符串,让其数值最大
defnumSubarraysWithSum(self, nums: List[int], goal: int) -> int: presum = [0] for i inrange(len(nums)): presum.append(presum[-1] + nums[i]) val_to_freq, res = collections.defaultdict(int), 0 for i inrange(len(presum)): if presum[i] - goal in val_to_freq: res += val_to_freq[presum[i] - goal] val_to_freq[presum[i]] += 1#attn return res
算法分析:
时间复杂度为O(n),空间复杂度O(n)
算法II解题思路Sliding Window:
此法虽然空间复杂度较优,但较难想。求字串的和可以考虑用Two pointers两边夹。这里求所有可能性,比如0011100, goal=3, 必须包括前缀0和后缀0,所以用Two pointers最长串的模板 类似于LeetCode 340 Longest Substring with At Most K Distinct Characters,不满足条件为窗口和大于goal,所以满足条件为小于等于goal(类似于at most k)。 所以要用at_most(goal) - at_most(goal - 1)才能得到最后结果。 计算的时候,是i-left+1代表窗口和<=subgoal的以nums[i]为结尾的子数组个数,比如10101, i指向最后一个1, left指向第一个0, res是4个,对应1, 01, 101, 0101
注意事项:
模板满足条件在内循环外,所以计算结果在内循环结束后。
subgoal如果小于0,返回0。比如goal为0,nums=[0,0]
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defnumSubarraysWithSum(self, nums: List[int], goal: int) -> int: defat_most(subgoal): if subgoal < 0: #attn return0 window_sum, left, res = 0, 0, 0 i = 0 for i inrange(len(nums)): window_sum += nums[i] while window_sum > subgoal: window_sum -= nums[left] left += 1 res += i - left + 1# ending with nums[i] return res
Koko loves to eat bananas. There are n piles of bananas, the i<sup>th</sup> pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integerksuch that she can eat all the bananas withinhhours.
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>), where u<sub>i</sub> is the source node, v<sub>i</sub> is the target node, and w<sub>i</sub> is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all thennodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 Output: 2
Example 2:
Input: times = [[1,2,1]], n = 2, k = 1 Output: 1
Example 3:
Input: times = [[1,2,1]], n = 2, k = 2 Output: -1
Constraints:
1 <= k <= n <= 1001 <= times.length <= 6000 times[i].length == 31 <= u<sub>i</sub>, v<sub>i</sub> <= n u<sub>i</sub> != v<sub>i</sub>0 <= w<sub>i</sub> <= 100 All the pairs (u<sub>i</sub>, v<sub>i</sub>) are *unique. (i.e., no multiple edges.)
题目大意:
求从某一个点出发的所有能到达的点中的最短时间。若不能都到达返回-1
解题思路:
单源最短路径的最大值,如果有点不能到达返回-1.用BFS+Heap的模板
解题步骤:
N/A
注意事项:
用queue
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defnetworkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: # build graph graph = collections.defaultdict(list) for e in times: graph[e[0]].append((e[1], e[2])) heap = [(0, k)] # weight, node visited = {k: 0} while heap: weight, node = heapq.heappop(heap) for neighbor, _weight in graph[node]: if neighbor in visited and visited[neighbor] <= weight + _weight: continue heapq.heappush(heap, (weight + _weight, neighbor)) visited[neighbor] = weight + _weight returnmax(visited.values()) iflen(visited) == n else -1
defbfs(self, graph, start) -> List[int]: queue, res = deque([start]), [] visited = {start} while queue: node = queue.popleft() res.append(node) for neighbor in graph[node]: if neighbor in visited: continue queue.append(neighbor) visited.add(neighbor) return res
树模板只要把visited去掉,neighbor改成left和right
注意事项:
visited = {start}不写set([start])
if neighbor in visited在循环里,不是if node in visited
在bfs_layer2,res.append(level)
计算最短距离的图遍历(最常考的模板)
只要加line 4和14
visited在函数内定义
遇到target就返回最短距离,若离开循环返回-1,问清楚是否存在路径不存在的情况
求距离公式不需要用min,因为这个遍历保证了最短距离了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defbfs_layer(self, graph, start, target) -> int: queue = deque([start]) visited = {start} distance = {start: 1} while queue: node = queue.popleft() if node == target: return distance[node] for neighbor in graph[node]: if neighbor in visited: continue queue.append(neighbor) visited.add(neighbor) distance[neighbor] = distance[node] + 1 return -1
写法2
1 2 3 4 5 6 7 8 9 10 11 12 13
defbfs_layer_v2(self, graph, start, target) -> int: queue = deque([(start, 1)]) visited = {start} while queue: node, distance = queue.popleft() if node == target: return distance for neighbor in graph[node]: if neighbor in visited: continue queue.append((neighbor, distance + 1)) visited.add(neighbor) return -1
按层遍历
核心是加这一行for _ in range(len(queue)) 具体还要加line 5, 6和14, 15. 二叉树不需要visited。能用distance dict就尽量不用此法,因为多了一个循环。
注意事项:
关键行: 多这一行for循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defbfs_layer2(self, graph, start) -> List[List[int]]: queue, res = deque([start]), [] visited = {start} while queue: level = [] for _ inrange(len(queue)): node = queue.popleft() level.append(node) for neighbor in graph[node]: if neighbor in visited: continue queue.append(neighbor) visited.add(neighbor) res.append(level) return res