diff --git a/200-300q/281.py b/200-300q/281.py new file mode 100644 index 0000000..0dab44a --- /dev/null +++ b/200-300q/281.py @@ -0,0 +1,35 @@ +''' +Given two 1d vectors, implement an iterator to return their elements alternately. + +For example, given two 1d vectors: + +v1 = [1, 2] +v2 = [3, 4, 5, 6] +By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. +''' + +class Solution(object): + def __init__(self, v1, v2): + self.v1 = v1 + self.v2 = v2 + self.index_v1 = 0 + self.index_v2 = 0 + + def next(self): + result = -1 + if self.index_v1 != len(self.v1) and self.index_v1 <= self.index_v2: + result = self.v1[self.index_v1] + self.index_v1 += 1 + else: + result = self.v2[self.index_v2] + self.index_v2 += 1 + + return result + + def hasNext(self): + return self.index_v1 < len(self.v1) or self.index_v2 < len(self.v2) + + +solution = Solution([1, 2], [3, 4, 5, 6]) +while solution.hasNext(): + print solution.next() \ No newline at end of file diff --git a/200-300q/298.py b/200-300q/298.py new file mode 100644 index 0000000..64fef9f --- /dev/null +++ b/200-300q/298.py @@ -0,0 +1,41 @@ +''' +Given a binary tree, find the length of the longest consecutive sequence path. + +The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse). + +For example, + 1 + \ + 3 + / \ + 2 4 + \ + 5 +Longest consecutive sequence path is 3-4-5, so return 3. + 2 + \ + 3 + / + 2 + / + 1 +Longest consecutive sequence path is 2-3,not3-2-1, so return 2. +''' + + +class Solution(object): + def dfs(curr, parent, length): + if not curr: + return length + if parent: + length = length + 1 if curr.val == parent.val + 1 + else: + length = 1 + + return max(length, max(dfs(curr.left, curr, length), dfs(curr.right, curr, length))) + + def longestConsecutive(TreeNode root): + if not root: + return 0 + + return dfs(root, null, 0) diff --git a/300-400q/307.py b/300-400q/307.py new file mode 100644 index 0000000..9a94600 --- /dev/null +++ b/300-400q/307.py @@ -0,0 +1,93 @@ +''' +Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. + +The update(i, val) function modifies nums by updating the element at index i to val. + +Example: + +Given nums = [1, 3, 5] + +sumRange(0, 2) -> 9 +update(1, 2) +sumRange(0, 2) -> 8 +Note: + +The array is only modifiable by the update function. +You may assume the number of calls to update and sumRange function is distributed evenly. +''' + +class Node(object): + def __init__(self, val ,start, end): + self.sum = val + self.right, self.left = None, None + self.range= [start, end] + +class SegementTree(object): + def __init__(self, size): + self.root = self._build_segment_tree(0, size-1) + + def _build_segment_tree(self, start, end): + if start > end: + return None + node = Node(0, start, end) + if start == end: + return node + mid = (start+end)/2 + node.left, node.right = self._build_segment_tree(start, mid), self._build_segment_tree(mid+1, end) + return node + + def update(self, index, val, root=None): + root = root or self.root + if index < root.range[0] or index > root.range[1]: + return + root.sum += val + if index == root.range[0] == root.range[1]: + return + self.update(index, val, root.left) + self.update(index, val, root.right) + + def range_sum(self, start, end, root=None): + root = root or self.root + if end < root.range[0] or start > root.range[1]: + return 0 + if start <= root.range[0] and end >= root.range[1]: + return root.sum + return self.range_sum(start, end, root.left) + self.range_sum(start, end, root.right) + + +class NumArray(object): + + def __init__(self, nums): + """ + :type nums: List[int] + """ + self.nums = nums + self.segment_tree = SegementTree(len(nums)) + for index, num in enumerate(nums): + self.segment_tree.update(index, num) + + + def update(self, i, val): + """ + :type i: int + :type val: int + :rtype: None + """ + diff = val-self.nums[i] + self.segment_tree.update(i, diff) + self.nums[i] = val + + + def sumRange(self, i, j): + """ + :type i: int + :type j: int + :rtype: int + """ + return self.segment_tree.range_sum(i, j) + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# obj.update(i,val) +# param_2 = obj.sumRange(i,j) \ No newline at end of file diff --git a/300-400q/346.py b/300-400q/346.py new file mode 100644 index 0000000..4a6b082 --- /dev/null +++ b/300-400q/346.py @@ -0,0 +1,33 @@ +''' +Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. + +For example, +MovingAverage m = new MovingAverage(3); +m.next(1) = 1 +m.next(10) = (1 + 10) / 2 +m.next(3) = (1 + 10 + 3) / 3 +m.next(5) = (10 + 3 + 5) / 3 +''' + +class Solution(object): + def __init__(self): + self.queue = [] + self.curr_sum = 0 + + def movingAverage(self, num, size): + if len(self.queue) >= size: + val = self.queue.pop(0) + self.curr_sum -= val + + self.curr_sum += num + self.queue.append(num) + return float(self.curr_sum)/len(self.queue) + + + +solution = Solution() +window_size = int(input()) +num = int(input()) +while num != -1: + print solution.movingAverage(num, window_size) + num = int(input()) \ No newline at end of file diff --git a/400-500Q/418.py b/400-500Q/418.py new file mode 100644 index 0000000..136f4fc --- /dev/null +++ b/400-500Q/418.py @@ -0,0 +1,80 @@ +''' +Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. + +Note: + +A word cannot be split into two lines. +The order of words in the sentence must remain unchanged. +Two consecutive words in a line must be separated by a single space. +Total words in the sentence won't exceed 100. +Length of each word is greater than 0 and won't exceed 10. +1 ≤ rows, cols ≤ 20,000. +Example 1: + +Input: +rows = 2, cols = 8, sentence = ["hello", "world"] + +Output: +1 + +Explanation: +hello--- +world--- + +The character '-' signifies an empty space on the screen. +Example 2: + +Input: +rows = 3, cols = 6, sentence = ["a", "bcd", "e"] + +Output: +2 + +Explanation: +a-bcd- +e-a--- +bcd-e- + +The character '-' signifies an empty space on the screen. +Example 3: + +Input: +rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] + +Output: +1 + +Explanation: +I-had +apple +pie-I +had-- + +The character '-' signifies an empty space on the screen. +''' + +class Solution(object): + def wordsTyping(self, sentences, rows, cols): + """" + :sentences List + :rows int + :cols int + """ + sentence = '-'.join(sentences) + sentence += '-' + + index_in_sentence = 0 + for row in range(rows): + index_in_sentence += cols + if sentence[(index_in_sentence%len(sentence))] == '-': + index_in_sentence += 1 + else: + while index_in_sentence > 0 and sentence[((index_in_sentence - 1)%len(sentence))] != '-': + index_in_sentence -= 1 + + return index_in_sentence/len(sentence) + +solution = Solution() +row, col = 3, 6 +sentences = ["a", "bcd", "e"] +print solution.wordsTyping(sentences=sentences, rows=row, cols=col) diff --git a/README.md b/README.md index 8e5a009..61f79ae 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/). |454|[4Sum II](https://leetcode.com/problems/4sum-ii/)|[Python](./400-500Q/454.py)|Medium| |448|[Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array)|[Python](./400-500q/448.py)|Easy| |442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array)|[Python](./400-500q/442.py)|Easy| +|418|[Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting)|[Python](./400-500q/418.py)|Medium| |410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [Python](./400-500Q/410.py)|Hard| @@ -109,6 +110,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/). |378|[Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix) | [Python](./300-400q/378.py)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Python](./300-400q/350.py)|Easy| |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](./300-400q/347.py)|Medium| +|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream)|[Python](./300-400q/346.py)|Easy| |340|[Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters)|[Python](./300-400q/340.py)|Hard| |334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [Python](./300-400q/334.py)|Medium| |332|[Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/)|[Python](./300-400q/332.py)|Medium| @@ -117,18 +119,21 @@ Python solution of problems from [LeetCode](https://leetcode.com/). |326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [Python](./300-400q/326.py)|Easy| |322|[Coin Change](https://leetcode.com/problems/coin-change/) | [Python](./300-400q/322.py)|Medium| |315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [Python](./300-400q/315.py)|Hard| +|307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable)|[Python](./300-400q/307.py)|Medium| |301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses)|[Python](./300-400q/301.py)|Hard| ##### [Problems 200-300q](./200-300q/) | # | Title | Solution | Difficulty | |---| ----- | -------- | ---------- | |300|[Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | [Python](./200-300q/300.py)|Medium| +|298|[Binary Tree Longest Consecutive Sequence ](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence)|[Python](./200-300q/298.py)|Medium| |297|[Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree) | [Python](./200-300q/297.py)|Hard| |295|[Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [Python](./200-300q/295.py)|Hard| |289|[Game of Life](https://leetcode.com/problems/game-of-life) | [Python](/200-300q/289.py)|Medium| |287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | [Python](./200-300q/287.py)|Hard| |285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst) | [Python](./200-300q/285.py)|Medium| |283|[Move Zeros](https://leetcode.com/problems/move-zeroes)|[Python](./200-300q/283.py)|Easy| +|281|[Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator)|[Python](./200-300q/281.py)|Medium| |279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/) | [Python](./200-300q/279.py)|Medium| |268|[Missing Number](https://leetcode.com/problems/missing-number)|[Python](./200-300q/268.py)|Easy| |257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths)|[Python](./200-300q/257.py)|Easy|