Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [1,2], p = 1, q = 2 Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 10<sup>5</sup>].
-10<sup>9</sup> <= Node.val <= 10<sup>9</sup> All Node.val are unique.
p != q * p and q will exist in the tree.
deflowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': ifnot root: returnNone if root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root return left if left else right
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.
Example:
**Input: low = "50", high = "100"
**Output:** 3
Explanation: 69, 88, and 96 are three strobogrammatic numbers.
Note: Because the range might be a large number, the lowand high numbers are represented as string.
defstrobogrammaticInRange(self, low: str, high: str) -> int: stro_dict = {'0': '0', '1': '1', '8': '8', '6': '9', '9': '6'} res = 0 res += self.dfs('', low, high, stro_dict) res += self.dfs('0', low, high, stro_dict) res += self.dfs('1', low, high, stro_dict) res += self.dfs('8', low, high, stro_dict) return res
defdfs(self, s, low, high, stro_dict): iflen(s) > len(high) or (len(s) == len(high) and s > high): return0 res = 0 iflen(s) > len(low) or (len(s) == len(low) and s >= low): res = 1 iflen(s) > 1and s[0] == '0': # i.e. 08 res = 0 for key, val in stro_dict.items(): res += self.dfs(key + s + val, low, high, stro_dict) return res
Given an n x nmatrix where each of the rows and columns is sorted in ascending order, return thek<sup>th</sup>smallest element in the matrix.
Note that it is the k<sup>th</sup> smallest element in the sorted order, not the k<sup>th</sup>distinct element.
You must find a solution with complexity better than O(n<sup>2</sup>).
Example 1:
**Input:** matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are [1,5,9,10,11,12,13,**13**,15], and the 8th smallest number is 13
Example 2:
**Input:** matrix = [[-5]], k = 1
**Output:** -5
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 300
-10<sup>9</sup> <= matrix[i][j] <= 10<sup>9</sup>
All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
1 <= k <= n<sup>2</sup>
Follow up: Could you solve the problem in O(n) time complexity?
题目大意:
按行按列有序矩阵中,找第k小的数。
Heap解题思路(推荐):
见Heap知识点。 分别将(value, i, j)放入heap中,取出堆顶元素后,去(i, j)相邻右和下节点放入堆中。这个方法容易实现,所以推荐。
LeetCode 074 Search a 2D Matrix 每一行有序,下一行的首元素大于上一行的尾元素 + 找target LeetCode 240 Search a 2D Matrix II 按行按列有序 + 找target LeetCode 378 Kth Smallest Element in a Sorted Matrix 按行按列有序 + 找第k大 矩阵结构方面,第一道每一行都是独立,所以可以独立地按行按列做二分法 后两道,矩阵二维连续,所以解法都是类BFS,从某个点开始,然后比较它相邻的两个点。出发点不同,第二道在近似矩阵中点(右上角或左下角),第三道在左上角出发。
注意事项:
将(value, i, j)放入heap中
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defkthSmallest4(self, matrix: List[List[int]], k: int) -> int: OFFSETS = [(0, 1), (1, 0)] heap = [(matrix[0][0], 0, 0)] visited = set([(0, 0)]) while heap: node = heapq.heappop(heap) k -= 1 if k == 0: return node[0] for _dx, _dy in OFFSETS: x, y = node[1] + _dx, node[2] + _dy if x < 0or x >= len(matrix) or y < 0or y >= len(matrix[0]) or (x, y) in visited: continue heapq.heappush(heap, (matrix[x][y], x, y)) visited.add((x, y)) return -1
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return trueif there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 10<sup>4</sup>].
-10<sup>5</sup> <= Node.val <= 10<sup>5</sup> pos is -1 or a valid index in the linked-list.
*Follow up: Can you solve it using O(1) (i.e. constant) memory?
题目大意:
求LL是否存在循环
解题思路:
快慢指针。若存在循环就一定会相遇,这是显然的。
解题步骤:
N/A
注意事项:
不涉及删除,所以不需要哟用到fake_node,但循环中先走再判断。
Python代码:
1 2 3 4 5 6 7
defhasCycle(self, head: ListNode) -> bool: fast, slow= head, head while fast and fast.next: fast, slow = fast.next.next, slow.next if fast == slow: # meets again returnTrue returnFalse