Skip to content

Commit 2fac908

Browse files
committed
add more algorithms
1 parent 24db4c4 commit 2fac908

File tree

7 files changed

+127
-28
lines changed

7 files changed

+127
-28
lines changed

array/merge_intervals.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Given a collection of intervals, merge all overlapping intervals.
3+
4+
For example,
5+
Given [1,3],[2,6],[8,10],[15,18],
6+
return [1,6],[8,10],[15,18].
7+
"""
8+
9+
# Definition for an interval.
10+
class Interval(object):
11+
def __init__(self, s=0, e=0):
12+
self.start = s
13+
self.end = e
14+
15+
def merge(intervals):
16+
"""
17+
:type intervals: List[Interval]
18+
:rtype: List[Interval]
19+
"""
20+
out = []
21+
for i in sorted(intervals, key=lambda i: i.start):
22+
if out and i.start <= out[-1].end:
23+
out[-1].end = max(out[-1].end, i.end)
24+
else:
25+
out += i,
26+
return out
27+
28+
def print_intervals(intervals):
29+
res = []
30+
for i in intervals:
31+
res.append('['+str(i.start)+','+str(i.end)+']')
32+
print("".join(res))
33+
34+
if __name__ == "__main__":
35+
given = [[1,3],[2,6],[8,10],[15,18]]
36+
intervals = []
37+
for l, r in given:
38+
intervals.append(Interval(l,r))
39+
print_intervals(intervals)
40+
print_intervals(merge(intervals))
File renamed without changes.

divide-and-conquer/expression_add_operators.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,15 @@ def add_operator(num, target):
2323
return res
2424

2525
def helper(res, path, num, target, pos, prev, multed):
26-
print(res, path, num, target, pos, prev, multed)
2726
if pos == len(num):
2827
if (target == prev):
2928
res.append(path)
3029
return
3130
for i in range(pos, len(num)):
32-
if i != pos and num[pos] == '0': break
31+
if i != pos and num[pos] == '0': # all digits have to be used
32+
break
3333
cur = int(num[pos:i+1])
34-
print(cur)
35-
if (pos == 0):
34+
if pos == 0:
3635
helper(res, path + str(cur), num, target, i+1, cur, cur)
3736
else:
3837
helper(res, path + "+" + str(cur), num, target, i+1, prev + cur, cur)
@@ -44,4 +43,11 @@ def helper(res, path, num, target, pos, prev, multed):
4443
s = "123"
4544
target = 6
4645
print(add_operator(s, target))
46+
# "232", 8 -> ["2*3+2", "2+3*2"]
47+
s = "232"
48+
target = 8
49+
print(add_operator(s, target))
4750

51+
s = "123045"
52+
target = 3
53+
print(add_operator(s, target))
File renamed without changes.

heap/merge_sorted_k_lists.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
3+
"""
4+
5+
# Definition for singly-linked list.
6+
# class ListNode(object):
7+
# def __init__(self, x):
8+
# self.val = x
9+
# self.next = None
10+
11+
from heapq import heappush, heappop, heapreplace, heapify
12+
13+
def mergeKLists(lists):
14+
dummy = node = ListNode(0)
15+
h = [(n.val, n) for n in lists if n]
16+
heapify(h)
17+
while h:
18+
v, n = h[0]
19+
if n.next is None:
20+
heappop(h) #only change heap size when necessary
21+
else:
22+
heapreplace(h, (n.next.val, n.next))
23+
node.next = n
24+
node = node.next
25+
26+
return dummy.next
27+
28+
from Queue import PriorityQueue
29+
30+
def merge_k_lists(lists):
31+
dummy = ListNode(None)
32+
curr = dummy
33+
q = PriorityQueue()
34+
for node in lists:
35+
if node: q.put((node.val,node))
36+
while q.qsize()>0:
37+
curr.next = q.get()[1]
38+
curr=curr.next
39+
if curr.next: q.put((curr.next.val, curr.next))
40+
return dummy.next
41+
42+
43+
"""
44+
I think my code's complexity is also O(nlogk) and not using heap or priority queue,
45+
n means the total elements and k means the size of list.
46+
47+
The mergeTwoLists functiony in my code comes from the problem Merge Two Sorted Lists
48+
whose complexity obviously is O(n), n is the sum of length of l1 and l2.
49+
50+
To put it simpler, assume the k is 2^x, So the progress of combination is like a full binary tree,
51+
from bottom to top. So on every level of tree, the combination complexity is n,
52+
beacause every level have all n numbers without repetition.
53+
The level of tree is x, ie logk. So the complexity is O(nlogk).
54+
55+
for example, 8 ListNode, and the length of every ListNode is x1, x2,
56+
x3, x4, x5, x6, x7, x8, total is n.
57+
58+
on level 3: x1+x2, x3+x4, x5+x6, x7+x8 sum: n
59+
60+
on level 2: x1+x2+x3+x4, x5+x6+x7+x8 sum: n
61+
62+
on level 1: x1+x2+x3+x4+x5+x6+x7+x8 sum: n
63+
"""

tests/test_stack.py

-24
This file was deleted.

tree/binary_tree_paths.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
def binaryTreePaths(root):
2+
res = []
3+
if not root:
4+
return res
5+
DFS(res, root, str(root.val))
6+
return res
7+
8+
def DFS(res, root, cur):
9+
if not root.left and not root.right:
10+
res.append(cur)
11+
if root.left:
12+
DFS(res, root.left, cur+'->'+str(root.left.val))
13+
if root.right:
14+
DFS(res, root.right, cur+'->'+str(root.right.val))

0 commit comments

Comments
 (0)