From 7efd213c6891d210c87728477bcb4ed3021f556e Mon Sep 17 00:00:00 2001 From: Kurt-Yu Date: Wed, 23 Jan 2019 21:15:14 +1100 Subject: [PATCH] added some python solutions --- README.md | 20 +++++++++++++---- .../isOneBitCharacter.py | 10 +++++++++ .../FindTheDuplicateNumber/findDuplicate.py | 13 +++++++++++ .../python/ImageSmoother/imageSmoother.py | 13 +++++++++++ .../python/K-diffPairsInAnArray/findPairs.py | 6 +++++ .../dominantIndex.py | 6 +++++ .../findLengthOfLCIS.py | 11 ++++++++++ .../maxDistToClosest.py | 16 ++++++++++++++ .../MaximumAverageSubarrayI/findMaxAverage.py | 22 +++++++++++++++++++ .../maximumProduct.py | 11 ++++++++++ .../minCostClimbingStairs.py | 5 +++++ .../Non-decreasingArray/checkPossibility.py | 10 +++++++++ .../largeGroupPositions.py | 13 +++++++++++ .../findUnsortedSubarray.py | 3 +++ .../SquaresOfSortedArray/sortedSquares.py | 2 ++ .../python/ThirdMaximumNumber/thirdMax.py | 14 ++++++++++++ .../ValidMountainArray/validMountainArray.py | 20 +++++++++++++++++ 17 files changed, 191 insertions(+), 4 deletions(-) create mode 100644 algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py create mode 100644 algorithms/python/FindTheDuplicateNumber/findDuplicate.py create mode 100644 algorithms/python/ImageSmoother/imageSmoother.py create mode 100644 algorithms/python/K-diffPairsInAnArray/findPairs.py create mode 100644 algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py create mode 100644 algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py create mode 100644 algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py create mode 100644 algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py create mode 100644 algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py create mode 100644 algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py create mode 100644 algorithms/python/Non-decreasingArray/checkPossibility.py create mode 100644 algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py create mode 100644 algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py create mode 100644 algorithms/python/SquaresOfSortedArray/sortedSquares.py create mode 100644 algorithms/python/ThirdMaximumNumber/thirdMax.py create mode 100644 algorithms/python/ValidMountainArray/validMountainArray.py diff --git a/README.md b/README.md index c854b72d5..02508445c 100644 --- a/README.md +++ b/README.md @@ -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| @@ -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| @@ -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| diff --git a/algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py b/algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py new file mode 100644 index 000000000..bcdfc7069 --- /dev/null +++ b/algorithms/python/1-bitAnd2-bitCharacters/isOneBitCharacter.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/FindTheDuplicateNumber/findDuplicate.py b/algorithms/python/FindTheDuplicateNumber/findDuplicate.py new file mode 100644 index 000000000..f682b4c76 --- /dev/null +++ b/algorithms/python/FindTheDuplicateNumber/findDuplicate.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/ImageSmoother/imageSmoother.py b/algorithms/python/ImageSmoother/imageSmoother.py new file mode 100644 index 000000000..f90828d7b --- /dev/null +++ b/algorithms/python/ImageSmoother/imageSmoother.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/K-diffPairsInAnArray/findPairs.py b/algorithms/python/K-diffPairsInAnArray/findPairs.py new file mode 100644 index 000000000..271a39668 --- /dev/null +++ b/algorithms/python/K-diffPairsInAnArray/findPairs.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py b/algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py new file mode 100644 index 000000000..676bea452 --- /dev/null +++ b/algorithms/python/LargestNumberAtLeastTwiceOfOthers/dominantIndex.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py b/algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py new file mode 100644 index 000000000..3588468a0 --- /dev/null +++ b/algorithms/python/LongestContinuousIncreasingSubsequence/findLengthOfLCIS.py @@ -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) \ No newline at end of file diff --git a/algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py b/algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py new file mode 100644 index 000000000..c72de387b --- /dev/null +++ b/algorithms/python/MaximizeDistanceToClosestPerson/maxDistToClosest.py @@ -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) \ No newline at end of file diff --git a/algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py b/algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py new file mode 100644 index 000000000..496a4facc --- /dev/null +++ b/algorithms/python/MaximumAverageSubarrayI/findMaxAverage.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py b/algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py new file mode 100644 index 000000000..ea36a256a --- /dev/null +++ b/algorithms/python/MaximumProductOfThreeNumbers/maximumProduct.py @@ -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]) \ No newline at end of file diff --git a/algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py b/algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py new file mode 100644 index 000000000..403946efc --- /dev/null +++ b/algorithms/python/MinCostClimbingStairs/minCostClimbingStairs.py @@ -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) \ No newline at end of file diff --git a/algorithms/python/Non-decreasingArray/checkPossibility.py b/algorithms/python/Non-decreasingArray/checkPossibility.py new file mode 100644 index 000000000..5c8f27e80 --- /dev/null +++ b/algorithms/python/Non-decreasingArray/checkPossibility.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py b/algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py new file mode 100644 index 000000000..616d19a49 --- /dev/null +++ b/algorithms/python/PositionsOfLargeGroups/largeGroupPositions.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py b/algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py new file mode 100644 index 000000000..631bc04a9 --- /dev/null +++ b/algorithms/python/ShortestUnsortedContinuousSubarray/findUnsortedSubarray.py @@ -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) \ No newline at end of file diff --git a/algorithms/python/SquaresOfSortedArray/sortedSquares.py b/algorithms/python/SquaresOfSortedArray/sortedSquares.py new file mode 100644 index 000000000..cbbe06ccf --- /dev/null +++ b/algorithms/python/SquaresOfSortedArray/sortedSquares.py @@ -0,0 +1,2 @@ +def sortedSquares(self, A): + return list(sorted([a ** 2 for a in A])) \ No newline at end of file diff --git a/algorithms/python/ThirdMaximumNumber/thirdMax.py b/algorithms/python/ThirdMaximumNumber/thirdMax.py new file mode 100644 index 000000000..36f46d90b --- /dev/null +++ b/algorithms/python/ThirdMaximumNumber/thirdMax.py @@ -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 \ No newline at end of file diff --git a/algorithms/python/ValidMountainArray/validMountainArray.py b/algorithms/python/ValidMountainArray/validMountainArray.py new file mode 100644 index 000000000..c40f5db3a --- /dev/null +++ b/algorithms/python/ValidMountainArray/validMountainArray.py @@ -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 \ No newline at end of file