Skip to content

Commit 72ac886

Browse files
Kurt-Yuhaoel
authored andcommitted
added some python solutions
1 parent afd1009 commit 72ac886

File tree

13 files changed

+259
-8
lines changed

13 files changed

+259
-8
lines changed

README.md

+12-8
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,12 @@ LeetCode
88

99
| # | Title | Solution | Difficulty |
1010
|---| ----- | -------- | ---------- |
11+
|976|[Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle/) | [Python](./algorithms/python/LargestPerimeterTriangle/largestPerimeter.py)|Easy|
1112
|971|[Flip Binary Tree To Match Preorder Traversal](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/) | [Python](./algorithms/python/FlipBinaryTreeToMatchPreorderTraversal/flipMatchVoyage.py)|Medium|
13+
|969|[Pancake Sorting](https://leetcode.com/problems/pancake-sorting/) | [Python](./algorithms/python/PancakeSorting/pancakeSort.py)|Medium|
1214
|958|[Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/) | [Python](./algorithms/python/CheckCompletenessOfABinaryTree/isCompleteTree.py)|Medium|
1315
|951|[Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) | [Python](./algorithms/python/FlipEquivalentBinaryTrees/flipEquiv.py)|Medium|
16+
|950|[Reveal Cards In Increasing Order](https://leetcode.com/problems/reveal-cards-in-increasing-order/) | [Python](./algorithms/python/RevealCardsInIncreasingOrder/deckRevealedIncreasing.py)|Medium|
1417
|859|[Buddy Strings](https://leetcode.com/problems/buddy-strings/description/) | [C++](./algorithms/cpp/buddyStrings/BuddyStrings.cpp)|Easy|
1518
|858|[Mirror Reflection](https://leetcode.com/problems/mirror-reflection/description/) | [C++](./algorithms/cpp/mirrorReflection/MirrorReflection.cpp)|Medium|
1619
|852|[Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/description/) | [C++](./algorithms/cpp/peakIndexInAMountainArray/PeakIndexInAMountainArray.cpp)|Easy|
@@ -30,6 +33,7 @@ LeetCode
3033
|563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | [Python](./algorithms/python/BinaryTreeTilt/findTilt.py)|Easy|
3134
|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [Python](./algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py)|Easy|
3235
|538|[Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [Python](./algorithms/python/ConvertBSTtoGreaterTree/convertBST.py)|Easy|
36+
|509|[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](./algorithms/python/FibonacciNumber/fib.py)|Easy|
3337
|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp)|Medium|
3438
|450|[DeleteNodeInABST](https://leetcode.com/problems/delete-node-in-a-bst/) | [Python](./algorithms/python/DeleteNodeInABST/deleteNode.py)|Medium|
3539
|449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/) | [Python](./algorithms/python/SerializeAndDeserializeBST/serialize.py)|Medium|
@@ -130,8 +134,8 @@ LeetCode
130134
|258|[Add Digits](https://leetcode.com/problems/add-digits/)| [C++](./algorithms/cpp/addDigits/addDigits.cpp)|Easy|
131135
|257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)| [C++](./algorithms/cpp/binaryTreePaths/binaryTreePaths.cpp)|Easy|
132136
|242|[Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [C++](./algorithms/cpp/anagrams/ValidAnagram.cpp), [Java](./algorithms/java/src/validAnagram/ValidAnagram.java)|Easy|
133-
|241|[Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/)|[C++](./algorithms/cpp/differentWaysToAddParentheses/DifferentWaysToAddParentheses.cpp)|Medium|
134-
|240|[Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/)|[C++](./algorithms/cpp/search2DMatrix/search2DMatrix.II.cpp), [Java](./algorithms/java/src/searchA2DMatrixII/SearchA2DMatrixII.java)|Medium|
137+
|241|[Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/)|[C++](./algorithms/cpp/differentWaysToAddParentheses/DifferentWaysToAddParentheses.cpp), [Python](./algorithms/python/DifferentWaysToAddParentheses/diffWaysToCompute.py)|Medium|
138+
|240|[Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/)|[C++](./algorithms/cpp/search2DMatrix/search2DMatrix.II.cpp), [Java](./algorithms/java/src/searchA2DMatrixII/SearchA2DMatrixII.java), [Python](./algorithms/python/SearchA2DMatrixII/searchMatrix.py)|Medium|
135139
|239|[Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [C++](./algorithms/cpp/slidingWindowMaximum/SlidingWindowMaximum.cpp)|Hard|
136140
|238|[Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)| [C++](./algorithms/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp)|Medium|
137141
|237|[Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./algorithms/cpp/deleteNodeInALinkedList/DeleteNodeInALinkedList.cpp)|Easy|
@@ -169,11 +173,11 @@ LeetCode
169173
|205|[Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)| [C++](./algorithms/cpp/isomorphicStrings/IsomorphicStrings.cpp)|Easy|
170174
|204|[Count Primes](https://leetcode.com/problems/count-primes/)| [C++](./algorithms/cpp/countPrimes/CountPrimes.cpp)|Easy|
171175
|203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [C++](./algorithms/cpp/removeLinkedListElements/RemoveLinkedListElements.cpp)|Easy|
172-
|202|[Happy Number](https://leetcode.com/problems/happy-number/)| [C++](./algorithms/cpp/happyNumber/HappyNumber.cpp)|Easy|
176+
|202|[Happy Number](https://leetcode.com/problems/happy-number/)| [C++](./algorithms/cpp/happyNumber/HappyNumber.cpp), [Python](./algorithms/python/HappyNumber/isHappy.py)|Easy|
173177
|201|[Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/)| [C++](./algorithms/cpp/bitwiseANDOfNumbersRange/BitwiseAndOfNumbersRange.cpp)|Medium|
174-
|200|[Number of Islands](https://leetcode.com/problems/number-of-islands/)| [C++](./algorithms/cpp/numberOfIslands/NumberOfIslands.cpp)|Medium|
178+
|200|[Number of Islands](https://leetcode.com/problems/number-of-islands/)| [C++](./algorithms/cpp/numberOfIslands/NumberOfIslands.cpp), [Python](./algorithms/python/NumberOfIslands/numIslands.py)|Medium|
175179
|199|[Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/)| [C++](./algorithms/cpp/binaryTreeRightSideView/binaryTreeRightSideView.cpp)|Medium|
176-
|198|[House Robber](https://leetcode.com/problems/house-robber/)| [C++](./algorithms/cpp/houseRobber/houseRobber.cpp)|Easy|
180+
|198|[House Robber](https://leetcode.com/problems/house-robber/)| [C++](./algorithms/cpp/houseRobber/houseRobber.cpp), [Python](./algorithms/python/HouseRobber/rob.py)|Easy|
177181
|191|[Number of 1 Bits](https://oj.leetcode.com/problems/number-of-1-bits/)| [C++](./algorithms/cpp/numberOf1Bits/numberOf1Bits.cpp)|Easy|
178182
|190|[Reverse Bits](https://oj.leetcode.com/problems/reverse-bits/)| [C++](./algorithms/cpp/reverseBits/reverseBits.cpp)|Easy|
179183
|189|[Rotate Array](https://oj.leetcode.com/problems/rotate-array/)| [C++](./algorithms/cpp/rotateArray/rotateArray.cpp), [Java](./algorithms/java/src/rotateArray/RotateArray.java)|Easy|
@@ -212,12 +216,12 @@ LeetCode
212216
|146|[LRU Cache](https://oj.leetcode.com/problems/lru-cache/)| [C++](./algorithms/cpp/LRUCache/LRUCache.cpp), [Java](./algorithms/java/src/lruCache/LRUCache.java)|Hard|
213217
|145|[Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/)| [C++](./algorithms/cpp/binaryTreePostorderTraversal/binaryTreePostorderTraversal.cpp), [Python](./algorithms/python/BinaryTreePostorderTraversal/postorderTraversal.py)|Hard|
214218
|144|[Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/)| [C++](./algorithms/cpp/binaryTreePreorderTraversal/binaryTreePreorderTraversal.cpp), [Java](./algorithms/java/src/binaryTreePreorderTraversal/binaryTreePreorderTraversal.java)|Medium|
215-
|143|[Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [C++](./algorithms/cpp/reorderList/reorderList.cpp)|Medium|
216-
|142|[Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [C++](./algorithms/cpp/linkedListCycle/linkedListCycle.II.cpp)|Medium|
219+
|143|[Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [C++](./algorithms/cpp/reorderList/reorderList.cpp), [Python](./algorithms/python/ReorderList/reorderList.py)|Medium|
220+
|142|[Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [C++](./algorithms/cpp/linkedListCycle/linkedListCycle.II.cpp), [Python](./algorithms/python/LinkedListCycleII/detectCycle.py)|Medium|
217221
|141|[Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [C++](./algorithms/cpp/linkedListCycle/linkedListCycle.cpp)|Medium|
218222
|140|[Word Break II](https://oj.leetcode.com/problems/word-break-ii/)| [C++](./algorithms/cpp/wordBreak/wordBreak.II.cpp)|Hard|
219223
|139|[Word Break](https://oj.leetcode.com/problems/word-break/)| [C++](./algorithms/cpp/wordBreak/wordBreak.cpp)|Medium|
220-
|138|[Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/)| [C++](./algorithms/cpp/copyListWithRandomPointer/copyListWithRandomPointer.cpp)|Hard|
224+
|138|[Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/)| [C++](./algorithms/cpp/copyListWithRandomPointer/copyListWithRandomPointer.cpp), [Python](./algorithms/python/CopyListWithRandomPointer/copyRandomList.py)|Hard|
221225
|137|[Single Number II](https://oj.leetcode.com/problems/single-number-ii/)| [C++](./algorithms/cpp/singleNumber/singleNumber.II.cpp)|Medium|
222226
|136|[Single Number](https://oj.leetcode.com/problems/single-number/)| [C++](./algorithms/cpp/singleNumber/singleNumber.cpp)|Medium|
223227
|135|[Candy](https://oj.leetcode.com/problems/candy/)| [C++](./algorithms/cpp/candy/candy.cpp)|Hard|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# method 1: using a dict and store each node as key, each copied node as value
2+
# Space complexity: O(n)
3+
# Time complexity: O(n)
4+
5+
def copyRandomList(self, head):
6+
d = {}
7+
m = n = head
8+
while m:
9+
d[m] = RandomListNode(m.label)
10+
m = m.next
11+
12+
while n:
13+
d[n].next = d.get(n.next)
14+
d[n].random = d.get(n.random)
15+
n = n.next
16+
17+
return d.get(head)
18+
19+
# Method 2:
20+
# Space complexity: O(1)
21+
# Time complexity: O(n)
22+
23+
def copyRandomList(self, head):
24+
if not head: return None
25+
26+
# Step 1: copy each node and link them together with original ones
27+
curr = head
28+
while curr:
29+
new = RandomListNode(curr.label)
30+
new.next = curr.next
31+
curr.next = new
32+
curr = curr.next.next
33+
34+
# Step 2: build random node for each copied nodes
35+
curr = head
36+
while curr:
37+
if curr.random: curr.next.random = curr.random.next
38+
curr = curr.next.next
39+
40+
# Step 3: restore the original list and extract copied list
41+
newhead = head.next
42+
pold = head
43+
pnew = newhead
44+
while pnew.next:
45+
pold.next = pnew.next
46+
pold = pold.next
47+
pnew.next = pold.next
48+
pnew = pnew.next
49+
pold.next = None
50+
pnew.next = None
51+
return newhead
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def diffWaysToCompute(self, input):
2+
return [a + b if c == '+' else a - b if c == '-' else a * b \
3+
for i, c in enumerate(input) if c in '+-*' \
4+
for a in self.diffWaysToCompute(input[:i]) \
5+
for b in self.diffWaysToCompute(input[i+1:])] or [int(input)]
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
Method 1: iterative:
3+
"""
4+
def fib1(self, N):
5+
if N <= 1: return N
6+
a, b = 0, 1
7+
for _ in range(2, N + 1):
8+
a, b = b, a + b
9+
return b
10+
11+
"""
12+
Method 2: recursive without memorization:
13+
"""
14+
def fib2(self, N):
15+
if N <= 1: return N
16+
return self.fib(N - 1) + self.fib(N - 2)
17+
18+
"""
19+
Method 3: recursive with memorization
20+
"""
21+
def fib3(self, N):
22+
memo = {0:0, 1:1}
23+
def helper(n):
24+
if n not in memo:
25+
memo[n] = helper(n - 1) + helper(n - 2)
26+
return memo[n]
27+
return helper(N)
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Method 1: straight forward solution, use a set to track if there is a cycle
2+
3+
def isHappy1(self, n):
4+
if n <= 0: return False
5+
s = set()
6+
while n not in s:
7+
s.add(n)
8+
n = sum([int(i) ** 2 for i in str(n)])
9+
if n == 1: return True
10+
return False
11+
12+
# Method 2: using a slow and fast pointer to determine cycle (like in linked list)
13+
# No extra space needed
14+
def isHappy2(self, n):
15+
"""
16+
:type n: int
17+
:rtype: bool
18+
"""
19+
if n <= 0: return False
20+
def helper(n):
21+
res = 0
22+
while n:
23+
res += (n % 10) ** 2
24+
n = n // 10
25+
return res
26+
27+
slow = fast = n
28+
while True:
29+
slow = helper(slow)
30+
fast = helper(helper(fast))
31+
if slow == 1: return True
32+
if slow == fast: break
33+
return False

algorithms/python/HouseRobber/rob.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def rob(self, nums):
2+
temp = [0, 0]
3+
for n in nums:
4+
temp[0], temp[1] = max(temp), n + temp[0]
5+
6+
return max(temp)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def largestPerimeter(self, A):
2+
A.sort()
3+
n = len(A)
4+
for i in range(1, len(A) - 1):
5+
if A[n - i - 2] + A[n - i - 1] > A[n - i]:
6+
return A[n - i - 2] + A[n - i - 1] + A[n - i]
7+
return 0
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def detectCycle(self, head):
2+
slow, fast = head, head
3+
while fast and fast.next:
4+
slow = slow.next
5+
fast = fast.next.next
6+
if slow == fast: break
7+
8+
if not fast or not fast.next: return None
9+
slow = head
10+
while slow != fast:
11+
slow = slow.next
12+
fast = fast.next
13+
return slow
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
def numIslands(self, grid):
2+
if not grid or not grid[0]: return 0
3+
row, col = len(grid), len(grid[0])
4+
self.visited = [[False for _ in range(col)] for _ in range(row)]
5+
6+
def floodfill(i, j):
7+
if grid[i][j] == '1' and self.visited[i][j] == False:
8+
self.visited[i][j] = True
9+
if i > 0:
10+
floodfill(i - 1, j)
11+
if i < row - 1:
12+
floodfill(i + 1, j)
13+
if j > 0:
14+
floodfill(i, j - 1)
15+
if j < col - 1:
16+
floodfill(i, j + 1)
17+
18+
res = 0
19+
for i in range(row):
20+
for j in range(col):
21+
if grid[i][j] == '1' and self.visited[i][j] == False:
22+
res += 1
23+
floodfill(i, j)
24+
return res
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
basic idea: find the index of smallest element in A, filp the list from that index, this makes the smallest element
3+
comes to the first, then filp the whole list, to make smallest element goes to the tail. And then delete that element.
4+
5+
Do this step until all the smallest element comes to the tail, then just filp the whole list again, and we can get what we want
6+
"""
7+
8+
def pancakeSort(self, A):
9+
res = []
10+
n = len(A)
11+
while A:
12+
smallest = A.index(min(A))
13+
res.append(smallest + 1)
14+
res.append(len(A))
15+
A = list(reversed(A[:smallest + 1])) + A[smallest + 1:]
16+
A.reverse()
17+
del A[-1]
18+
res.append(n)
19+
return res
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def reorderList(self, head):
2+
if not head or not head.next: return
3+
4+
# Step 1: find the middle node
5+
middle = None
6+
slow, fast = head, head
7+
while fast and fast.next:
8+
middle = slow
9+
slow = slow.next
10+
fast = fast.next.next
11+
middle.next = None
12+
13+
# Step 2: reverse the second half
14+
prev = None
15+
while slow:
16+
nextNode = slow.next
17+
slow.next = prev
18+
prev, slow = slow, nextNode
19+
20+
# Step 3: merge two lists
21+
while head and prev:
22+
first, second = head.next, prev.next
23+
head.next = prev
24+
if first: prev.next = first
25+
head, prev = first, second
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def deckRevealedIncreasing(self, deck):
2+
deck.sort()
3+
res = [0] * len(deck)
4+
index = list(range(len(deck)))
5+
6+
for i in range(len(deck)):
7+
res[index.pop(0)] = deck[i]
8+
if index: index.append(index.pop(0))
9+
return res
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Method 1: Binary Search on each row, if the first element of the row is already bigger than target, then skip
2+
# Time Complexity: O(mlogn)
3+
def searchMatrix1(self, matrix, target):
4+
def helper(low, high, row):
5+
while low <= high:
6+
mid = (low + high) // 2
7+
if matrix[row][mid] < target: low = mid + 1
8+
elif matrix[row][mid] > target: high = mid - 1
9+
else: return True
10+
return False
11+
12+
if not matrix or not matrix[0]: return False
13+
for i in range(len(matrix)):
14+
if matrix[i][0] > target: return False
15+
elif matrix[i][0] == target: return True
16+
if helper(0, len(matrix[i]) - 1, i): return True
17+
return False
18+
19+
# Method 2: compare the element with top-right corner, and reduce the search range
20+
# Time complexity: O(m + n)
21+
def searchMatrix2(self, matrix, target):
22+
if not matrix or not matrix[0]: return False
23+
row, col = 0, len(matrix[0]) - 1
24+
while row < len(matrix) and col >= 0:
25+
if matrix[row][col] > target: col -= 1
26+
elif matrix[row][col] < target: row += 1
27+
else: return True
28+
return False

0 commit comments

Comments
 (0)