Skip to content

Commit

Permalink
update bunch
Browse files Browse the repository at this point in the history
  • Loading branch information
keon committed Mar 14, 2017
1 parent 708c190 commit b3583c1
Show file tree
Hide file tree
Showing 68 changed files with 1,603 additions and 92 deletions.
11 changes: 0 additions & 11 deletions array/house_robber.py

This file was deleted.

1 change: 1 addition & 0 deletions array/plus_one.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# The digits are stored such that the most significant
# digit is at the head of the list.


def plusOne(digits):
"""
:type digits: List[int]
Expand Down
30 changes: 30 additions & 0 deletions array/rotate_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3,
the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can,
there are at least 3 different ways to solve this problem.
"""


def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
reverse(nums, 0, n - k - 1)
reverse(nums, n - k, n - 1)
reverse(nums, 0, n - 1)


def reverse(array, a, b):
while a < b:
array[a], array[b] = array[b], array[a]
a += 1
b -= 1
46 changes: 46 additions & 0 deletions array/three_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""
Given an array S of n integers, are there elements a, b, c in S
such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
"""


def three_sum(nums:"List[int]")->"List[int]":
res = []
nums.sort()
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, len(nums)-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s > 0:
r -= 1
elif s < 0:
l += 1
else:
# found three sum
res.append((nums[i], nums[l], nums[r]))
# remove duplicates
while l < r and nums[l] == nums[l+1]:
l+=1
while l < r and nums[r] == nums[r-1]:
r -= 1
l += 1
r -= 1
return res


if __name__ == "__main__":
x = [-1,0,1,2,-1,-4]
print(three_sum(x))
29 changes: 29 additions & 0 deletions array/two_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
Given an array of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""


def two_sum(nums:"List[int]", target:"int")->"List[int]":
dic = {}
for i, num in enumerate(nums):
if num in dic:
return [dic[num], i]
else:
dic[target - num] = i


if __name__ == "__main__":
arr = [3,2,4]
target = 6
res = two_sum(arr, target)
print(res)
File renamed without changes.
32 changes: 32 additions & 0 deletions backtrack/generate_parenthesis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""
Given n pairs of parentheses, write a function to generate
all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""

def gen_parenthesis(n:"int")->"List[str]":
res = []
add_pair(res, "", n, 0)
return res

def add_pair(res, s, left, right):
if left == 0 and right == 0:
res.append(s)
return
if right > 0:
add_pair(res, s+")", left, right-1)
if left > 0:
add_pair(res, s+"(", left-1, right+1)


if __name__=="__main__":
print(gen_parenthesis(3))
35 changes: 35 additions & 0 deletions backtrack/letter_combination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Given a digit string, return all possible letter
combinations that the number could represent.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
"""


def letter_combinations(digits:"str")->"List[str]":
if digits == "":
return []
kmaps = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
ans = [""]
for num in digits:
tmp = []
for an in ans:
for char in kmaps[num]:
tmp.append(an + char)
ans = tmp
return ans


if __name__ == "__main__":
digit_string = "23"
print(letter_combinations(digit_string))
10 changes: 10 additions & 0 deletions backtrack/subsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
# ]


# O(2**n)


def subsets(nums):
res = []
backtrack(res, nums, [], 0)
Expand Down Expand Up @@ -44,6 +47,13 @@ def backtrack(res, nums, stack, pos):
# backtrack(res, nums, cur, pos+1)


# Iteratively
def subsets2(self, nums):
res = [[]]
for num in sorted(nums):
res += [item+[num] for item in res]
return res

test = [1,2,3]
print(test)
print(subsets(test))
21 changes: 21 additions & 0 deletions bit/count_ones.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
Write a function that takes an unsigned integer and
returns the number of ’1' bits it has
(also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary
representation 00000000000000000000000000001011,
so the function should return 3.
"""


def count_ones(n):
"""
:type n: int
:rtype: int
"""
counter = 0
while n:
counter += n & 1
n >>= 1
return counter
18 changes: 18 additions & 0 deletions bit/reverse_bits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596
(represented in binary as 00000010100101000001111010011100),
return 964176192
(represented in binary as 00111001011110000010100101000000).
"""


def reverse_bits(n):
m = 0
i = 0
while i < 32:
m = (m << 1) + (n & 1)
n >>= 1
i += 1
return m
19 changes: 19 additions & 0 deletions bit/single_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
Given an array of integers, every element appears
twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity.
Could you implement it without using extra memory?
"""


def single_number(nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
for num in nums:
i ^= num
return i
46 changes: 46 additions & 0 deletions bit/single_number2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""
Given an array of integers, every element appears
three times except for one, which appears exactly once.
Find that single one.
Note:
Your algorithm should have a linear runtime complexity.
Could you implement it without using extra memory?
"""


"""
32 bits for each integer.
Consider 1 bit in it, the sum of each integer's corresponding bit
(except for the single number)
should be 0 if mod by 3. Hence, we sum the bits of all
integers and mod by 3,
the remaining should be the exact bit of the single number.
In this way, you get the 32 bits of the single number.
"""


def single_number(nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in range(0, 32):
count = 0
for num in nums:
if ((num >> i) & 1):
count += 1
res |= ((count % 3) << i)
if res >= 2**31:
res -= 2**32
return res


# Another awesome answer
def single_number2(nums):
ones, twos = 0, 0
for i in range(len(nums)):
ones = (ones ^ nums[i]) & ~twos
twos = (twos ^ nums[i]) & ~ones
return ones
Loading

0 comments on commit b3583c1

Please sign in to comment.