Skip to content

Commit efdd131

Browse files
committed
Solution of zigzag iterator, segment tree, running average, BT longest consecutive chain, senetence fitting
1 parent 9a2d5db commit efdd131

File tree

6 files changed

+287
-0
lines changed

6 files changed

+287
-0
lines changed

200-300q/281.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Given two 1d vectors, implement an iterator to return their elements alternately.
3+
4+
For example, given two 1d vectors:
5+
6+
v1 = [1, 2]
7+
v2 = [3, 4, 5, 6]
8+
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].
9+
'''
10+
11+
class Solution(object):
12+
def __init__(self, v1, v2):
13+
self.v1 = v1
14+
self.v2 = v2
15+
self.index_v1 = 0
16+
self.index_v2 = 0
17+
18+
def next(self):
19+
result = -1
20+
if self.index_v1 != len(self.v1) and self.index_v1 <= self.index_v2:
21+
result = self.v1[self.index_v1]
22+
self.index_v1 += 1
23+
else:
24+
result = self.v2[self.index_v2]
25+
self.index_v2 += 1
26+
27+
return result
28+
29+
def hasNext(self):
30+
return self.index_v1 < len(self.v1) or self.index_v2 < len(self.v2)
31+
32+
33+
solution = Solution([1, 2], [3, 4, 5, 6])
34+
while solution.hasNext():
35+
print solution.next()

200-300q/298.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Given a binary tree, find the length of the longest consecutive sequence path.
3+
4+
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).
5+
6+
For example,
7+
1
8+
\
9+
3
10+
/ \
11+
2 4
12+
\
13+
5
14+
Longest consecutive sequence path is 3-4-5, so return 3.
15+
2
16+
\
17+
3
18+
/
19+
2
20+
/
21+
1
22+
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
23+
'''
24+
25+
26+
class Solution(object):
27+
def dfs(curr, parent, length):
28+
if not curr:
29+
return length
30+
if parent:
31+
length = length + 1 if curr.val == parent.val + 1
32+
else:
33+
length = 1
34+
35+
return max(length, max(dfs(curr.left, curr, length), dfs(curr.right, curr, length)))
36+
37+
def longestConsecutive(TreeNode root):
38+
if not root:
39+
return 0
40+
41+
return dfs(root, null, 0)

300-400q/307.py

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
'''
2+
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
3+
4+
The update(i, val) function modifies nums by updating the element at index i to val.
5+
6+
Example:
7+
8+
Given nums = [1, 3, 5]
9+
10+
sumRange(0, 2) -> 9
11+
update(1, 2)
12+
sumRange(0, 2) -> 8
13+
Note:
14+
15+
The array is only modifiable by the update function.
16+
You may assume the number of calls to update and sumRange function is distributed evenly.
17+
'''
18+
19+
class Node(object):
20+
def __init__(self, val ,start, end):
21+
self.sum = val
22+
self.right, self.left = None, None
23+
self.range= [start, end]
24+
25+
class SegementTree(object):
26+
def __init__(self, size):
27+
self.root = self._build_segment_tree(0, size-1)
28+
29+
def _build_segment_tree(self, start, end):
30+
if start > end:
31+
return None
32+
node = Node(0, start, end)
33+
if start == end:
34+
return node
35+
mid = (start+end)/2
36+
node.left, node.right = self._build_segment_tree(start, mid), self._build_segment_tree(mid+1, end)
37+
return node
38+
39+
def update(self, index, val, root=None):
40+
root = root or self.root
41+
if index < root.range[0] or index > root.range[1]:
42+
return
43+
root.sum += val
44+
if index == root.range[0] == root.range[1]:
45+
return
46+
self.update(index, val, root.left)
47+
self.update(index, val, root.right)
48+
49+
def range_sum(self, start, end, root=None):
50+
root = root or self.root
51+
if end < root.range[0] or start > root.range[1]:
52+
return 0
53+
if start <= root.range[0] and end >= root.range[1]:
54+
return root.sum
55+
return self.range_sum(start, end, root.left) + self.range_sum(start, end, root.right)
56+
57+
58+
class NumArray(object):
59+
60+
def __init__(self, nums):
61+
"""
62+
:type nums: List[int]
63+
"""
64+
self.nums = nums
65+
self.segment_tree = SegementTree(len(nums))
66+
for index, num in enumerate(nums):
67+
self.segment_tree.update(index, num)
68+
69+
70+
def update(self, i, val):
71+
"""
72+
:type i: int
73+
:type val: int
74+
:rtype: None
75+
"""
76+
diff = val-self.nums[i]
77+
self.segment_tree.update(i, diff)
78+
self.nums[i] = val
79+
80+
81+
def sumRange(self, i, j):
82+
"""
83+
:type i: int
84+
:type j: int
85+
:rtype: int
86+
"""
87+
return self.segment_tree.range_sum(i, j)
88+
89+
90+
# Your NumArray object will be instantiated and called as such:
91+
# obj = NumArray(nums)
92+
# obj.update(i,val)
93+
# param_2 = obj.sumRange(i,j)

300-400q/346.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
3+
4+
For example,
5+
MovingAverage m = new MovingAverage(3);
6+
m.next(1) = 1
7+
m.next(10) = (1 + 10) / 2
8+
m.next(3) = (1 + 10 + 3) / 3
9+
m.next(5) = (10 + 3 + 5) / 3
10+
'''
11+
12+
class Solution(object):
13+
def __init__(self):
14+
self.queue = []
15+
self.curr_sum = 0
16+
17+
def movingAverage(self, num, size):
18+
if len(self.queue) >= size:
19+
val = self.queue.pop(0)
20+
self.curr_sum -= val
21+
22+
self.curr_sum += num
23+
self.queue.append(num)
24+
return float(self.curr_sum)/len(self.queue)
25+
26+
27+
28+
solution = Solution()
29+
window_size = int(input())
30+
num = int(input())
31+
while num != -1:
32+
print solution.movingAverage(num, window_size)
33+
num = int(input())

400-500Q/418.py

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
'''
2+
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.
3+
4+
Note:
5+
6+
A word cannot be split into two lines.
7+
The order of words in the sentence must remain unchanged.
8+
Two consecutive words in a line must be separated by a single space.
9+
Total words in the sentence won't exceed 100.
10+
Length of each word is greater than 0 and won't exceed 10.
11+
1 ≤ rows, cols ≤ 20,000.
12+
Example 1:
13+
14+
Input:
15+
rows = 2, cols = 8, sentence = ["hello", "world"]
16+
17+
Output:
18+
1
19+
20+
Explanation:
21+
hello---
22+
world---
23+
24+
The character '-' signifies an empty space on the screen.
25+
Example 2:
26+
27+
Input:
28+
rows = 3, cols = 6, sentence = ["a", "bcd", "e"]
29+
30+
Output:
31+
2
32+
33+
Explanation:
34+
a-bcd-
35+
e-a---
36+
bcd-e-
37+
38+
The character '-' signifies an empty space on the screen.
39+
Example 3:
40+
41+
Input:
42+
rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]
43+
44+
Output:
45+
1
46+
47+
Explanation:
48+
I-had
49+
apple
50+
pie-I
51+
had--
52+
53+
The character '-' signifies an empty space on the screen.
54+
'''
55+
56+
class Solution(object):
57+
def wordsTyping(self, sentences, rows, cols):
58+
""""
59+
:sentences List<String>
60+
:rows int
61+
:cols int
62+
"""
63+
sentence = '-'.join(sentences)
64+
sentence += '-'
65+
66+
index_in_sentence = 0
67+
for row in range(rows):
68+
index_in_sentence += cols
69+
if sentence[(index_in_sentence%len(sentence))] == '-':
70+
index_in_sentence += 1
71+
else:
72+
while index_in_sentence > 0 and sentence[((index_in_sentence - 1)%len(sentence))] != '-':
73+
index_in_sentence -= 1
74+
75+
return index_in_sentence/len(sentence)
76+
77+
solution = Solution()
78+
row, col = 3, 6
79+
sentences = ["a", "bcd", "e"]
80+
print solution.wordsTyping(sentences=sentences, rows=row, cols=col)

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
9797
|454|[4Sum II](https://leetcode.com/problems/4sum-ii/)|[Python](./400-500Q/454.py)|Medium|
9898
|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|
9999
|442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array)|[Python](./400-500q/442.py)|Easy|
100+
|418|[Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting)|[Python](./400-500q/418.py)|Medium|
100101
|410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [Python](./400-500Q/410.py)|Hard|
101102

102103

@@ -109,6 +110,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
109110
|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|
110111
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Python](./300-400q/350.py)|Easy|
111112
|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](./300-400q/347.py)|Medium|
113+
|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream)|[Python](./300-400q/346.py)|Easy|
112114
|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|
113115
|334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [Python](./300-400q/334.py)|Medium|
114116
|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/).
117119
|326|[Power of Three](https://leetcode.com/problems/power-of-three/) | [Python](./300-400q/326.py)|Easy|
118120
|322|[Coin Change](https://leetcode.com/problems/coin-change/) | [Python](./300-400q/322.py)|Medium|
119121
|315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | [Python](./300-400q/315.py)|Hard|
122+
|307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable)|[Python](./300-400q/307.py)|Medium|
120123
|301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses)|[Python](./300-400q/301.py)|Hard|
121124

122125
##### [Problems 200-300q](./200-300q/)
123126
| # | Title | Solution | Difficulty |
124127
|---| ----- | -------- | ---------- |
125128
|300|[Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | [Python](./200-300q/300.py)|Medium|
129+
|298|[Binary Tree Longest Consecutive Sequence ](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence)|[Python](./200-300q/298.py)|Medium|
126130
|297|[Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree) | [Python](./200-300q/297.py)|Hard|
127131
|295|[Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [Python](./200-300q/295.py)|Hard|
128132
|289|[Game of Life](https://leetcode.com/problems/game-of-life) | [Python](/200-300q/289.py)|Medium|
129133
|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | [Python](./200-300q/287.py)|Hard|
130134
|285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst) | [Python](./200-300q/285.py)|Medium|
131135
|283|[Move Zeros](https://leetcode.com/problems/move-zeroes)|[Python](./200-300q/283.py)|Easy|
136+
|281|[Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator)|[Python](./200-300q/281.py)|Medium|
132137
|279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/) | [Python](./200-300q/279.py)|Medium|
133138
|268|[Missing Number](https://leetcode.com/problems/missing-number)|[Python](./200-300q/268.py)|Easy|
134139
|257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths)|[Python](./200-300q/257.py)|Easy|

0 commit comments

Comments
 (0)