Implement a key-value store that can serialize multiple string key-value pairs into a single string and deserialize it back. Both keys and values can contain any characters including delimiters, newlines, and special characters.
if nums[end] == target: return end elif nums[start] == target: return start else: return -1
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
deflast_position(self, nums: List[int], target: int) -> int: ifnot nums: return -1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if target < nums[mid]: end = mid elif target > nums[mid]: start = mid else: # Depends on the target on the right side or left side. For fist pos, use end = mid start = mid
if nums[end] == target: return end elif nums[start] == target: return start else: return -1
defiterative_inorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append(it) it = it.left while stack: node = stack.pop() res.append(node.val) if node.right: n = node.right while n: stack.append(n) n = n.left return res
defiterative_preorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append(it) res.append(it.val) it = it.left while stack: node = stack.pop() if node.right: n = node.right while n: stack.append(n) res.append(n.val) n = n.left return res
defiterative_postorder(self, root: TreeNode) -> List[int]: ifnot root: return [] res, stack = [], [] it = root while it: stack.append((it, 0)) # count for it in the stack top it = it.left while stack: pair = stack.pop() node = pair[0] occurrence = pair[1] + 1 if occurrence == 2: res.append(node.val) continue# don't iterate on right node again else: stack.append((node, occurrence)) if node.right: n = node.right while n: stack.append((n, 0)) n = n.left return res