Skip to content

Commit

Permalink
1102-04/10
Browse files Browse the repository at this point in the history
  • Loading branch information
youhusky committed Nov 3, 2017
1 parent c3a5a30 commit d4ebb7d
Show file tree
Hide file tree
Showing 5 changed files with 262 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 043. Multiply Strings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

# Note:

# The length of both num1 and num2 is < 110.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert the inputs to integer directly.

# must see the Leetcode First Discussion

class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
m = len(num1)
n = len(num2)

pos = [0 for _ in range(m+n)]

for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):

second_position = i+j
first_position = i+j+1

original = int(num1[i]) * int(num2[j])
temp = original + pos[first_position]

pos[second_position] += temp / 10 ## 15/10 = 5
pos[first_position] = temp % 10 ## 15%10 = 1
res = ""
for i in pos:
if not res and i == 0:
continue
res += str(i)
return res if res else '0'


67 changes: 67 additions & 0 deletions 049. Group Anagrams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Given an array of strings, group anagrams together.

# For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
# Return:

# [
# ["ate", "eat","tea"],
# ["nat","tan"],
# ["bat"]
# ]
# Note: All inputs will be in lower-case.
# Solution 1 sorted str
class Solution(object):
def groupAnagrams(self, strs):
"""
O(nklgk)
k-length of word in list
:type strs: List[str]
:rtype: List[List[str]]
"""
dic = {}
for word in strs:
ori = word
# imp
word = str(sorted(word))

if word not in dic:
dic[word] = [ori]
else:
dic[word].append(ori)
return dic.values()

# Note: All inputs will be in lower-case.
# Solution 2

# we can create size equals to 26 list to store

class Solution(object):
def groupAnagrams(self, strs):
"""
O(nk)
:type strs: List[str]
:rtype: List[List[str]]
"""
if not strs:
return []
dic = {}

for word in strs:
# init count
count = [0 for _ in range(26)]
for char in word:
count[ord(char) - ord('a')] += 1

# rebuild str
temp = ""
for i in range(26):
if count[i] != 0:
temp += chr(i+97) * count[i]
print temp
if temp not in dic:
dic[temp] = [word]
else:
dic[temp].append(word)
return dic.values()


99 changes: 99 additions & 0 deletions 380. Insert Delete GetRandom O(1).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Design a data structure that supports all following operations in average O(1) time.

# insert(val): Inserts an item val to the set if not already present.
# remove(val): Removes an item val from the set if present.
# getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
# Example:

# // Init an empty set.
# RandomizedSet randomSet = new RandomizedSet();

# // Inserts 1 to the set. Returns true as 1 was inserted successfully.
# randomSet.insert(1);

# // Returns false as 2 does not exist in the set.
# randomSet.remove(2);

# // Inserts 2 to the set, returns true. Set now contains [1,2].
# randomSet.insert(2);

# // getRandom should return either 1 or 2 randomly.
# randomSet.getRandom();

# // Removes 1 from the set, returns true. Set now contains [2].
# randomSet.remove(1);

# // 2 was already in the set, so return false.
# randomSet.insert(2);

# // Since 2 is the only number in the set, getRandom always return 2.
# randomSet.getRandom();

# use array to save index
import random
class RandomizedSet(object):

def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}

self.array = []

def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""

if val in self.dic:
return False
# use array.length as the value!
self.dic[val] = len(self.array)
self.array.append(val)
#print 'insert', self.array
return True


def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.dic:
return False

if val != self.array[-1]:
swapitem = self.array[-1]
index = self.dic[val]

self.array[index] = swapitem
self.dic[swapitem] = index



#print 'remove',self.array
self.array.pop()
#print 'removed',self.array
del(self.dic[val])
return True



def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.array[random.randint(0,len(self.array)-1)]



# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
5 changes: 5 additions & 0 deletions 525. Contiguous Array.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def findMaxLength(self, nums):
# init
dic[0] = -1
for i in range(len(nums)):

if nums[i] == 0:
zero += 1
else:
Expand All @@ -32,4 +33,8 @@ def findMaxLength(self, nums):
res = max(res, i - dic[zero-one])
else:
dic[zero-one] = i
print i,dic
return res
test = [1,0,0,0,0,1,1,1]
m = Solution()
print m.findMaxLength(test)
49 changes: 49 additions & 0 deletions 554. Brick Wall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

# The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

# If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

# You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

# Example:
# Input:
# [[1,2,2,1],
# [3,1,2],
# [1,3,2],
# [2,4],
# [3,1,2],
# [1,3,1,1]]
# Output: 2
# Explanation:

# Note:
# The width sum of bricks in different rows are the same and won't exceed INT_MAX.
# The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.

# Use HashMap to store where wall is broken
# Interesting Idea
from collections import defaultdict
class Solution(object):
def leastBricks(self, wall):
"""
:type wall: List[List[int]]
:rtype: int
"""
if not wall:
return 0
# init
dic = defaultdict(int)
res = 0

for each_wall in wall:
length = 0
for brick in range(len(each_wall)-1):
# not include the last one
length += each_wall[brick]
dic[length] += 1
res = max(res, dic[length])

return len(wall) - res


0 comments on commit d4ebb7d

Please sign in to comment.