Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
9535e57
Update Uber面经集合.py
UmassJin Jul 29, 2015
eb8f4b9
Update Letter_Combinations_of_a_Phone_Number.py
UmassJin Jul 29, 2015
5764d29
Update Letter_Combinations_of_a_Phone_Number.py
UmassJin Jul 29, 2015
3144439
Update Uber面经集合.py
UmassJin Jul 30, 2015
9dcad60
Update Uber面经集合.py
UmassJin Jul 30, 2015
b5f6c6e
Update Min_Heap_Implement.md
UmassJin Jul 31, 2015
5e1d680
Update Min_Heap_Implement.md
UmassJin Jul 31, 2015
fe49f5d
Update Uber面经集合.py
UmassJin Jul 31, 2015
09e3169
Update Min_Heap_Implement.md
UmassJin Jul 31, 2015
dd3789e
Update Todo_list.md
UmassJin Jul 31, 2015
ed72a00
Update Uber面经集合.py
UmassJin Jul 31, 2015
4f2cba9
Update Uber面经集合.py
UmassJin Aug 1, 2015
aa54bf7
Update Uber面经集合.py
UmassJin Aug 4, 2015
e8e20dc
Update Design_Spreadsheet_OOD.md
UmassJin Aug 4, 2015
03df3fa
Update Design_Spreadsheet_OOD.md
UmassJin Aug 4, 2015
30cdac6
Create Design_elevator.md
UmassJin Aug 4, 2015
c85e4ed
Rename Design_elevator.md to Design_Elevator.md
UmassJin Aug 4, 2015
9d359c5
Update knowledge.md
UmassJin Aug 5, 2015
84d801c
Update knowledge.md
UmassJin Aug 5, 2015
7dc0750
Update about.md
UmassJin Aug 5, 2015
0a6ee45
Update Uber面经集合.py
UmassJin Aug 6, 2015
becc0c3
Create The_Skyline_Problem.py
UmassJin Aug 6, 2015
59dcbe6
Update The_Skyline_Problem.py
UmassJin Aug 6, 2015
97def36
Update Python_Basic.md
UmassJin Aug 7, 2015
a459192
Update Uber面经集合.py
UmassJin Aug 7, 2015
008e753
Update Python_Basic.md
UmassJin Aug 8, 2015
8221330
Update LRU_Cache.py
UmassJin Aug 10, 2015
8bc5065
Update Uber面经集合.py
UmassJin Aug 11, 2015
11ebd99
Update google面经集合.py
UmassJin Aug 11, 2015
8aaddbe
Update Compare_Version_Numbers.py
UmassJin Aug 11, 2015
137fcfc
Update google面经集合.py
UmassJin Aug 12, 2015
69d7975
Update Strongly_Connect_Graph.py
UmassJin Aug 12, 2015
181287e
Update Strongly_Connect_Graph.py
UmassJin Aug 12, 2015
30efca8
Update Tree.py
UmassJin Aug 12, 2015
77d48fe
Update Binary Tree Serialization.py
UmassJin Aug 12, 2015
f038dd9
Update Tree.py
UmassJin Aug 12, 2015
4a2e13d
Update Tree.py
UmassJin Aug 12, 2015
e00804d
Update google面经集合.py
UmassJin Aug 12, 2015
f45349d
Update google面经集合.py
UmassJin Aug 12, 2015
f78ef96
Update google面经集合.py
UmassJin Aug 12, 2015
8bbfb50
Update google面经集合.py
UmassJin Aug 12, 2015
9a46b98
Update google面经集合.py
UmassJin Aug 13, 2015
af33917
Update google面经集合.py
UmassJin Aug 13, 2015
dbc985e
Update google面经集合.py
UmassJin Aug 13, 2015
3c02d53
Update google面经集合.py
UmassJin Aug 13, 2015
1381355
Update google面经集合.py
UmassJin Aug 13, 2015
0528bf5
Update google面经集合.py
UmassJin Aug 13, 2015
19e146d
Update google面经集合.py
UmassJin Aug 13, 2015
ddcf89d
Update google面经集合.py
UmassJin Aug 14, 2015
4a1feb3
Update google面经集合.py
UmassJin Aug 14, 2015
deed338
Update google面经集合.py
UmassJin Aug 14, 2015
a4f62c2
Update google面经集合.py
UmassJin Aug 14, 2015
6801b43
Update Quick_Select.md
UmassJin Aug 14, 2015
5fa793d
Update google面经集合.py
UmassJin Aug 14, 2015
4ace307
Update google面经集合.py
UmassJin Aug 14, 2015
0874576
Update google面经集合.py
UmassJin Aug 14, 2015
3a9847e
Create LICENSE
UmassJin Jan 12, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions Algorithm/Min_Heap_Implement.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,189 @@ heapified :
------------------------------------
```


#### Heap use ```__cmp__```
##### How could we sort the string "abc" and "adef" (which are sorted in each string)?

```python
import random
from random import randint
import heapq

class MyLine(object):
def __init__(self, string):
self.string = string

def __cmp__(self, other):
for i in xrange(min(len(self.string), len(other.string))):
if self.string[i] > other.string[i]:
return 1
elif self.string[i] < other.string[i]:
return -1
else:
continue
if len(self.string) > len(other.string):
return 1
elif len(self.string) < len(other.string):
return -1
else:
return 0

def merge_karray(files):
'''
@ input files list: [file1, file2, file3...]
@ output:
'''
if not files: return None
heap = []
result = []
k = len(files)
for i in xrange(k):
ele = files[i]
if ele:
heap.append((MyLine(ele), i))
heapq.heapify(heap)

while heap:
element = heapq.heappop(heap)
value, file_index = element[0], element[1]
result.append(value.string)
return result

if __name__ == '__main__':
lines = []
for i in xrange(5):
lines.append('abc' + str(randint(1,200)))
lines.append('efg' + str(randint(1,200)))
lines.append('xyz' + str(randint(1,200)))
print merge_karray(lines)

```

##### Uber phone interview
```python
# given a list of filenames, each file has been sorted
# merge into a big file

from random import randint
import heapq

class MyFile(object):
def __init__(self, n):
self.lines = []
self.i = 0
self.length = 3
r = 0
for i in xrange(n):
pass
# r = randint(r, r + 100)
# self.lines.append(str(r))
self.lines.append('abc' + str(randint(1,200)))
self.lines.append('efg' + str(randint(1,200)))
self.lines.append('xyz' + str(randint(1,200)))

# sort by alphabetical order
# compare 1st letter
# if 1st letter is same,compare 2nd, etc.
# content of file:
# acd
# abc
# xyz
# xyy
# sorted:
# abc
# acd
# xyy,
# xyz
# sorted(str, cmp = lambda x: )

def nextline(self):
if self.i < self.length:
self.i += 1
return self.lines[self.i - 1]
else:
return None

def merge_karray(files):
'''
@ input files list: [file1, file2, file3...]
@ output:
'''
if not files:
return None
heap = []
result = []
k = len(files)
for i in xrange(k):
ele = files[i].nextline()
if ele:
heap.append((MyLine(ele), i))
heapq.heapify(heap)
#print "heap: ", heap

while heap:
element = heapq.heappop(heap)
value, file_index = element[0], element[1]
result.append(value.string)
new_value = files[file_index].nextline()
if new_value:
heapq.heappush(heap, (MyLine(new_value), file_index))
return result


# "abc", "abcd"
class MyLine(object):
def __init__(self, string):
self.string = string

def __cmp__(self, other):
for i in xrange(min(len(self.string), len(other.string))):
if self.string[i] > other.string[i]:
return 1
elif self.string[i] < other.string[i]:
return -1
else:
continue
if len(self.string) > len(other.string):
return 1
elif len(self.string) < len(other.string):
return -1
else:
return 0
# comapre between 2 strings



if __name__ == '__main__':
f1 = MyFile(10)
f2 = MyFile(20)
f3 = MyFile(15)
k = 10
files = []
for i in xrange(k):
files.append(MyFile(3))
str1 = "abcd"
str2 = "abcf"
# test = MyLine(str1)
# __cmp__
#print MyLine("abcz") < MyLine("abcd")

# files
# for f in files:
# print '-'*20
# l = f.nextline()
# while l:
# print l
# l = f.nextline()
print merge_karray(files)


```


* [Merge K sorted linked list](https://github.com/UmassJin/Leetcode/blob/master/Array/Merge_K_Sorted_Lists.py)
* [Merge K sorted array](https://github.com/UmassJin/Leetcode/blob/master/Experience/Merge_k_sorted_array.md)
* [Good Video about how to make max heap](https://www.youtube.com/watch?v=WsNQuCa_-PU)
* [Median in stream data](https://github.com/UmassJin/Leetcode/blob/master/Experience/Median_in_stream_data.py)
* [Find K closet points](https://github.com/UmassJin/Leetcode/blob/master/Experience/K_closet_points.py)
* [Python __cmp__ compare](http://stackoverflow.com/questions/11989178/how-to-heapify-by-field-from-custom-objects)
3 changes: 3 additions & 0 deletions Algorithm/Quick_Select.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ array = [12, 3, 5, 7, 4, 19, 26]
print KthSmallest(array, 0, len(array)-1, 3)
```

time complexity:
The worst case time complexity of the above solution is still O(n2). In worst case, the randomized function may always pick a corner element. The expected time complexity of above randomized QuickSelect is Θ(n)

#### Reference
* [G4G set1](http://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/)
* [G4G set2](http://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array-set-2-expected-linear-time/)
Expand Down
15 changes: 10 additions & 5 deletions Algorithm/Strongly_Connect_Graph.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
# http://www.geeksforgeeks.org/strongly-connected-components/
# http://www.geeksforgeeks.org/connectivity-in-a-directed-graph/
'''
Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pair of vertices. For example, following is a strongly connected graph.
`对于无向图来说判断连通非常简单,只需要做一次搜索,然后判断路径中是否经过了每个节点即可。但是有向图不可以这么做,比如上图,从节点0开始搜索可以经过所有节点,但是很明显它不是strongly connected。
Naive的方法是,对每一个节点做一次DFS,如果存在一个节点在DFS中没有经过每一个节点,那么则不是强连通图。这个算法复杂度是O(V*(V+E))。
Given a directed graph, find out whether the graph is strongly connected or not.
A directed graph is strongly connected if there is a path between any two pair of vertices.
For example, following is a strongly connected graph.
`对于无向图来说判断连通非常简单,只需要做一次搜索,然后判断路径中是否经过了每个节点即可。
但是有向图不可以这么做,比如上图,从节点0开始搜索可以经过所有节点,但是很明显它不是strongly connected。
Naive的方法是,对每一个节点做一次DFS,如果存在一个节点在DFS中没有经过每一个节点,那么则不是强连通图。
这个算法复杂度是O(V*(V+E))。
或者用Floyd Warshall算法来找出任意两个节点的最短路径。复杂度是O(v3)。

一个更好的办法是强连通分量算法Strongly Connected Components (SCC) algorithm。我们可以用O(V+E)时间复杂度找出一个图中所有的SCC。如果SCC只有一个,那么这个图就是强连通图。
一个更好的办法是强连通分量算法Strongly Connected Components (SCC) algorithm。
我们可以用O(V+E)时间复杂度找出一个图中所有的SCC。如果SCC只有一个,那么这个图就是强连通图。

用Kosaraju算法,两个pass做DFS:

Expand All @@ -21,7 +26,7 @@ def dfs(node, visited):
visited[node] = True
for neighbor in node.neighbor:
if not visited[neighbor]:
dfs(neighbor)
dfs(neighbor, visited)

def strongly_connected_graph(graph):
visited = [False for i in xrange(graph.V)]
Expand Down
7 changes: 7 additions & 0 deletions Array/Compare_Version_Numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@

0.1 < 1.1 < 1.2 < 13.37

# https://leetcode.com/discuss/45331/2-4-lines-python-3-different-ways
def compareVersion(self, version1, version2):
v1, v2 = (map(int, v.split('.')) for v in (version1, version2))
d = len(v2) - len(v1)
return cmp(v1 + [0]*d, v2 + [0]*-d)


class Solution:
# @param version1, a string
# @param version2, a string
Expand Down
6 changes: 4 additions & 2 deletions Array/LRU_Cache.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
'''
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
set(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
'''

class ListNode:
Expand Down
45 changes: 25 additions & 20 deletions Array/Letter_Combinations_of_a_Phone_Number.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

class Solution:
# @return a list of strings, [s1, s2]
dict = {'1':'',
dict = {'0':'',
'1':'',
'2':'abc',
'3':'def',
'4':'ghi',
Expand All @@ -21,43 +22,33 @@ class Solution:

# Iteration
def letterCombinations(self, digits):
if len(digits)==0: return []
if not digits: return []
result = [''] # Note: here we should use [''] not empty []
for digit in digits:
ret = []
for comb in result:
for char in Solution.dict[digit]:
ret.append(comb+char)
result = ret
if ret: # Note: add ret here, we need to consider the case "12"
result = ret
return result

# Recursion 1
def letterCombinations_1(self, digits):
if len(digits)==0: return []
result = []
self.combination_rec(digits,0,result,'')
return result

def combination_rec(self,digits,i,result,ret):
if i == len(digits): #注意这里一定要check i == len(digits), check the following recursion solution !
result.append(ret)
return
for char in Solution.dict[digits[i]]: # Here we do not need to for loop the digits !!!
self.combination_rec(digits,i+1,result,ret+char)

# Recursion 2
# Recursion 1
def letterCombinations(self, digits):
if not digits: return []
result = []
length = len(digits)
self.letter_com_helper(digits, result, '',length)
self.letter_com_helper(digits, result, '', length)
return result

def letter_com_helper(self, digits, result, substr,length):
if len(digits) == 0 and len(substr) == length: # 这里如果我们传递digits[i+1:] 还需要check len(substr) == length
if len(substr) == length:
result.append(substr); return

for i, digit in enumerate(digits):
if digit == "1" or digit == '0': # take care the special '1' and '0' case
length -= 1
for char in Solution.dict[digit]:
self.letter_com_helper(digits[i+1:], result, substr + char,length)

Expand All @@ -66,7 +57,21 @@ def letter_com_helper(self, digits, result, substr,length):
# Output: ["aa","ab","ac","ba","bb","bc","ca","cb","cc","a","b","c"]
# Expected: ["aa","ab","ac","ba","bb","bc","ca","cb","cc"]

# Recursion 2
# Recursion 2
def letterCombinations_1(self, digits):
if len(digits)==0: return []
result = []
self.combination_rec(digits,0,result,'')
return result

def combination_rec(self,digits,i,result,ret):
if i == len(digits): #注意这里一定要check i == len(digits), check the following recursion solution !
result.append(ret)
return
for char in Solution.dict[digits[i]]: # Here we do not need to for loop the digits !!!
self.combination_rec(digits,i+1,result,ret+char)

# Recursion 3
def letterCombinations_2(self, digits):
if digits == "":
return [""]
Expand Down
Loading