diff --git a/find-median-from-data-stream/printjin-gmailcom.py b/find-median-from-data-stream/printjin-gmailcom.py new file mode 100644 index 000000000..2baac7c19 --- /dev/null +++ b/find-median-from-data-stream/printjin-gmailcom.py @@ -0,0 +1,15 @@ +import heapq + +class MedianFinder: + def __init__(self): + self.low = [] + self.high = [] + def addNum(self, num): + heapq.heappush(self.low, -num) + heapq.heappush(self.high, -heapq.heappop(self.low)) + if len(self.high) > len(self.low): + heapq.heappush(self.low, -heapq.heappop(self.high)) + def findMedian(self): + if len(self.low) > len(self.high): + return -self.low[0] + return (-self.low[0] + self.high[0]) / 2 diff --git a/insert-interval/printjin-gmailcom.py b/insert-interval/printjin-gmailcom.py new file mode 100644 index 000000000..288e32063 --- /dev/null +++ b/insert-interval/printjin-gmailcom.py @@ -0,0 +1,17 @@ +class Solution: + def insert(self, intervals, newInterval): + result = [] + i = 0 + n = len(intervals) + while i < n and intervals[i][1] < newInterval[0]: + result.append(intervals[i]) + i += 1 + while i < n and intervals[i][0] <= newInterval[1]: + newInterval[0] = min(newInterval[0], intervals[i][0]) + newInterval[1] = max(newInterval[1], intervals[i][1]) + i += 1 + result.append(newInterval) + while i < n: + result.append(intervals[i]) + i += 1 + return result diff --git a/kth-smallest-element-in-a-bst/printjin-gmailcom.py b/kth-smallest-element-in-a-bst/printjin-gmailcom.py new file mode 100644 index 000000000..46a757f0c --- /dev/null +++ b/kth-smallest-element-in-a-bst/printjin-gmailcom.py @@ -0,0 +1,15 @@ +class Solution: + def kthSmallest(self, root, k): + self.count = 0 + self.result = 0 + def inorder(node): + if not node: + return + inorder(node.left) + self.count += 1 + if self.count == k: + self.result = node.val + return + inorder(node.right) + inorder(root) + return self.result diff --git a/lowest-common-ancestor-of-a-binary-search-tree/printjin-gmailcom.py b/lowest-common-ancestor-of-a-binary-search-tree/printjin-gmailcom.py new file mode 100644 index 000000000..06a0fc5ab --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/printjin-gmailcom.py @@ -0,0 +1,9 @@ +class Solution: + def lowestCommonAncestor(self, root, p, q): + while root: + if p.val < root.val and q.val < root.val: + root = root.left + elif p.val > root.val and q.val > root.val: + root = root.right + else: + return root diff --git a/meeting-rooms/printjin-gmailcom,.py b/meeting-rooms/printjin-gmailcom,.py new file mode 100644 index 000000000..34ef1efdc --- /dev/null +++ b/meeting-rooms/printjin-gmailcom,.py @@ -0,0 +1,9 @@ +from typing import List + +class Solution: + def canAttendMeetings(self, intervals: List[Interval]) -> bool: + intervals.sort(key=lambda x: x.start) + for i in range(1, len(intervals)): + if intervals[i].start < intervals[i - 1].end: + return False + return True