Skip to content

Commit

Permalink
add more algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
keon committed Jan 3, 2017
1 parent 24db4c4 commit 2fac908
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 28 deletions.
40 changes: 40 additions & 0 deletions array/merge_intervals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
"""

# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e

def merge(intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
out = []
for i in sorted(intervals, key=lambda i: i.start):
if out and i.start <= out[-1].end:
out[-1].end = max(out[-1].end, i.end)
else:
out += i,
return out

def print_intervals(intervals):
res = []
for i in intervals:
res.append('['+str(i.start)+','+str(i.end)+']')
print("".join(res))

if __name__ == "__main__":
given = [[1,3],[2,6],[8,10],[15,18]]
intervals = []
for l, r in given:
intervals.append(Interval(l,r))
print_intervals(intervals)
print_intervals(merge(intervals))
File renamed without changes.
14 changes: 10 additions & 4 deletions divide-and-conquer/expression_add_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,15 @@ def add_operator(num, target):
return res

def helper(res, path, num, target, pos, prev, multed):
print(res, path, num, target, pos, prev, multed)
if pos == len(num):
if (target == prev):
res.append(path)
return
for i in range(pos, len(num)):
if i != pos and num[pos] == '0': break
if i != pos and num[pos] == '0': # all digits have to be used
break
cur = int(num[pos:i+1])
print(cur)
if (pos == 0):
if pos == 0:
helper(res, path + str(cur), num, target, i+1, cur, cur)
else:
helper(res, path + "+" + str(cur), num, target, i+1, prev + cur, cur)
Expand All @@ -44,4 +43,11 @@ def helper(res, path, num, target, pos, prev, multed):
s = "123"
target = 6
print(add_operator(s, target))
# "232", 8 -> ["2*3+2", "2+3*2"]
s = "232"
target = 8
print(add_operator(s, target))

s = "123045"
target = 3
print(add_operator(s, target))
File renamed without changes.
63 changes: 63 additions & 0 deletions heap/merge_sorted_k_lists.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
"""

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

from heapq import heappush, heappop, heapreplace, heapify

def mergeKLists(lists):
dummy = node = ListNode(0)
h = [(n.val, n) for n in lists if n]
heapify(h)
while h:
v, n = h[0]
if n.next is None:
heappop(h) #only change heap size when necessary
else:
heapreplace(h, (n.next.val, n.next))
node.next = n
node = node.next

return dummy.next

from Queue import PriorityQueue

def merge_k_lists(lists):
dummy = ListNode(None)
curr = dummy
q = PriorityQueue()
for node in lists:
if node: q.put((node.val,node))
while q.qsize()>0:
curr.next = q.get()[1]
curr=curr.next
if curr.next: q.put((curr.next.val, curr.next))
return dummy.next


"""
I think my code's complexity is also O(nlogk) and not using heap or priority queue,
n means the total elements and k means the size of list.
The mergeTwoLists functiony in my code comes from the problem Merge Two Sorted Lists
whose complexity obviously is O(n), n is the sum of length of l1 and l2.
To put it simpler, assume the k is 2^x, So the progress of combination is like a full binary tree,
from bottom to top. So on every level of tree, the combination complexity is n,
beacause every level have all n numbers without repetition.
The level of tree is x, ie logk. So the complexity is O(nlogk).
for example, 8 ListNode, and the length of every ListNode is x1, x2,
x3, x4, x5, x6, x7, x8, total is n.
on level 3: x1+x2, x3+x4, x5+x6, x7+x8 sum: n
on level 2: x1+x2+x3+x4, x5+x6+x7+x8 sum: n
on level 1: x1+x2+x3+x4+x5+x6+x7+x8 sum: n
"""
24 changes: 0 additions & 24 deletions tests/test_stack.py

This file was deleted.

14 changes: 14 additions & 0 deletions tree/binary_tree_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def binaryTreePaths(root):
res = []
if not root:
return res
DFS(res, root, str(root.val))
return res

def DFS(res, root, cur):
if not root.left and not root.right:
res.append(cur)
if root.left:
DFS(res, root.left, cur+'->'+str(root.left.val))
if root.right:
DFS(res, root.right, cur+'->'+str(root.right.val))

0 comments on commit 2fac908

Please sign in to comment.