Skip to content

Commit

Permalink
added some python solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
Kurt-Yu authored and haoel committed Jan 26, 2019
1 parent 72ac886 commit 7efd213
Show file tree
Hide file tree
Showing 17 changed files with 191 additions and 4 deletions.
20 changes: 16 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,43 @@ LeetCode

| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
|977|[Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Python](./algorithms/python/SquaresOfSortedArray/sortedSquares.py)|Easy|
|976|[Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle/) | [Python](./algorithms/python/LargestPerimeterTriangle/largestPerimeter.py)|Easy|
|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|
|969|[Pancake Sorting](https://leetcode.com/problems/pancake-sorting/) | [Python](./algorithms/python/PancakeSorting/pancakeSort.py)|Medium|
|958|[Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/) | [Python](./algorithms/python/CheckCompletenessOfABinaryTree/isCompleteTree.py)|Medium|
|951|[Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) | [Python](./algorithms/python/FlipEquivalentBinaryTrees/flipEquiv.py)|Medium|
|950|[Reveal Cards In Increasing Order](https://leetcode.com/problems/reveal-cards-in-increasing-order/) | [Python](./algorithms/python/RevealCardsInIncreasingOrder/deckRevealedIncreasing.py)|Medium|
|941|[Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/) | [Python](./algorithms/python/ValidMountainArray/validMountainArray.py)|Easy|
|859|[Buddy Strings](https://leetcode.com/problems/buddy-strings/description/) | [C++](./algorithms/cpp/buddyStrings/BuddyStrings.cpp)|Easy|
|858|[Mirror Reflection](https://leetcode.com/problems/mirror-reflection/description/) | [C++](./algorithms/cpp/mirrorReflection/MirrorReflection.cpp)|Medium|
|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|
844|[Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/description/) | [C++](./algorithms/cpp/backspaceStringCompare/BackspaceStringCompare.cpp)|Easy|
|849|[Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [Python](./algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py)|Easy|
|844|[Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/description/) | [C++](./algorithms/cpp/backspaceStringCompare/BackspaceStringCompare.cpp)|Easy|
|837|[Most Common Word](https://leetcode.com/problems/most-common-word/) | [C++](./algorithms/cpp/mostCommonWord/MostCommonWord.cpp)|Easy|
|830|[Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [Python](./algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py)|Easy|
|804|[Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [C++](./algorithms/cpp/uniqueMorseCodeWords/UniqueMorseCodeWords.cpp)|Easy|
|771|[Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description) | [C++](./algorithms/cpp/jewelsAndStones/JewelsAndStones.cpp)|Easy|
|747|[Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/) | [Python](./algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py)|Easy|
|746|[Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [Python](./algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py)|Easy|
|717|[1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [Python](./algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py)|Easy|
|687|[Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | [Python](./algorithms/python/LongestUnivaluePath/longestUnivaluePath.py)|Easy|
|684|[Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [Python](./algorithms/python/RedundantConnection/findRedundantConnection.py)|Medium|
|674|[Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Python](./algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py)|Easy|
|671|[Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](./algorithms/python/SecondMinimumNodeInABinaryTree/findSecondMinimumValue.py)|Easy|
|665|[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [Python](./algorithms/python/Non-decreasingArray/checkPossibility.py)|Easy|
|662|[Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) | [Python](./algorithms/python/MaximumWidthOfBinaryTree/widthOfBinaryTree.py)|Medium|
|661|[Image Smoother](https://leetcode.com/problems/image-smoother/) | [Python](./algorithms/python/ImageSmoother/imageSmoother.py)|Easy|
|655|[Print Binary Tree](https://leetcode.com/problems/print-binary-tree/) | [Python](./algorithms/python/PrintBinaryTree/printTree.py)|Medium|
|652|[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/) | [Python](./algorithms/python/FindDuplicateSubtrees/findDuplicateSubtrees.py)|Medium|
|643|[Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/description/) | [C++](./algorithms/cpp/maximumAverageSubarray/MaximumAverageSubarray.I.cpp)|Easy|
|643|[Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/description/) | [C++](./algorithms/cpp/maximumAverageSubarray/MaximumAverageSubarray.I.cpp), [Python](./algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py)|Easy|
|628|[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [Python](./algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py)|Easy|
|623|[Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/) | [Python](./algorithms/python/AddOneRowToTree/addOneRow.py)|Medium|
|572|[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) | [Python](./algorithms/python/SubtreeOfAnotherTree/isSubtree.py)|Easy|
|563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | [Python](./algorithms/python/BinaryTreeTilt/findTilt.py)|Easy|
|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [Python](./algorithms/python/DiameterOfBinaryTree/diameterOfBinaryTree.py)|Easy|
|538|[Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [Python](./algorithms/python/ConvertBSTtoGreaterTree/convertBST.py)|Easy|
|532|[K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) | [Python](./algorithms/python/K-diffPairsInAnArray/findPairs.py)|Easy|
|509|[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Python](./algorithms/python/FibonacciNumber/fib.py)|Easy|
|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp)|Medium|
|450|[DeleteNodeInABST](https://leetcode.com/problems/delete-node-in-a-bst/) | [Python](./algorithms/python/DeleteNodeInABST/deleteNode.py)|Medium|
Expand All @@ -41,7 +53,7 @@ LeetCode
|418|[SentenceScreenFitting](https://leetcode.com/problems/sentence-screen-fitting/) ♥ | [C++](./algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.cpp)|Easy|
|416|[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [C++](./algorithms/cpp/partitionEqualSubsetSum/PartitionEqualSubsetSum.cpp)|Medium|
|415|[Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./algorithms/cpp/addStrings/AddStrings.cpp)|Easy|
|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp)|Easy|
|414|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./algorithms/cpp/thirdMaximumNumber/ThirdMaximumNumber.cpp), [Python](./algorithms/python/ThirdMaximumNumber/thirdMax.py)|Easy|
|413|[Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./algorithms/cpp/arithmeticSlices/ArithmeticSlices.cpp)|Medium|
|412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./algorithms/cpp/fizzBuzz/FizzBuzz.cpp)|Easy|
|410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [C++](./algorithms/cpp/splitArrayLargestSum/SplitArrayLargestSum.cpp)|Hard|
Expand Down Expand Up @@ -117,7 +129,7 @@ LeetCode
|295|[Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | [C++](./algorithms/cpp/findMedianFromDataStream/FindMedianFromDataStream.cpp)|Hard|
|292|[Nim Game](https://leetcode.com/problems/nim-game/) | [C++](./algorithms/cpp/nimGame/nimGame.cpp)|Easy|
|290|[Word Pattern](https://leetcode.com/problems/word-pattern/) | [C++](./algorithms/cpp/wordPattern/WordPattern.cpp)|Easy|
|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | [C++](./algorithms/cpp/findTheDuplicateNumber/findTheDuplicateNumber.cpp)|Hard|
|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | [C++](./algorithms/cpp/findTheDuplicateNumber/findTheDuplicateNumber.cpp), [Python](./algorithms/python/FindTheDuplicateNumber/findDuplicate.py)|Hard|
|285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/) ♥ | [Java](./algorithms/java/src/inorderSuccessorInBST/inorderSuccessorInBST.java)|Medium|
|284|[Peeking Iterator](https://leetcode.com/problems/peeking-iterator/) | [C++](./algorithms/cpp/peekingIterator/PeekingIterator.cpp)|Medium|
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./algorithms/cpp/moveZeroes/moveZeroes.cpp)|Easy|
Expand Down
10 changes: 10 additions & 0 deletions algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def isOneBitCharacter(self, bits):
i = 0
while i < len(bits):
if bits[i] == 0:
i += 1
if i >= len(bits): return True
if bits[i] == 1:
i += 2
if i >= len(bits): return False
if i == len(bits) - 1: return True
13 changes: 13 additions & 0 deletions algorithms/python/FindTheDuplicateNumber/findDuplicate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# the same as linked list cycle problem
def findDuplicate(self, nums):
if len(nums) <= 1: return -1
slow, fast = nums[0], nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]

fast = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
13 changes: 13 additions & 0 deletions algorithms/python/ImageSmoother/imageSmoother.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def imageSmoother(self, M):
from copy import deepcopy

if not M or not M[0]: return [[]]
row, col = len(M), len(M[0])
res = deepcopy(M)
for x in range(row):
for y in range(col):
temp = [M[i][j] for i in [x - 1, x, x + 1] for j in [y - 1, y, y + 1] if \
0 <= i < row and 0 <= j < col]
res[x][y] = sum(temp) // len(temp)

return res
6 changes: 6 additions & 0 deletions algorithms/python/K-diffPairsInAnArray/findPairs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def findPairs(self, nums, k):
if k > 0:
return len(set(nums) & set(a + k for a in nums))
elif k == 0:
return sum(v > 1 for v in collections.Counter(nums).values())
return 0
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
def dominantIndex(self, nums):
i = nums.index(max(nums))
l = nums[i]
del nums[i]
if not nums: return 0
return i if l >= 2 * max(nums) else -1
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def findLengthOfLCIS(self, nums):
if not nums: return 0
res = 1
temp = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
temp += 1
else:
res = max(temp, res)
temp = 1
return max(temp, res)
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
def maxDistToClosest(self, seats):
first = seats.index(1)
last = 0
for i in range(len(seats) - 1, -1, -1):
if seats[i]:
last = i
break
res = 0
temp = 0
for i in range(first, last + 1):
if seats[i] == 1:
res = max(temp, res)
temp = 0
else:
temp += 1
return max(first, len(seats) - last - 1, (res + 1) // 2)
22 changes: 22 additions & 0 deletions algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Method 1: sliding window

def findMaxAverage(self, nums, k):
total = 0
temp = float('-inf')
for i, n in enumerate(nums):
total += n
if i >= k: total -= nums[i- k]
if i >= k - 1:
temp = max(temp, total)
return temp / k



# Method 2: prefix sum
def findMaxAverage(self, nums, k):
temp = [0]
for n in nums:
temp.append(temp[-1] + n)

res = max(temp[i + k] - temp[i] for i in range(len(nums) - k + 1))
return res / k
11 changes: 11 additions & 0 deletions algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# simply find the three largest and two smallest
# Method 1: sort
def maximumProduct(self, nums):
nums.sort()
return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3])

# Method 2: using heapq, O(n) time
def maximumProduct(self, nums):
import heapq
a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)
return max(a[0] * a[1] * a[2], a[0] * b[0] * b[1])
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def minCostClimbingStairs(self, cost):
temp = [0, cost[0]]
for i in range(1, len(cost)):
temp[0], temp[1] = temp[1], min(temp) + cost[i]
return min(temp)
10 changes: 10 additions & 0 deletions algorithms/python/Non-decreasingArray/checkPossibility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def checkPossibility(self, nums):
count = 0
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
count += 1
if i == 1 or nums[i - 2] <= nums[i]: nums[i - 1] = nums[i]
else: nums[i] = nums[i - 1]

if count >= 2: return False
return True
13 changes: 13 additions & 0 deletions algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def largeGroupPositions(self, S):
res = []
i = 0
while i < len(S) - 2:
if S[i] == S[i + 1] and S[i] == S[i + 2]:
val = S[i]
index = i
while i < len(S) and S[i] == val:
i += 1
res.append([index, i - 1])
i -= 1
i += 1
return res
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
def findUnsortedSubarray(self, nums):
same = [a == b for a, b in zip(nums, sorted(nums))]
return 0 if all(same) else len(nums) - same.index(False) - same[::-1].index(False)
2 changes: 2 additions & 0 deletions algorithms/python/SquaresOfSortedArray/sortedSquares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def sortedSquares(self, A):
return list(sorted([a ** 2 for a in A]))
14 changes: 14 additions & 0 deletions algorithms/python/ThirdMaximumNumber/thirdMax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def thirdMax(self, nums):
if len(set(nums)) < 3: return max(nums)
first = second = third = float('-inf')
for n in nums:
if n > first:
third = second
second = first
first = n
elif second < n < first:
third = second
second = n
elif third < n < second:
third = n
return third
20 changes: 20 additions & 0 deletions algorithms/python/ValidMountainArray/validMountainArray.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Method 1: using index find the max first, and then process

def validMountainArray(self, A):
if len(A) < 3: return False
index = A.index(max(A))
if index == 0 or index == len(A) -1: return False
for i in range(1, len(A)):
if i <= index:
if A[i] <= A[i - 1]: return False
else:
if A[i] >= A[i - 1]: return False
return True


# Method 2: one pass, using two pointers trace from the begining and end
def validMountainArray(self, A):
i, j = 0, len(A) - 1
while i < len(A) - 1 and A[i] < A[i + 1]: i += 1
while j > 0 and A[j - 1] > A[j]: j -= 1
return 0 < i == j < len(A) - 1

0 comments on commit 7efd213

Please sign in to comment.