├── .gitignore ├── Array ├── 118_Pascal'sTriangle.py ├── 119_Pascal'sTriangleII.py ├── 189_RotateArray.py ├── 228_SummaryRanges.py ├── 26_RemoveDuplicatesFromSortedArray.py ├── 27_RemoveElement.py ├── 283_MoveZeroes.py ├── 289_GameOfLife.py ├── 31_NextPermutation.py ├── 41_FirstMissingPositive.py ├── 54_SpiralMatrix.py ├── 56_MergeIntervals.py ├── 57_InsertInterval.py ├── 59_SpiralMatrixII.py ├── 670_MaximumSwap.py ├── 73_SetMatrixZeroes.py └── llb │ ├── 1. Two Sum.cpp │ ├── 118. Pascal's Triangle.cpp │ ├── 119. Pascal's Triangle II.cpp │ ├── 121. Best Time to Buy and vSell Stock.cpp │ ├── 167. Two Sum II - Input array is sorted.cpp │ ├── 169. Majority Element.cpp │ ├── 189. Rotate Array.cpp │ ├── 217. Contains Duplicate.cpp │ ├── 219. Contains Duplicate II.cpp │ ├── 26. Remove Duplicates from Sorted Array.cpp │ ├── 268. Missing Number.cpp │ ├── 27. Remove Element.cpp │ ├── 283. Move Zeroes.cpp │ ├── 35. Search Insert Position.cpp │ ├── 414. Third Maximum Number.cpp │ ├── 448. Find All Numbers Disappeared in an Array.cpp │ ├── 561. Array Partition I.cpp │ ├── 697. Degree of an Array.cpp │ ├── 717. 1-bit and 2-bit Characters.cpp │ └── 88. Merge Sorted Array.cpp ├── Backtracking ├── 17_LetterCombinationsOfAPhoneNumber.py ├── 216_CombinationSumIII.py ├── 22_GenerateParentheses.py ├── 39_CombinationSum.py ├── 46_Permutations.py ├── 47_PermutationsII.py ├── 78_Subsets.py └── 90_SubsetsII.py ├── BinarySearch ├── 153_FindMinimumInRotatedSortedArray.py ├── 154_FindMinimumInRotatedSortedArrayII.py ├── 162_FindPeakElement.py ├── 230_KthSmallestElementInABST.py ├── 278_FirstBadVersion.py ├── 33_SearchInRotatedSortedArray.py ├── 34_SearchForARange.py ├── 367_ValidPerfectSquare.py ├── 4_MedianOfTwoSortedArrays.go ├── 69_Sqrt(x).py ├── 74_SearchA2DMatrix.py └── 81_SearchInRotatedSortedArrayII.py ├── BitManipulation ├── 169_MajorityElement.py ├── 190_ReverseBits.py ├── 191_NumberOf1Bits.py └── 231_PowerOfTwo.py ├── BreadthFirstSearch └── 199_BinaryTreeRightSideView.py ├── DepthFirstSearch ├── 129_SumRootToLeafNumbers.py ├── 130_SurroundedRegions.py └── 200_NumberOfIslands.py ├── Design └── Design.py ├── DivideConquer └── DivideConquer.py ├── DynamicProgramming ├── 121_BestTimeToBuyAndSellStock.py ├── 122_BestTimeToBuyAndSellStockII.py ├── 198_HouseRobber.py ├── 213_HouseRobberII.py ├── 53_MaximumSubarray.py ├── 62_UniquePaths.py ├── 64_MinimumPathSum.py └── 70_ClimbingStairs.py ├── Graph └── Graph.py ├── Greedy └── Greedy.py ├── HashTable ├── 136_SingleNumber.py ├── 1_TwoSum.py ├── 1_TwoSum.rb ├── 217_ContainsDuplicate.py ├── 349_IntersectionOfTwoArrays.py ├── 3_LongestSubstringWithoutRepeatingCharacters.cpp └── llb │ ├── 136. Single Number.cpp │ ├── 202. Happy Number.cpp │ ├── 217. Contains Duplicate.cpp │ ├── 219. Contains Duplicate II.cpp │ ├── 349. Intersection of Two Arrays.cpp │ └── 94. Binary Tree Inorder Traversal.cpp ├── Heap └── Heap.py ├── LICENSE ├── LinkedList ├── 141. Linked List Cycle(判断链表是否有回路).cpp ├── 141_LinkedListCycle.py ├── 142. Linked List Cycle II(找含环链表入环口).cpp ├── 143. Reorder List(重排链表).cpp ├── 160. Intersection of Two Linked Lists(找两个交汇链表的交汇点).cpp ├── 160_IntersectionOfTwoLinkedLists.py ├── 19. Remove Nth Node From End of List(尾部第n个节点删除).cpp ├── 2. Add Two Numbers(链表数相加).cpp ├── 203. Remove Linked List Elements(删除值为val的所有节点).cpp ├── 203_RemoveLinkedListElements.py ├── 206. Reverse Linked List(翻转单链表).cpp ├── 206_ReverseLinkedList.py ├── 21. Merge Two Sorted Lists(合并有序链表).cpp ├── 21_MergeTwoSortedLists.py ├── 234_PalindromeLinkedList.py ├── 234_Palindrome_Linked_List(链表回文判断).cpp ├── 237_Delete Node in a Linked List(删除节点).cpp ├── 24_SwapNodesInPairs.py ├── 2_AddTwoNumbers.py ├── 2_AddTwoNumbers.py3 ├── 445. Add Two Numbers II(链表逆序相加).cpp ├── 61. Rotate List(旋转链表).cpp ├── 61_RotateList.py ├── 82_RemoveDuplicatesFromSortedListII.py ├── 83. Remove Duplicates from Sorted List(已排序列表去重).cpp ├── 83_RemoveDuplicatesFromSortedList.py └── 92_ReverseLinkedListII.py ├── Math └── Math.py ├── ProblemsList.md ├── README.md ├── Stack ├── 150_EvaluateReversePolishNotation.py ├── 155_MinStack.py ├── 20_ValidParentheses.py ├── 225_ImplementStackUsingQueues.py ├── 232_ImplementQueueUsingStacks.py ├── 316_RemoveDuplicateLetters.py ├── 341_FlattenNestedListIterator.py ├── 71_SimplifyPath.py └── llb │ ├── 103. Binary Tree Zigzag Level Order Traversal.cpp │ ├── 144. Binary Tree Preorder Traversal.cpp │ ├── 145. Binary Tree Postorder Traversal.cpp │ ├── 150. Evaluate Reverse Polish Notation.cpp │ ├── 155. Min Stack.cpp │ ├── 173. Binary Search Tree Iterator.cpp │ ├── 20. Valid Parentheses.cpp │ ├── 225. Implement Stack using Queues.cpp │ ├── 232. Implement Queue using Stacks.cpp │ ├── 331. Verify Preorder Serialization of a Binary Tree.cpp │ ├── 394. Decode String.cpp │ ├── 682. Baseball Game.cpp │ ├── 71. Simplify Path.cpp │ └── 94. Binary Tree Inorder Traversal.cpp ├── String ├── 14_LongestCommonPrefix.py ├── 151_ReverseWordsInAString.py ├── 165_CompareVersionNumbers.py ├── 28_ImplementstrStr.py ├── 344_ReverseString.py ├── 38_CountAndSay.py ├── 58_LengthOfLastWord.py ├── 67_AddBinary.py ├── 68_TextJustification.py ├── 6_ZigZagConversion.py └── 8_StringToInteger.py ├── Tree ├── 102_BinaryTreeLevelOrderTraversal.py ├── 104_MaximumDepthOfBinaryTree.py ├── 105_ConstructBinaryTreeFromPreorderAndInorderTraversal.py ├── 106_ConstructBinaryTreeFromInorderAndPostorderTraversal.py ├── 108_ConvertSortedArrayToBinarySearchTree.py ├── 109_ConvertSortedListToBinarySearchTree.py ├── 110_BalancedBinaryTree.py ├── 111_MinimumDepthOfBinaryTree.py ├── 112_PathSum.py ├── 113_PathSumII.py ├── 144_BinaryTreePreorderTraversal.py ├── 145_BinaryTreePostorderTraversal.py ├── 173_BinarySearchTreeIterator.py ├── 222_CountCompleteTreeNodes.py ├── 235_LowestCommonAncestorOfABinarySearchTree.py ├── 236_LowestCommonAncestorOfABinaryTree.py ├── 257_BinaryTreePaths.py ├── 94_BinaryTreeInorderTraversal.py ├── 98_ValidateBinarySearchTree.py ├── 99_RecoverBinarySearchTree.py └── llb │ ├── 100. Same Tree.cpp │ ├── 101. Symmetric Tree.cpp │ ├── 103. Binary Tree Zigzag Level Order Traversal.cpp │ ├── 104. Maximum Depth of Binary Tree.cpp │ ├── 107. Binary Tree Level Order Traversal II.cpp │ ├── 108. Convert Sorted Array to Binary Search Tree.cpp │ ├── 110. Balanced Binary Tree.cpp │ ├── 111. Minimum Depth of Binary Tree.cpp │ ├── 112. Path Sum.cpp │ ├── 113. Path Sum II.cpp │ ├── 144. Binary Tree Preorder Traversal.cpp │ ├── 145. Binary Tree Postorder Traversal.cpp │ ├── 173. Binary Search Tree Iterator.cpp │ ├── 226. Invert Binary Tree.cpp │ ├── 235. Lowest Common Ancestor of a Binary Search Tree.cpp │ ├── 404. Sum of Left Leaves.cpp │ ├── 437. Path Sum III.cpp │ ├── 449. Serialize and Deserialize BST.cpp │ ├── 450. Delete Node in a BST.cpp │ ├── 94. Binary Tree Inorder Traversal.cpp │ └── 98. Validate Binary Search Tree.cpp ├── TwoPointers └── 15_3Sum.py └── other └── 5_LongestPalindromicSubstring.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # pycharm project settings 104 | .idea/ 105 | 106 | # macos 107 | .DS_Store 108 | -------------------------------------------------------------------------------- /Array/118_Pascal'sTriangle.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/pascals-triangle/description. 6 | 题目描述: 7 | 8 | Given numRows, generate the first numRows of Pascal's triangle. 9 | 10 | For example, 11 | given numRows = 5, 12 | 13 | Return 14 | 15 | [ 16 | [1], 17 | [1,1], 18 | [1,2,1], 19 | [1,3,3,1], 20 | [1,4,6,4,1] 21 | ] 22 | 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def generate(self, numRows): 28 | """ 29 | :type numRows: int 30 | :rtype: List[List[int]] 31 | """ 32 | if numRows == 0: 33 | return [] 34 | elif numRows == 1: 35 | return [[1]] 36 | elif numRows == 2: 37 | return [[1], [1, 1]] 38 | 39 | triangles = [[1], [1, 1]] 40 | for row in range(2, numRows): 41 | triangle = [1] 42 | for column in range(1, row): 43 | triangle.append(triangles[row - 1][column - 1] + triangles[row - 1][column]) 44 | triangle.append(1) 45 | triangles.append(triangle) 46 | 47 | return triangles 48 | -------------------------------------------------------------------------------- /Array/119_Pascal'sTriangleII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/pascals-triangle-ii/description. 6 | 题目描述: 7 | 8 | Given an index k, return the kth row of the Pascal's triangle. 9 | 10 | For example, given k = 3, 11 | Return [1,3,3,1]. 12 | 13 | Note: 14 | Could you optimize your algorithm to use only O(k) extra space? 15 | 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def getRow(self, rowIndex): 21 | """ 22 | :type rowIndex: int 23 | :rtype: List[int] 24 | """ 25 | if rowIndex == 0: 26 | return [1] 27 | elif rowIndex == 1: 28 | return [1, 1] 29 | 30 | triangle = [1, 1] 31 | for row in range(2, rowIndex + 1): 32 | a = triangle[0] 33 | for column in range(1, row): 34 | b = triangle[column] 35 | triangle[column] = a + b 36 | a = b 37 | triangle.append(1) 38 | 39 | return triangle 40 | -------------------------------------------------------------------------------- /Array/228_SummaryRanges.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/summary-ranges/description. 6 | 题目描述: 7 | 8 | Given a sorted integer array without duplicates, return the summary of its ranges. 9 | 10 | Example 1: 11 | Input: [0,1,2,4,5,7] 12 | Output: ["0->2","4->5","7"] 13 | Example 2: 14 | Input: [0,2,3,4,6,8,9] 15 | Output: ["0","2->4","6","8->9"] 16 | Credits: 17 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def summaryRanges(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: List[str] 27 | """ 28 | if not nums: 29 | return [] 30 | 31 | summary_ranges = [] 32 | ll = len(nums) 33 | start = end = nums[0] 34 | for i in range(1, ll): 35 | if nums[i] == end + 1: 36 | end += 1 37 | else: 38 | if end != start: 39 | summary_ranges.append('{0}->{1}'.format(start, end)) 40 | else: 41 | summary_ranges.append('{0}'.format(start)) 42 | start = nums[i] 43 | end = nums[i] 44 | 45 | if end != start: 46 | summary_ranges.append('{0}->{1}'.format(start, end)) 47 | else: 48 | summary_ranges.append('{0}'.format(start)) 49 | 50 | return summary_ranges 51 | -------------------------------------------------------------------------------- /Array/26_RemoveDuplicatesFromSortedArray.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description. 6 | 题目描述: 7 | Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new 8 | length. 9 | 10 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) 11 | extra memory. 12 | 13 | Example: 14 | 15 | Given nums = [1,1,2], 16 | 17 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 18 | It doesn't matter what you leave beyond the new length. 19 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def removeDuplicates(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | if not nums: 30 | return 0 31 | 32 | cursor = 0 33 | for i in range(1, len(nums)): 34 | if nums[cursor] != nums[i]: 35 | cursor += 1 36 | nums[cursor] = nums[i] 37 | 38 | return cursor + 1 39 | -------------------------------------------------------------------------------- /Array/27_RemoveElement.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/remove-element/description. 6 | 题目描述: 7 | Given an array and a value, remove all instances of that value in-place and return the new length. 8 | 9 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) 10 | extra memory. 11 | 12 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 13 | 14 | Example: 15 | 16 | Given nums = [3,2,2,3], val = 3, 17 | 18 | Your function should return length = 2, with the first two elements of nums being 2. 19 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def removeElement(self, nums, val): 25 | """ 26 | :type nums: List[int] 27 | :type val: int 28 | :rtype: int 29 | """ 30 | if not nums: 31 | return 0 32 | 33 | total = len(nums) 34 | counter = 0 35 | cursor = 0 36 | for i in range(0, total): 37 | if val == nums[i]: 38 | counter += 1 39 | else: 40 | nums[cursor] = nums[i] 41 | cursor += 1 42 | 43 | return total - counter 44 | -------------------------------------------------------------------------------- /Array/283_MoveZeroes.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/move-zeroes/description. 6 | 题目描述: 7 | 8 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the 9 | non-zero elements. 10 | 11 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 12 | 13 | Note: 14 | You must do this in-place without making a copy of the array. 15 | Minimize the total number of operations. 16 | Credits: 17 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def moveZeroes(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: void Do not return anything, modify nums in-place instead. 27 | """ 28 | if not nums: 29 | return 30 | 31 | first_zero_pos = 0 32 | ll = len(nums) 33 | 34 | for i in range(1, ll): 35 | if nums[i] != 0 and nums[first_zero_pos] == 0: 36 | nums[first_zero_pos], nums[i] = nums[i], nums[first_zero_pos] 37 | first_zero_pos += 1 38 | elif nums[first_zero_pos] != 0: 39 | first_zero_pos = i 40 | -------------------------------------------------------------------------------- /Array/31_NextPermutation.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/next-permutation/description. 6 | 题目描述: 7 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 8 | 9 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending 10 | order). 11 | 12 | The replacement must be in-place, do not allocate extra memory. 13 | 14 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand 15 | column. 16 | 1,2,3 → 1,3,2 17 | 3,2,1 → 1,2,3 18 | 1,1,5 → 1,5,1 19 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def nextPermutation(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: void Do not return anything, modify nums in-place instead. 28 | """ 29 | ll = len(nums) 30 | target = ll - 1 31 | lex = True 32 | 33 | for i in range(ll - 2, -1, -1): 34 | if nums[target] <= nums[i]: 35 | target -= 1 36 | else: 37 | target = i 38 | lex = False 39 | break 40 | 41 | if not lex: 42 | for i in range(ll - 1, target, -1): 43 | if nums[target] < nums[i]: 44 | nums[target], nums[i] = nums[i], nums[target] 45 | nums[target + 1:] = sorted(nums[target + 1:]) 46 | break 47 | else: 48 | nums.reverse() 49 | -------------------------------------------------------------------------------- /Array/41_FirstMissingPositive.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/first-missing-positive/description. 6 | 题目描述: 7 | Given an unsorted integer array, find the first missing positive integer. 8 | 9 | For example, 10 | Given [1,2,0] return 3, 11 | and [3,4,-1,1] return 2. 12 | 13 | Your algorithm should run in O(n) time and uses constant space. 14 | 15 | """ 16 | 17 | 18 | class Solution(object): 19 | def firstMissingPositive(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: int 23 | """ 24 | ll = len(nums) 25 | 26 | for i in range(ll): 27 | while 0 < nums[i] <= ll and nums[i] != i + 1: 28 | idx = nums[i] - 1 29 | if nums[idx] == nums[i]: 30 | break 31 | nums[i], nums[idx] = nums[idx], nums[i] 32 | for i in range(ll): 33 | if nums[i] != i + 1: 34 | return i + 1 35 | 36 | return ll + 1 37 | -------------------------------------------------------------------------------- /Array/54_SpiralMatrix.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/spiral-matrix/description. 6 | 题目描述: 7 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 8 | 9 | For example, 10 | Given the following matrix: 11 | 12 | [ 13 | [ 1, 2, 3 ], 14 | [ 4, 5, 6 ], 15 | [ 7, 8, 9 ] 16 | ] 17 | You should return [1,2,3,6,9,8,7,4,5]. 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def spiralOrder(self, matrix): 24 | """ 25 | :type matrix: List[List[int]] 26 | :rtype: List[int] 27 | """ 28 | if not matrix: 29 | return [] 30 | 31 | spiral_array = [] 32 | rows = len(matrix) 33 | columns = len(matrix[0]) 34 | total = rows * columns 35 | directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] 36 | sx, sy = 0, 0 37 | dr = 0 38 | changes = 1 39 | circle = 0 40 | 41 | while total > 0: 42 | spiral_array.append(matrix[sx][sy]) 43 | if dr == 0 and sy == columns - circle - 1: 44 | dr = 1 45 | changes += 1 46 | elif dr == 1 and sx == rows - circle - 1: 47 | dr = 2 48 | changes += 1 49 | elif dr == 2 and sy == circle: 50 | dr = 3 51 | changes += 1 52 | elif dr == 3 and sx == circle: 53 | dr = 0 54 | changes += 1 55 | 56 | dx, dy = directions[dr] 57 | sx, sy = sx + dx, sy + dy 58 | if changes == 4: 59 | changes = 0 60 | circle += 1 61 | total -= 1 62 | 63 | return spiral_array 64 | -------------------------------------------------------------------------------- /Array/56_MergeIntervals.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/merge-intervals/description. 6 | 题目描述: 7 | 8 | Given a collection of intervals, merge all overlapping intervals. 9 | 10 | For example, 11 | Given [1,3],[2,6],[8,10],[15,18], 12 | return [1,6],[8,10],[15,18]. 13 | 14 | """ 15 | 16 | 17 | # Definition for an interval. 18 | class Interval(object): 19 | def __init__(self, s=0, e=0): 20 | self.start = s 21 | self.end = e 22 | 23 | def __repr__(self): 24 | return '(start: {0}, end: {1})'.format(self.start, self.end) 25 | 26 | 27 | class Solution(object): 28 | def merge(self, intervals): 29 | """ 30 | :type intervals: List[Interval] 31 | :rtype: List[Interval] 32 | """ 33 | if not intervals: 34 | return [] 35 | 36 | result = [] 37 | intervals.sort(key=lambda val: val.start) 38 | first_interval = intervals[0] 39 | start, end = first_interval.start, first_interval.end 40 | for interval in intervals: 41 | if interval.start <= end: 42 | end = max(end, interval.end) 43 | else: 44 | result.append(Interval(start, end)) 45 | start = interval.start 46 | end = interval.end 47 | 48 | result.append(Interval(start, end)) 49 | 50 | return result 51 | -------------------------------------------------------------------------------- /Array/57_InsertInterval.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/insert-interval/description. 6 | 题目描述: 7 | 8 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 9 | 10 | You may assume that the intervals were initially sorted according to their start times. 11 | 12 | Example 1: 13 | Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. 14 | 15 | Example 2: 16 | Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. 17 | 18 | This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. 19 | 20 | """ 21 | 22 | 23 | # Definition for an interval. 24 | class Interval(object): 25 | def __init__(self, s=0, e=0): 26 | self.start = s 27 | self.end = e 28 | 29 | def __repr__(self): 30 | return '(start: {0}, end: {1})'.format(self.start, self.end) 31 | 32 | 33 | class Solution(object): 34 | def insert(self, intervals, newInterval): 35 | """ 36 | :type intervals: List[Interval] 37 | :type newInterval: Interval 38 | :rtype: List[Interval] 39 | """ 40 | intervals.append(newInterval) 41 | 42 | result = [] 43 | intervals.sort(key=lambda val: val.start) 44 | first_interval = intervals[0] 45 | start, end = first_interval.start, first_interval.end 46 | for interval in intervals: 47 | if interval.start <= end: 48 | end = max(end, interval.end) 49 | else: 50 | result.append(Interval(start, end)) 51 | start = interval.start 52 | end = interval.end 53 | 54 | result.append(Interval(start, end)) 55 | 56 | return result 57 | -------------------------------------------------------------------------------- /Array/59_SpiralMatrixII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: 6 | 题目描述: 7 | 8 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 9 | 10 | For example, 11 | Given n = 3, 12 | 13 | You should return the following matrix: 14 | [ 15 | [ 1, 2, 3 ], 16 | [ 8, 9, 4 ], 17 | [ 7, 6, 5 ] 18 | ] 19 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def generateMatrix(self, n): 25 | """ 26 | :type n: int 27 | :rtype: List[List[int]] 28 | """ 29 | if n <= 0: 30 | return [] 31 | 32 | directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] 33 | sx, sy = 0, 0 34 | digit = 1 35 | dr = 0 36 | changes = 1 37 | circle = 0 38 | rows = columns = n 39 | total = rows * columns 40 | matrix = [{} for _ in range(rows)] 41 | 42 | while total > 0: 43 | matrix[sx][sy] = digit 44 | if dr == 0 and sy == columns - circle - 1: 45 | dr = 1 46 | changes += 1 47 | elif dr == 1 and sx == rows - circle - 1: 48 | dr = 2 49 | changes += 1 50 | elif dr == 2 and sy == circle: 51 | dr = 3 52 | changes += 1 53 | elif dr == 3 and sx == circle: 54 | dr = 0 55 | changes += 1 56 | 57 | dx, dy = directions[dr] 58 | sx, sy = sx + dx, sy + dy 59 | if changes == 4: 60 | circle += 1 61 | changes = 0 62 | 63 | total -= 1 64 | digit += 1 65 | 66 | for idx, sub_matrix in enumerate(matrix): 67 | matrix[idx] = [sub_matrix[key] for key in sorted(sub_matrix.keys())] 68 | 69 | return matrix 70 | -------------------------------------------------------------------------------- /Array/670_MaximumSwap.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/maximum-swap/description. 6 | 题目描述: 7 | 8 | Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the 9 | maximum valued number you could get. 10 | 11 | Example 1: 12 | Input: 2736 13 | Output: 7236 14 | Explanation: Swap the number 2 and the number 7. 15 | Example 2: 16 | Input: 9973 17 | Output: 9973 18 | Explanation: No swap. 19 | Note: 20 | The given number is in the range [0, 10^8]. 21 | 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def maximumSwap(self, num): 27 | """ 28 | :type num: int 29 | :rtype: int 30 | """ 31 | if num <= 0 or num > 100000000: 32 | return 0 33 | 34 | s = list(str(num)) 35 | ll = len(s) 36 | pre = s[:] 37 | 38 | for i in range(ll - 2, -1, -1): 39 | pre[i] = max(pre[i], pre[i + 1]) 40 | 41 | for i in range(ll): 42 | if s[i] < pre[i]: 43 | for j in range(ll - 1, i, -1): 44 | if s[j] == pre[i]: 45 | s[j], s[i] = s[i], s[j] 46 | return int(''.join(s)) 47 | 48 | return num 49 | -------------------------------------------------------------------------------- /Array/llb/1. Two Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | Example: 7 | Given nums = [2, 7, 11, 15], target = 9, 8 | 9 | Because nums[0] + nums[1] = 2 + 7 = 9, 10 | return [0, 1] 11 | */ 12 | 13 | //思路:求两个数字和的数字index 14 | 15 | 16 | class Solution { 17 | public: 18 | vector twoSum(vector& nums, int target) { 19 | vector resultVec; 20 | for(int i=0; i> generate(int numRows) { 24 | //思路:每行两边的都是1,中间都是上一行的j和j-1之和 25 | // vector> resultVec(numRows); 26 | // for (int i=0; i> resultVec(numRows); 37 | for (int i=0; i tempVec(i+1); 39 | tempVec[0] = tempVec[i] = 1; 40 | for (int j=1; j getRow(int rowIndex) { 16 | vector vec(rowIndex+1); 17 | vec[0] = 1; //相当于赋初始值 18 | for (int i=0; i<=rowIndex; i++) { 19 | for (int j=i; j>0; j--) { //vec[0]永远不变 20 | vec[j] = vec[j] + vec[j-1]; 21 | } 22 | } 23 | return vec; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Array/llb/121. Best Time to Buy and vSell Stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Say you have an array for which the ith element is the price of a given stock on day i. 4 | 5 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 6 | 7 | Example 1: 8 | Input: [7, 1, 5, 3, 6, 4] 9 | Output: 5 10 | 11 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 12 | Example 2: 13 | Input: [7, 6, 4, 3, 1] 14 | Output: 0 15 | 16 | In this case, no transaction is done, i.e. max profit = 0. 17 | */ 18 | 19 | /*思路: 20 | 在目前最小的价格里,如果价格不是最小,那么就比较李屯,找出最大的 21 | */ 22 | 23 | class Solution { 24 | public: 25 | int maxProfit(vector& prices) { 26 | if (prices.size() == 0) { 27 | return 0; 28 | } 29 | 30 | int minPrice = prices[0]; //记录的最小的价格 31 | int maxProfit = 0; 32 | for (int i=0; i maxProfit) { 37 | maxProfit = prices[i]-minPrice; 38 | } 39 | } 40 | return maxProfit; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Array/llb/167. Two Sum II - Input array is sorted.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 4 | 5 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 6 | 7 | You may assume that each input would have exactly one solution and you may not use the same element twice. 8 | 9 | Input: numbers={2, 7, 11, 15}, target=9 10 | Output: index1=1, index2=2 11 | */ 12 | 13 | /* 14 | 思路:由于是排序数组,所以可以从两边开始标记,知道产生结果 15 | 注意:最后的index是第n个元素而非下标 16 | */ 17 | 18 | 19 | class Solution { 20 | public: 21 | vector twoSum(vector& numbers, int target) { 22 | //思路:由于是排序数组,所以从左右两边,用两个标记一次向中间聚头,直到产生结果 23 | int l=0, r = numbers.size()-1; 24 | while(l < r) { 25 | if (numbers[l] + numbers[r] > target) { 26 | r--; 27 | } 28 | else if (numbers[l] + numbers[r] < target) { 29 | l++; 30 | } 31 | else { 32 | vector resultVec; 33 | resultVec.push_back(++l); 34 | resultVec.push_back(++r); 35 | return resultVec; 36 | } 37 | } 38 | 39 | return vector(0); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Array/llb/169. Majority Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 4 | 5 | You may assume that the array is non-empty and the majority element always exist in the array. 6 | 7 | Credits: 8 | Special thanks to @ts for adding this problem and creating all test cases. 9 | */ 10 | 11 | 12 | 13 | 14 | class Solution { 15 | public: 16 | int majorityElement(vector& nums) { 17 | int majorityIndex = 0; 18 | int count = 1; //初始化为第一个 19 | for (int i=1; i& nums, int k) { 25 | //思路:利用数组翻转,先各自翻转两段,再翻转总长 26 | if (nums.size() == 0) { 27 | return; 28 | } 29 | 30 | int len = nums.size(); 31 | k = k%len; 32 | reverse(nums, 0, len-k-1); 33 | reverse(nums, len-k, len-1); 34 | reverse(nums, 0, len-1); 35 | } 36 | 37 | void reverse(vector& nums, int begin, int end) { 38 | while(begin < end) { 39 | int temp = nums[begin]; 40 | nums[begin] = nums[end]; 41 | nums[end] = temp; 42 | begin++; 43 | end--; 44 | } 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Array/llb/217. Contains Duplicate.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array of integers, find if the array contains any duplicates. 4 | Your function should return true if any value appears at least twice in the array, 5 | and it should return false if every element is distinct. 6 | */ 7 | 8 | /* 9 | 思路: 10 | 1.思路一:双重循环,逐个找出是否有相等的元素 11 | 2.思路二:先排序,然后对比每个元素和它的下个元素 12 | */ 13 | 14 | 15 | 方法一实现: 16 | class Solution { 17 | public: 18 | bool containsDuplicate(vector& nums) { 19 | for (int i=0; i& nums) { 35 | if (nums.size() == 0) { 36 | return false; 37 | } 38 | sort(nums.begin(), nums.end()); 39 | for (int i=0; i& nums, int k) { 16 | map myMap; 17 | for (int i=0; i& nums) { 24 | if (nums.size() == 0) { 25 | return 0; 26 | } 27 | 28 | int index = 1; 29 | for(int i=1; i& nums) { 30 | // sort(nums.begin(), nums.end()); 31 | // for(int i=0; i<=nums.size(); i++) 32 | // { 33 | // if (nums[i] != i) { 34 | // return i; 35 | // } 36 | // } 37 | // return 0; 38 | 39 | 40 | //思路二 41 | int len = nums.size(); 42 | int sum = len*(len+1)/2; 43 | for (int num : nums) { 44 | sum -= num; 45 | } 46 | return sum; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Array/llb/27. Remove Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array and a value, remove all instances of that value in-place and return the new length. 4 | 5 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 6 | 7 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 8 | 9 | Example: 10 | 11 | Given nums = [3,2,2,3], val = 3, 12 | 13 | Your function should return length = 2, with the first two elements of nums being 2. 14 | */ 15 | 16 | 17 | /* 18 | 思路:和问题26和相似,这个是去掉某个值的元素,然后计算长度。 19 | */ 20 | 21 | 22 | class Solution { 23 | public: 24 | int removeElement(vector& nums, int val) { 25 | if (nums.size() == 0) { 26 | return 0; 27 | } 28 | 29 | int len = 0; 30 | for(int i=0; i< nums.size(); i++) { 31 | if (nums[i] != val) { 32 | nums[len] = nums[i]; 33 | len++; 34 | } 35 | } 36 | 37 | return len; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Array/llb/283. Move Zeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 4 | 5 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 6 | 7 | Note: 8 | You must do this in-place without making a copy of the array. 9 | Minimize the total number of operations. 10 | Credits: 11 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 12 | */ 13 | 14 | /* 15 | 思路:可以放置一个记录非零的下标值,然后依次判断增长,最后它所在的位置就是非0数字的结尾 16 | */ 17 | 18 | class Solution { 19 | public: 20 | void moveZeroes(vector& nums) { 21 | //放置一个非零的指针 22 | int index = 0; 23 | for (int i=0; i& nums, int target) { 34 | 35 | int length = nums.size(); 36 | if (length == 0) { 37 | return 0; 38 | } 39 | if (target > nums[length-1]) { 40 | return length; 41 | } 42 | 43 | int insertIndex = 0; 44 | for (int i=0; i nums[i-1]) { 49 | insertIndex = i; 50 | break; 51 | } 52 | } 53 | } 54 | 55 | return insertIndex; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Array/llb/414. Third Maximum Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). 4 | 5 | Example 1: 6 | Input: [3, 2, 1] 7 | 8 | Output: 1 9 | 10 | Explanation: The third maximum is 1. 11 | Example 2: 12 | Input: [1, 2] 13 | 14 | Output: 2 15 | 16 | Explanation: The third maximum does not exist, so the maximum (2) is returned instead. 17 | Example 3: 18 | Input: [2, 2, 3, 1] 19 | 20 | Output: 1 21 | 22 | Explanation: Note that the third maximum here means the third maximum distinct number. 23 | Both numbers with value 2 are both considered as second maximum. 24 | */ 25 | 26 | 27 | /*思路:先排序,然后按照从尾部开始倒着寻找第三个,如果最后没有第三个大,那么就返回最大的*/ 28 | 29 | class Solution { 30 | public: 31 | int thirdMax(vector& nums) { 32 | //思路返回第三个大的数 33 | sort(nums.begin(), nums.end()); 34 | int len = nums.size(); 35 | int temp = nums[len-1]; 36 | int numKind = 1; 37 | for (int i=len-1; i>=0; i--) { 38 | if (nums[i] < temp) { 39 | temp = nums[i]; 40 | numKind++; 41 | if (numKind == 3) { 42 | break; 43 | } 44 | } 45 | } 46 | 47 | if (numKind < 3) { 48 | return nums[len-1]; //小于3时返回最大的 49 | } 50 | return temp; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /Array/llb/448. Find All Numbers Disappeared in an Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 4 | 5 | Find all the elements of [1, n] inclusive that do not appear in this array. 6 | 7 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 8 | 9 | Example: 10 | 11 | Input: 12 | [4,3,2,7,8,2,3,1] 13 | 14 | Output: 15 | [5,6] 16 | */ 17 | 18 | /*先把数字交换到该在的位置,然后数字不符合的再帅选出来,下标+1就是缺失的*/ 19 | 20 | 21 | class Solution { 22 | public: 23 | vector findDisappearedNumbers(vector& nums) { 24 | vector vec; 25 | 26 | //把他们交换到该交换的位置 27 | // for (int i=0; i& nums) { 24 | sort(nums.begin(), nums.end()); 25 | int sum = 0; 26 | for(int i=0; i& bits) { 24 | //思路:其实就是组合能组成10、11、0,不能组成01、00这样的,然后判断最后最后剩余的 25 | int i = 0; 26 | while (i < bits.size()-1){ 27 | if (bits[i] == 1){ 28 | i += 2; 29 | }else{ 30 | i++; 31 | } 32 | } 33 | return i == bits.size()-1; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Array/llb/88. Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 4 | 5 | Note: 6 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 7 | The number of elements initialized in nums1 and nums2 are m and n respectively. 8 | */ 9 | 10 | /*思路: 11 | 一:利用栈,然后排序 12 | 二:从尾部开始给排序 13 | */ 14 | 15 | class Solution { 16 | public: 17 | void merge(vector& nums1, int m, vector& nums2, int n) { 18 | /*思路一:利用栈*/ 19 | for (int i=0; i& nums1, int m, vector& nums2, int n) { 30 | //利用数组的index 31 | m--; 32 | n--; 33 | int index = m+n+1; //新的index 34 | while (m >= 0 || n >= 0) { 35 | if (m < 0) { 36 | nums1[index--] = nums2[n--]; //从尾部处理,m没了就直接复制num2中的 37 | } 38 | else if (n < 0) { 39 | nums1[index--] = nums1[m--]; 40 | } 41 | else { 42 | if (nums1[m] > nums2[n]) { 43 | nums1[index--] = nums1[m--]; 44 | } 45 | else { 46 | nums1[index--] = nums2[n--]; 47 | } 48 | } 49 | } 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Backtracking/17_LetterCombinationsOfAPhoneNumber.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/letter-combinations-of-a-phone-number/description. 6 | 题目描述: 7 | 8 | Given a digit string, return all possible letter combinations that the number could represent. 9 | 10 | A mapping of digit to letters (just like on the telephone buttons) is given below. 11 | 12 | Input:Digit string "23" 13 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 14 | Note: 15 | Although the above answer is in lexicographical order, your answer could be in any order you want. 16 | 17 | """ 18 | 19 | 20 | class Solution(object): 21 | def letterCombinations(self, digits): 22 | """ 23 | :type digits: str 24 | :rtype: List[str] 25 | """ 26 | if not digits: 27 | return [] 28 | 29 | dtm = {'0': '', '1': '', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', 30 | '9': 'wxyz'} 31 | ans = [] 32 | self.backtrack(digits, dtm, 0, '', ans) 33 | 34 | return ans 35 | 36 | def backtrack(self, digits, dtm, idx, s, ans): 37 | if len(s) == len(digits): 38 | ans.append(s) 39 | else: 40 | for i in range(idx, len(digits)): 41 | for c in dtm[digits[i]]: 42 | self.backtrack(digits, dtm, i + 1, s + c, ans) 43 | -------------------------------------------------------------------------------- /Backtracking/216_CombinationSumIII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/combination-sum-iii/description. 6 | 题目描述: 7 | 8 | Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be 9 | used and each combination should be a unique set of numbers. 10 | 11 | 12 | Example 1: 13 | 14 | Input: k = 3, n = 7 15 | 16 | Output: 17 | 18 | [[1,2,4]] 19 | 20 | Example 2: 21 | 22 | Input: k = 3, n = 9 23 | 24 | Output: 25 | 26 | [[1,2,6], [1,3,5], [2,3,4]] 27 | Credits: 28 | Special thanks to @mithmatt for adding this problem and creating all test cases. 29 | 30 | """ 31 | 32 | 33 | class Solution(object): 34 | def combinationSum3(self, k, n): 35 | """ 36 | :type k: int 37 | :type n: int 38 | :rtype: List[List[int]] 39 | """ 40 | if n < k: 41 | return [] 42 | 43 | ans = [] 44 | sub = [] 45 | self.backtrace(k, n, 1, sub, ans) 46 | 47 | return ans 48 | 49 | def backtrace(self, k, n, idx, sub, ans): 50 | if n < 0 or len(sub) > k: 51 | return 52 | elif n == 0 and len(sub) == k: 53 | ans.append(sub[:]) 54 | else: 55 | for i in range(idx, 10): 56 | sub.append(i) 57 | self.backtrace(k, n - i, i + 1, sub, ans) 58 | sub.pop() 59 | -------------------------------------------------------------------------------- /Backtracking/22_GenerateParentheses.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/generate-parentheses/description. 6 | 题目描述: 7 | 8 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 9 | 10 | For example, given n = 3, a solution set is: 11 | 12 | [ 13 | "((()))", 14 | "(()())", 15 | "(())()", 16 | "()(())", 17 | "()()()" 18 | ] 19 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def generateParenthesis(self, n): 25 | """ 26 | :type n: int 27 | :rtype: List[str] 28 | """ 29 | if n < 0: 30 | return [] 31 | elif n == 0: 32 | return [''] 33 | 34 | ans = [] 35 | self.backtrack(n, 1, 0, '(', ans) 36 | 37 | return ans 38 | 39 | def backtrack(self, n, lc, rc, cur, ans): 40 | # 保证每个状态下, 左括号出现次数不低于右括号 41 | if lc < rc or max(lc, rc) > n: 42 | return 43 | elif lc == n and rc == n: 44 | ans.append(cur) 45 | else: 46 | self.backtrack(n, lc + 1, rc, cur + '(', ans) 47 | self.backtrack(n, lc, rc + 1, cur + ')', ans) 48 | -------------------------------------------------------------------------------- /Backtracking/39_CombinationSum.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/combination-sum/description. 6 | 题目描述: 7 | 8 | Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in 9 | C where the candidate numbers sums to T. 10 | 11 | The same repeated number may be chosen from C unlimited number of times. 12 | 13 | Note: 14 | All numbers (including target) will be positive integers. 15 | The solution set must not contain duplicate combinations. 16 | For example, given candidate set [2, 3, 6, 7] and target 7, 17 | A solution set is: 18 | [ 19 | [7], 20 | [2, 2, 3] 21 | ] 22 | 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def combinationSum(self, candidates, target): 28 | """ 29 | :type candidates: List[int] 30 | :type target: int 31 | :rtype: List[List[int]] 32 | """ 33 | if not candidates: 34 | return [] 35 | 36 | ans = [] 37 | sub = [] 38 | ll = len(candidates) 39 | # 排序, 避免重复搜索 40 | candidates.sort() 41 | self.backtrack(candidates, target, sub, ans, ll, 0) 42 | 43 | return ans 44 | 45 | def backtrack(self, candidates, target, sub, ans, length, idx): 46 | if target < 0: 47 | return 48 | elif target == 0: 49 | ans.append(sub[:]) 50 | else: 51 | # 只搜索当前和之后的数 52 | for i in range(idx, length): 53 | sub.append(candidates[i]) 54 | self.backtrack(candidates, target - candidates[i], sub, ans, length, i) 55 | sub.pop() 56 | -------------------------------------------------------------------------------- /Backtracking/46_Permutations.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/permutations/description. 6 | 题目描述: 7 | 8 | Given a collection of distinct numbers, return all possible permutations. 9 | 10 | For example, 11 | [1,2,3] have the following permutations: 12 | [ 13 | [1,2,3], 14 | [1,3,2], 15 | [2,1,3], 16 | [2,3,1], 17 | [3,1,2], 18 | [3,2,1] 19 | ] 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def permuteUnique(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: List[List[int]] 29 | """ 30 | if not nums: 31 | return [] 32 | 33 | ans = [] 34 | sub = [] 35 | visited = [0 for _ in range(len(nums))] 36 | self.backtrace(nums, visited, sub, ans) 37 | 38 | return ans 39 | 40 | def backtrace(self, nums, visited, sub, ans): 41 | if len(sub) == len(nums): 42 | ans.append(sub[:]) 43 | else: 44 | for i in range(len(nums)): 45 | if not visited[i]: 46 | visited[i] = 1 47 | sub.append(nums[i]) 48 | self.backtrace(nums, visited, sub, ans) 49 | sub.pop() 50 | visited[i] = 0 51 | -------------------------------------------------------------------------------- /Backtracking/47_PermutationsII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/permutations-ii/description. 6 | 题目描述: 7 | 8 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 9 | 10 | For example, 11 | [1,1,2] have the following unique permutations: 12 | [ 13 | [1,1,2], 14 | [1,2,1], 15 | [2,1,1] 16 | ] 17 | 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def permuteUnique(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: List[List[int]] 26 | """ 27 | if not nums: 28 | return [] 29 | 30 | ans = [] 31 | sub = [] 32 | visited = [0 for _ in range(len(nums))] 33 | nums.sort() 34 | self.backtrace(nums, visited, sub, ans) 35 | 36 | return ans 37 | 38 | def backtrace(self, nums, visited, sub, ans): 39 | if len(sub) == len(nums): 40 | ans.append(sub[:]) 41 | else: 42 | for i in range(len(nums)): 43 | if not visited[i]: 44 | # 前面有重复元素未使用 45 | if i > 0 and nums[i] == nums[i - 1] and not visited[i - 1]: 46 | continue 47 | visited[i] = 1 48 | sub.append(nums[i]) 49 | self.backtrace(nums, visited, sub, ans) 50 | sub.pop() 51 | visited[i] = 0 52 | -------------------------------------------------------------------------------- /Backtracking/78_Subsets.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/subsets/description. 6 | 题目描述: 7 | 8 | Given a set of distinct integers, nums, return all possible subsets (the power set). 9 | 10 | Note: The solution set must not contain duplicate subsets. 11 | 12 | For example, 13 | If nums = [1,2,3], a solution is: 14 | 15 | [ 16 | [3], 17 | [1], 18 | [2], 19 | [1,2,3], 20 | [1,3], 21 | [2,3], 22 | [1,2], 23 | [] 24 | ] 25 | 26 | """ 27 | 28 | 29 | class Solution(object): 30 | def subsets(self, nums): 31 | """ 32 | :type nums: List[int] 33 | :rtype: List[List[int]] 34 | """ 35 | if not nums: 36 | return [] 37 | 38 | ans = [] 39 | sub = [] 40 | self.backtrace(nums, 0, sub, ans) 41 | 42 | return ans 43 | 44 | def backtrace(self, nums, idx, sub, ans): 45 | ans.append(sub[:]) 46 | for i in range(idx, len(nums)): 47 | sub.append(nums[i]) 48 | self.backtrace(nums, i + 1, sub, ans) 49 | sub.pop() 50 | -------------------------------------------------------------------------------- /Backtracking/90_SubsetsII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/subsets-ii/description. 6 | 题目描述: 7 | 8 | Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 9 | 10 | Note: The solution set must not contain duplicate subsets. 11 | 12 | For example, 13 | If nums = [1,2,2], a solution is: 14 | 15 | [ 16 | [2], 17 | [1], 18 | [1,2,2], 19 | [2,2], 20 | [1,2], 21 | [] 22 | ] 23 | 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def subsetsWithDup(self, nums): 29 | """ 30 | :type nums: List[int] 31 | :rtype: List[List[int]] 32 | """ 33 | if not nums: 34 | return [] 35 | 36 | ans = [] 37 | sub = [] 38 | visited = [0 for _ in range(len(nums))] 39 | nums.sort() 40 | self.backtrace(nums, 0, visited, sub, ans) 41 | 42 | return ans 43 | 44 | def backtrace(self, nums, idx, visited, sub, ans): 45 | ans.append(sub[:]) 46 | for i in range(idx, len(nums)): 47 | # 前面有重复元素未使用 48 | if i > 0 and nums[i] == nums[i - 1] and not visited[i - 1]: 49 | continue 50 | visited[i] = 1 51 | sub.append(nums[i]) 52 | self.backtrace(nums, i + 1, visited, sub, ans) 53 | sub.pop() 54 | visited[i] = 0 55 | -------------------------------------------------------------------------------- /BinarySearch/153_FindMinimumInRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description. 6 | 题目描述: 7 | 8 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 9 | 10 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 11 | 12 | Find the minimum element. 13 | 14 | You may assume no duplicate exists in the array. 15 | 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def findMin(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: int 24 | """ 25 | # return self.binary_search_recursive(nums, 0, len(nums) - 1) 26 | return self.binary_search_iterative(nums, 0, len(nums) - 1) 27 | 28 | def binary_search_recursive(self, nums, l, r): 29 | if l > r: 30 | return nums[r] 31 | 32 | mid = l + (r - l) // 2 33 | if nums[mid] < nums[r]: 34 | return min(nums[mid], self.binary_search_recursive(nums, l, mid - 1)) 35 | 36 | return min(nums[l], self.binary_search_recursive(nums, mid + 1, r)) 37 | 38 | def binary_search_iterative(self, nums, l, r): 39 | while l <= r: 40 | mid = l + (r - l) // 2 41 | if nums[mid] < nums[r]: 42 | r = mid 43 | else: 44 | l = mid + 1 45 | 46 | return nums[r] 47 | -------------------------------------------------------------------------------- /BinarySearch/154_FindMinimumInRotatedSortedArrayII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description. 6 | 题目描述: 7 | 8 | Follow up for "Find Minimum in Rotated Sorted Array": 9 | What if duplicates are allowed? 10 | 11 | Would this affect the run-time complexity? How and why? 12 | 13 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 14 | 15 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 16 | 17 | Find the minimum element. 18 | 19 | The array may contain duplicates. 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def findMin(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | left, right = 0, len(nums) - 1 31 | while left <= right: 32 | mid = left + (right - left) // 2 33 | if nums[mid] < nums[right]: 34 | right = mid 35 | elif nums[mid] > nums[right]: 36 | left = mid + 1 37 | else: 38 | right -= 1 39 | 40 | return nums[right + 1] 41 | -------------------------------------------------------------------------------- /BinarySearch/162_FindPeakElement.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/find-peak-element/description. 6 | 题目描述: 7 | 8 | A peak element is an element that is greater than its neighbors. 9 | 10 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 11 | 12 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 13 | 14 | You may imagine that num[-1] = num[n] = -∞. 15 | 16 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 17 | 18 | click to show spoilers. 19 | 20 | Note: 21 | Your solution should be in logarithmic complexity. 22 | 23 | Credits: 24 | Special thanks to @ts for adding this problem and creating all test cases. 25 | 26 | """ 27 | 28 | 29 | class Solution(object): 30 | def findPeakElement(self, nums): 31 | """ 32 | :type nums: List[int] 33 | :rtype: int 34 | """ 35 | left, right = 0, len(nums) - 1 36 | # 局部峰值落在哪个半区 37 | while left < right: 38 | mid = left + (right - left) // 2 39 | if nums[mid] < nums[mid + 1]: 40 | left = mid + 1 41 | else: 42 | right = mid 43 | 44 | return right 45 | -------------------------------------------------------------------------------- /BinarySearch/278_FirstBadVersion.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/first-bad-version/description. 6 | 题目描述: 7 | 8 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version 9 | of your product fails the quality check. Since each version is developed based on the previous version, all the 10 | versions after a bad version are also bad. 11 | 12 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the 13 | following ones to be bad. 14 | 15 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to 16 | find the first bad version. You should minimize the number of calls to the API. 17 | 18 | Credits: 19 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 20 | 21 | """ 22 | 23 | 24 | # The isBadVersion API is already defined for you. 25 | # @param version, an integer 26 | # @return a bool 27 | # def isBadVersion(version): 28 | 29 | class Solution(object): 30 | def firstBadVersion(self, n): 31 | """ 32 | :type n: int 33 | :rtype: int 34 | """ 35 | if n <= 1: 36 | return n 37 | 38 | left, right = 1, n 39 | while left <= right: 40 | mid = left + (right - left) // 2 41 | if isBadVersion(mid): 42 | right = mid - 1 43 | else: 44 | left = mid + 1 45 | 46 | return right + 1 47 | -------------------------------------------------------------------------------- /BinarySearch/33_SearchInRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/search-in-rotated-sorted-array/description. 6 | 题目描述: 7 | 8 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 9 | 10 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 11 | 12 | You are given a target value to search. If found in the array return its index, otherwise return -1. 13 | 14 | You may assume no duplicate exists in the array. 15 | 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def search(self, nums, target): 21 | """ 22 | :type nums: List[int] 23 | :type target: int 24 | :rtype: int 25 | """ 26 | if not nums: 27 | return -1 28 | 29 | left = 0 30 | right = len(nums) - 1 31 | # 每次确定一半有序 32 | while left <= right: 33 | mid = left + (right - left) // 2 34 | if nums[mid] == target: 35 | return mid 36 | if nums[mid] < nums[right]: 37 | if nums[mid] < target <= nums[right]: 38 | left = mid + 1 39 | else: 40 | right = mid - 1 41 | else: 42 | if nums[left] <= target < nums[mid]: 43 | right = mid - 1 44 | else: 45 | left = mid + 1 46 | 47 | return -1 48 | -------------------------------------------------------------------------------- /BinarySearch/34_SearchForARange.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/search-for-a-range/description. 6 | 题目描述: 7 | 8 | Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. 9 | 10 | Your algorithm's runtime complexity must be in the order of O(log n). 11 | 12 | If the target is not found in the array, return [-1, -1]. 13 | 14 | For example, 15 | Given [5, 7, 7, 8, 8, 10] and target value 8, 16 | return [3, 4]. 17 | 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def searchRange(self, nums, target): 23 | """ 24 | :type nums: List[int] 25 | :type target: int 26 | :rtype: List[int] 27 | """ 28 | if not nums: 29 | return [-1, -1] 30 | 31 | # 两次二分搜索 32 | return [self.searchLeftRange(nums, target), self.searchRightRange(nums, target)] 33 | 34 | def searchLeftRange(self, nums, target): 35 | left = 0 36 | right = len(nums) - 1 37 | while left <= right: 38 | mid = left + (right - left) // 2 39 | if nums[mid] == target: 40 | right = mid - 1 41 | elif nums[mid] < target: 42 | left = mid + 1 43 | else: 44 | right = mid - 1 45 | 46 | if left < len(nums) and nums[left] == target: 47 | return left 48 | 49 | return -1 50 | 51 | def searchRightRange(self, nums, target): 52 | left = 0 53 | right = len(nums) - 1 54 | while left <= right: 55 | mid = left + (right - left) // 2 56 | if nums[mid] == target: 57 | left = mid + 1 58 | elif nums[mid] < target: 59 | left = mid + 1 60 | else: 61 | right = mid - 1 62 | 63 | if right >= 0 and nums[right] == target: 64 | return right 65 | 66 | return -1 67 | -------------------------------------------------------------------------------- /BinarySearch/367_ValidPerfectSquare.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/valid-perfect-square/description. 6 | 题目描述: 7 | 8 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 9 | 10 | Note: Do not use any built-in library function such as sqrt. 11 | 12 | Example 1: 13 | 14 | Input: 16 15 | Returns: True 16 | Example 2: 17 | 18 | Input: 14 19 | Returns: False 20 | Credits: 21 | Special thanks to @elmirap for adding this problem and creating all test cases. 22 | 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def isPerfectSquare(self, num): 28 | """ 29 | :type num: int 30 | :rtype: bool 31 | """ 32 | if num <= 1: 33 | return True 34 | 35 | left = 0 36 | right = num // 2 37 | while left <= right: 38 | mid = left + (right - left) // 2 39 | p = mid * mid 40 | if p == num: 41 | return True 42 | elif p < num: 43 | left = mid + 1 44 | else: 45 | right = mid - 1 46 | 47 | return False 48 | -------------------------------------------------------------------------------- /BinarySearch/69_Sqrt(x).py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/sqrtx/description. 6 | 题目描述: 7 | 8 | Implement int sqrt(int x). 9 | 10 | Compute and return the square root of x. 11 | 12 | x is guaranteed to be a non-negative integer. 13 | 14 | 15 | Example 1: 16 | 17 | Input: 4 18 | Output: 2 19 | Example 2: 20 | 21 | Input: 8 22 | Output: 2 23 | Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be 24 | truncated. 25 | 26 | """ 27 | 28 | 29 | class Solution(object): 30 | def mySqrt(self, x): 31 | """ 32 | :type x: int 33 | :rtype: int 34 | """ 35 | if x <= 1: 36 | return x 37 | 38 | left = 0 39 | right = x // 2 40 | while left <= right: 41 | mid = left + (right - left) // 2 42 | if mid * mid <= x: 43 | left = mid + 1 44 | else: 45 | right = mid - 1 46 | 47 | return right 48 | -------------------------------------------------------------------------------- /BinarySearch/74_SearchA2DMatrix.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/search-a-2d-matrix/description. 6 | 题目描述: 7 | 8 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 9 | 10 | Integers in each row are sorted from left to right. 11 | The first integer of each row is greater than the last integer of the previous row. 12 | For example, 13 | 14 | Consider the following matrix: 15 | 16 | [ 17 | [1, 3, 5, 7], 18 | [10, 11, 16, 20], 19 | [23, 30, 34, 50] 20 | ] 21 | Given target = 3, return true. 22 | 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def searchMatrix(self, matrix, target): 28 | """ 29 | :type matrix: List[List[int]] 30 | :type target: int 31 | :rtype: bool 32 | """ 33 | if not any(matrix) or target < matrix[0][0] or target > matrix[-1][-1]: 34 | return False 35 | 36 | return self.searchMatrixColumns(matrix, self.searchMatrixRows(matrix, target), target) 37 | 38 | def searchMatrixRows(self, matrix, target): 39 | left = 0 40 | right = len(matrix) - 1 41 | while left <= right: 42 | mid = left + (right - left) // 2 43 | if matrix[mid][0] <= target: 44 | left = mid + 1 45 | else: 46 | right = mid - 1 47 | 48 | return right 49 | 50 | def searchMatrixColumns(self, matrix, row, target): 51 | left = 0 52 | right = len(matrix[row]) - 1 53 | while left <= right: 54 | mid = left + (right - left) // 2 55 | if matrix[row][mid] == target: 56 | return True 57 | elif matrix[row][mid] < target: 58 | left = mid + 1 59 | else: 60 | right = mid - 1 61 | 62 | return False 63 | -------------------------------------------------------------------------------- /BinarySearch/81_SearchInRotatedSortedArrayII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description. 6 | 题目描述: 7 | 8 | Follow up for "Search in Rotated Sorted Array": 9 | What if duplicates are allowed? 10 | 11 | Would this affect the run-time complexity? How and why? 12 | 13 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 14 | 15 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 16 | 17 | Write a function to determine if a given target is in the array. 18 | 19 | The array may contain duplicates. 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def search(self, nums, target): 26 | """ 27 | :type nums: List[int] 28 | :type target: int 29 | :rtype: bool 30 | """ 31 | if not nums: 32 | return False 33 | 34 | left, right = 0, len(nums) - 1 35 | # 核心: nums[mid] == nums[right] != target, 仅能排除right 36 | while left <= right: 37 | mid = left + (right - left) // 2 38 | if nums[mid] == target: 39 | return True 40 | if nums[mid] < nums[right]: 41 | if nums[mid] < target <= nums[right]: 42 | left = mid + 1 43 | else: 44 | right = mid - 1 45 | elif nums[mid] > nums[right]: 46 | if nums[left] <= target < nums[mid]: 47 | right = mid - 1 48 | else: 49 | left = mid + 1 50 | else: 51 | right -= 1 52 | 53 | return False 54 | -------------------------------------------------------------------------------- /BitManipulation/169_MajorityElement.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/majority-element/description. 6 | 题目描述: 7 | 8 | Given an array of size n, find the majority element. The majority element is the element that appears more than 9 | ⌊ n/2 ⌋ times. 10 | 11 | You may assume that the array is non-empty and the majority element always exist in the array. 12 | 13 | Credits: 14 | Special thanks to @ts for adding this problem and creating all test cases. 15 | 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def majorityElement(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: int 24 | """ 25 | ans = nums[0] 26 | cnt = 1 27 | 28 | for i in range(1, len(nums)): 29 | if cnt == 0: 30 | cnt += 1 31 | ans = nums[i] 32 | elif nums[i] == ans: 33 | cnt += 1 34 | else: 35 | cnt -= 1 36 | 37 | return ans 38 | -------------------------------------------------------------------------------- /BitManipulation/190_ReverseBits.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/reverse-bits/description. 6 | 题目描述: 7 | 8 | Reverse bits of a given 32 bits unsigned integer. 9 | 10 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 11 | (represented in binary as 00111001011110000010100101000000). 12 | 13 | Follow up: 14 | If this function is called many times, how would you optimize it? 15 | 16 | Related problem: Reverse Integer 17 | 18 | Credits: 19 | Special thanks to @ts for adding this problem and creating all test cases. 20 | 21 | """ 22 | 23 | 24 | class Solution: 25 | # @param n, an integer 26 | # @return an integer 27 | def reverseBits(self, n): 28 | res = 0 29 | for i in range(32): 30 | res = res << 1 | (n & 1) 31 | n >>= 1 32 | 33 | return res 34 | -------------------------------------------------------------------------------- /BitManipulation/191_NumberOf1Bits.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/number-of-1-bits/description. 6 | 题目描述: 7 | 8 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the 9 | Hamming weight). 10 | 11 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function 12 | should return 3. 13 | 14 | Credits: 15 | Special thanks to @ts for adding this problem and creating all test cases. 16 | 17 | """ 18 | 19 | 20 | class Solution(object): 21 | def hammingWeight(self, n): 22 | """ 23 | :type n: int 24 | :rtype: int 25 | """ 26 | ans = 0 27 | while n: 28 | n = n & (n - 1) 29 | ans += 1 30 | 31 | return ans 32 | -------------------------------------------------------------------------------- /BitManipulation/231_PowerOfTwo.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/power-of-two/description. 6 | 题目描述: 7 | 8 | Given an integer, write a function to determine if it is a power of two. 9 | 10 | Credits: 11 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 12 | 13 | """ 14 | 15 | 16 | class Solution(object): 17 | def isPowerOfTwo(self, n): 18 | """ 19 | :type n: int 20 | :rtype: bool 21 | """ 22 | if n == 0: 23 | return False 24 | 25 | return n & (n - 1) == 0 26 | -------------------------------------------------------------------------------- /BreadthFirstSearch/199_BinaryTreeRightSideView.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/binary-tree-right-side-view/description. 6 | 题目描述: 7 | 8 | Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see 9 | ordered from top to bottom. 10 | 11 | For example: 12 | Given the following binary tree, 13 | 1 <--- 14 | / \ 15 | 2 3 <--- 16 | \ \ 17 | 5 4 <--- 18 | You should return [1, 3, 4]. 19 | 20 | Credits: 21 | Special thanks to @amrsaqr for adding this problem and creating all test cases. 22 | 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | class TreeNode(object): 28 | def __init__(self, x): 29 | self.val = x 30 | self.left = None 31 | self.right = None 32 | 33 | 34 | class Solution(object): 35 | def rightSideView(self, root): 36 | """ 37 | :type root: TreeNode 38 | :rtype: List[int] 39 | """ 40 | if not root: 41 | return [] 42 | 43 | ans = [] 44 | self.bfs(root, ans) 45 | 46 | return ans 47 | 48 | def bfs(self, root, ans): 49 | queue = [] 50 | front = 0 51 | rear = 1 52 | 53 | queue.append(root) 54 | while front < rear: 55 | last = rear 56 | # 加入每层的最右节点 57 | ans.append(queue[last - 1].val) 58 | while front < last: 59 | root = queue[front] 60 | front += 1 61 | if root.left: 62 | queue.append(root.left) 63 | rear += 1 64 | if root.right: 65 | queue.append(root.right) 66 | rear += 1 67 | -------------------------------------------------------------------------------- /DepthFirstSearch/129_SumRootToLeafNumbers.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/sum-root-to-leaf-numbers/description. 6 | 题目描述: 7 | 8 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 9 | 10 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 11 | 12 | Find the total sum of all root-to-leaf numbers. 13 | 14 | For example, 15 | 16 | 1 17 | / \ 18 | 2 3 19 | The root-to-leaf path 1->2 represents the number 12. 20 | The root-to-leaf path 1->3 represents the number 13. 21 | 22 | Return the sum = 12 + 13 = 25. 23 | 24 | """ 25 | 26 | 27 | # Definition for a binary tree node. 28 | class TreeNode(object): 29 | def __init__(self, x): 30 | self.val = x 31 | self.left = None 32 | self.right = None 33 | 34 | 35 | class Solution(object): 36 | def sumNumbers(self, root): 37 | """ 38 | :type root: TreeNode 39 | :rtype: int 40 | """ 41 | return self.dfs(root, 0) 42 | 43 | def dfs(self, root, sub): 44 | if not root: 45 | return 0 46 | 47 | sub = 10 * sub + root.val 48 | if not root.left and not root.right: 49 | return sub 50 | 51 | return self.dfs(root.left, sub) + self.dfs(root.right, sub) 52 | -------------------------------------------------------------------------------- /DepthFirstSearch/130_SurroundedRegions.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/surrounded-regions/description. 6 | 题目描述: 7 | 8 | Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. 9 | 10 | A region is captured by flipping all 'O's into 'X's in that surrounded region. 11 | 12 | For example, 13 | X X X X 14 | X O O X 15 | X X O X 16 | X O X X 17 | After running your function, the board should be: 18 | 19 | X X X X 20 | X X X X 21 | X X X X 22 | X O X X 23 | 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def solve(self, board): 29 | """ 30 | :type board: List[List[str]] 31 | :rtype: void Do not return anything, modify board in-place instead. 32 | """ 33 | if not any(board): 34 | return 35 | 36 | rows, columns = len(board), len(board[0]) 37 | for i in range(rows): 38 | for j in range(columns): 39 | if i == 0 or i == rows - 1 or j == 0 or j == columns - 1 and board[i][j] == 'O': 40 | self.dfs(board, rows, columns, i, j) 41 | 42 | for i in range(rows): 43 | for j in range(columns): 44 | if board[i][j] == 'O': 45 | board[i][j] = 'X' 46 | elif board[i][j] == '$': 47 | board[i][j] = 'O' 48 | 49 | def dfs(self, board, rows, columns, i, j): 50 | if i < 0 or i >= rows or j < 0 or j >= columns or board[i][j] != 'O': 51 | return 52 | 53 | board[i][j] = '$' 54 | self.dfs(board, rows, columns, i - 1, j) 55 | self.dfs(board, rows, columns, i, j + 1) 56 | self.dfs(board, rows, columns, i + 1, j) 57 | self.dfs(board, rows, columns, i, j - 1) 58 | -------------------------------------------------------------------------------- /DepthFirstSearch/200_NumberOfIslands.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/number-of-islands/description. 6 | 题目描述: 7 | 8 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water 9 | and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid 10 | are all surrounded by water. 11 | 12 | Example 1: 13 | 14 | 11110 15 | 11010 16 | 11000 17 | 00000 18 | Answer: 1 19 | 20 | Example 2: 21 | 22 | 11000 23 | 11000 24 | 00100 25 | 00011 26 | Answer: 3 27 | 28 | Credits: 29 | Special thanks to @mithmatt for adding this problem and creating all test cases. 30 | 31 | """ 32 | 33 | 34 | class Solution(object): 35 | def numIslands(self, grid): 36 | """ 37 | :type grid: List[List[str]] 38 | :rtype: int 39 | """ 40 | if not grid or not grid[0]: 41 | return 0 42 | 43 | islands = 0 44 | rows, columns = len(grid), len(grid[0]) 45 | for i in range(rows): 46 | for j in range(columns): 47 | if self.dfs(grid, rows, columns, i, j): 48 | islands += 1 49 | 50 | return islands 51 | 52 | def dfs(self, grid, rows, columns, i, j): 53 | if i < 0 or i >= rows or j < 0 or j >= columns or grid[i][j] == '0': 54 | return 0 55 | 56 | grid[i][j] = '0' 57 | self.dfs(grid, rows, columns, i - 1, j) 58 | self.dfs(grid, rows, columns, i, j + 1) 59 | self.dfs(grid, rows, columns, i + 1, j) 60 | self.dfs(grid, rows, columns, i, j - 1) 61 | 62 | return 1 63 | -------------------------------------------------------------------------------- /Design/Design.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | -------------------------------------------------------------------------------- /DivideConquer/DivideConquer.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | -------------------------------------------------------------------------------- /DynamicProgramming/121_BestTimeToBuyAndSellStock.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description. 6 | 题目描述: 7 | 8 | Say you have an array for which the ith element is the price of a given stock on day i. 9 | 10 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), 11 | design an algorithm to find the maximum profit. 12 | 13 | Example 1: 14 | Input: [7, 1, 5, 3, 6, 4] 15 | Output: 5 16 | 17 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 18 | Example 2: 19 | Input: [7, 6, 4, 3, 1] 20 | Output: 0 21 | 22 | In this case, no transaction is done, i.e. max profit = 0. 23 | 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def maxProfit(self, prices): 29 | """ 30 | :type prices: List[int] 31 | :rtype: int 32 | """ 33 | if not prices: 34 | return 0 35 | 36 | return self.dynamic_max_profit(prices) 37 | 38 | # 动态规划 39 | # 搜索局部上升子序列, 保存当前最优解 40 | def dynamic_max_profit(self, prices): 41 | start = 0 42 | ans = 0 43 | for i in range(1, len(prices)): 44 | delta = prices[i] - prices[start] 45 | if delta > 0: 46 | ans = max(ans, delta) 47 | else: 48 | start = i 49 | 50 | return ans 51 | -------------------------------------------------------------------------------- /DynamicProgramming/122_BestTimeToBuyAndSellStockII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description. 6 | 题目描述: 7 | 8 | Say you have an array for which the ith element is the price of a given stock on day i. 9 | 10 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and 11 | sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time 12 | (ie, you must sell the stock before you buy again). 13 | 14 | """ 15 | 16 | 17 | class Solution(object): 18 | def maxProfit(self, prices): 19 | """ 20 | :type prices: List[int] 21 | :rtype: int 22 | """ 23 | if not prices: 24 | return 0 25 | 26 | return self.dynamic_max_profit(prices) 27 | 28 | # 动态规划: 29 | # 搜索所有的上升子序列, 求和 30 | def dynamic_max_profit(self, prices): 31 | ans = 0 32 | for i in range(1, len(prices)): 33 | if prices[i] > prices[i - 1]: 34 | ans += prices[i] - prices[i - 1] 35 | 36 | return ans 37 | -------------------------------------------------------------------------------- /DynamicProgramming/198_HouseRobber.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/house-robber/description. 6 | 题目描述: 7 | 8 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money 9 | stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system 10 | connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 11 | 12 | Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount 13 | of money you can rob tonight without alerting the police. 14 | 15 | Credits: 16 | Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding 17 | additional test cases. 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def rob(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: int 27 | """ 28 | if not nums: 29 | return 0 30 | elif len(nums) == 1: 31 | return nums[0] 32 | elif len(nums) == 2: 33 | return max(nums[0], nums[1]) 34 | 35 | return self.dynamic_rob(nums) 36 | 37 | def dynamic_rob(self, nums): 38 | # 递推公式: dp[i] = max(dp[i-1], dp[i-2] + nums[i]), i > 2 39 | # dp[i]仅与dp[i-1], dp[i-2]相关, 只需存储这两个状态即可. 40 | dp1 = nums[0] 41 | dp2 = max(nums[0], nums[1]) 42 | for i in range(2, len(nums)): 43 | dp1, dp2 = dp2, max(dp2, dp1 + nums[i]) 44 | 45 | return dp2 46 | -------------------------------------------------------------------------------- /DynamicProgramming/213_HouseRobberII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/house-robber-ii/description. 6 | 题目描述: 7 | 8 | Note: This is an extension of House Robber. 9 | 10 | After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will 11 | not get too much attention. This time, all houses at this place are arranged in a circle. That means the first 12 | house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those 13 | in the previous street. 14 | 15 | Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount 16 | of money you can rob tonight without alerting the police. 17 | 18 | Credits: 19 | Special thanks to @Freezen for adding this problem and creating all test cases. 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def rob(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | if not nums: 31 | return 0 32 | 33 | # 选/不选第一家, 取较大值 34 | return max(self.dynamic_rob(nums, 0), self.dynamic_rob(nums, 1)) 35 | 36 | def dynamic_rob(self, nums, choice): 37 | if len(nums) <= choice: 38 | return 0 39 | elif len(nums) <= 1 + choice: 40 | return nums[choice] 41 | 42 | dp1 = nums[choice] 43 | dp2 = max(nums[choice], nums[1 + choice]) 44 | for i in range(2 + choice, len(nums) - 1 + choice): 45 | dp1, dp2 = dp2, max(dp2, dp1 + nums[i]) 46 | 47 | return dp2 48 | -------------------------------------------------------------------------------- /DynamicProgramming/53_MaximumSubarray.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/maximum-subarray/description. 6 | 题目描述: 7 | 8 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 9 | 10 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 11 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 12 | 13 | click to show more practice. 14 | 15 | More practice: 16 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which 17 | is more subtle. 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def maxSubArray(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: int 27 | """ 28 | if not nums: 29 | return 0 30 | 31 | return self.dynamic_sub_array(nums) 32 | 33 | # 动态规划, O(n) 34 | def dynamic_sub_array(self, nums): 35 | ans = float('-inf') 36 | cur = 0 37 | for i in range(len(nums)): 38 | cur += nums[i] 39 | ans = max(ans, cur) 40 | if cur < 0: 41 | cur = 0 42 | 43 | return ans 44 | -------------------------------------------------------------------------------- /DynamicProgramming/62_UniquePaths.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/unique-paths/description. 6 | 题目描述: 7 | 8 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 9 | 10 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right 11 | corner of the grid (marked 'Finish' in the diagram below). 12 | 13 | How many possible unique paths are there? 14 | 15 | 16 | Above is a 3 x 7 grid. How many possible unique paths are there? 17 | 18 | Note: m and n will be at most 100. 19 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def uniquePaths(self, m, n): 25 | """ 26 | :type m: int 27 | :type n: int 28 | :rtype: int 29 | """ 30 | if m <= 1 or n <= 1: 31 | return 1 32 | 33 | return self.dynamic_unique_paths(m, n) 34 | 35 | # 常规dp 36 | def dynamic_unique_paths(self, m, n): 37 | dp = [[0 for _ in range(n)] for _ in range(m)] 38 | for i in range(m): 39 | dp[i][0] = 1 40 | for j in range(n): 41 | dp[0][j] = 1 42 | for i in range(1, m): 43 | for j in range(1, n): 44 | dp[i][j] = dp[i][j - 1] + dp[i - 1][j] 45 | 46 | return dp[m - 1][n - 1] 47 | -------------------------------------------------------------------------------- /DynamicProgramming/64_MinimumPathSum.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/minimum-path-sum/description. 6 | 题目描述: 7 | 8 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the 9 | sum of all numbers along its path. 10 | 11 | Note: You can only move either down or right at any point in time. 12 | 13 | Example 1: 14 | [[1,3,1], 15 | [1,5,1], 16 | [4,2,1]] 17 | Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. 18 | 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def minPathSum(self, grid): 24 | """ 25 | :type grid: List[List[int]] 26 | :rtype: int 27 | """ 28 | if not any(grid): 29 | return 0 30 | 31 | return self.dynamic_min_path_sum(grid) 32 | 33 | # 动态规划: 34 | # 递推公式: dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j], i>=1, j>=1 35 | def dynamic_min_path_sum(self, grid): 36 | rows = len(grid) 37 | columns = len(grid[0]) 38 | dp = [[0 for _ in range(columns)] for _ in range(rows)] 39 | dp[0][0] = grid[0][0] 40 | for i in range(1, rows): 41 | dp[i][0] = dp[i - 1][0] + grid[i][0] 42 | for j in range(1, columns): 43 | dp[0][j] = dp[0][j - 1] + grid[0][j] 44 | 45 | for i in range(1, rows): 46 | for j in range(1, columns): 47 | dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j] 48 | 49 | return dp[rows - 1][columns - 1] 50 | -------------------------------------------------------------------------------- /DynamicProgramming/70_ClimbingStairs.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/climbing-stairs/description. 6 | 题目描述: 7 | 8 | You are climbing a stair case. It takes n steps to reach to the top. 9 | 10 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 11 | 12 | Note: Given n will be a positive integer. 13 | 14 | 15 | Example 1: 16 | 17 | Input: 2 18 | Output: 2 19 | Explanation: There are two ways to climb to the top. 20 | 21 | 1. 1 step + 1 step 22 | 2. 2 steps 23 | Example 2: 24 | 25 | Input: 3 26 | Output: 3 27 | Explanation: There are three ways to climb to the top. 28 | 29 | 1. 1 step + 1 step + 1 step 30 | 2. 1 step + 2 steps 31 | 3. 2 steps + 1 step 32 | 33 | """ 34 | 35 | 36 | class Solution(object): 37 | def climbStairs(self, n): 38 | """ 39 | :type n: int 40 | :rtype: int 41 | """ 42 | if n <= 2: 43 | return n 44 | 45 | # return self.dynamic_climb_stairs(n) 46 | return self.dynamic_climb_stairs_optimization(n) 47 | 48 | def dynamic_climb_stairs(self, n): 49 | # 递推公式: dp[n] = dp[n-1]+dp[n-2], n > 2 50 | # 空间复杂度: O(n) 51 | dp = [0] * n 52 | dp[0] = 1 53 | dp[1] = 2 54 | for i in range(2, n): 55 | dp[i] = dp[i - 1] + dp[i - 2] 56 | 57 | return dp[n - 1] 58 | 59 | def dynamic_climb_stairs_optimization(self, n): 60 | # 优化: dp[n]仅与dp[n-1], dp[n-2]有关, 只需存储这两个状态即可 61 | # 空间复杂度: O(1) 62 | dp1 = 1 63 | dp2 = 2 64 | for i in range(2, n): 65 | dp1, dp2 = dp2, dp1 + dp2 66 | 67 | return dp2 68 | -------------------------------------------------------------------------------- /Graph/Graph.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | -------------------------------------------------------------------------------- /Greedy/Greedy.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | -------------------------------------------------------------------------------- /HashTable/136_SingleNumber.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/single-number/description. 6 | 题目描述: 7 | 8 | Given an array of integers, every element appears twice except for one. Find that single one. 9 | 10 | Note: 11 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 12 | 13 | """ 14 | 15 | 16 | class Solution(object): 17 | def singleNumber(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | if not nums: 23 | return 0 24 | 25 | # 异或 26 | ans = nums[0] 27 | for i in range(1, len(nums)): 28 | ans ^= nums[i] 29 | 30 | return ans 31 | -------------------------------------------------------------------------------- /HashTable/1_TwoSum.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/two-sum/description. 6 | 题目描述: 7 | 8 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 9 | 10 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 11 | 12 | Example: 13 | Given nums = [2, 7, 11, 15], target = 9, 14 | 15 | Because nums[0] + nums[1] = 2 + 7 = 9, 16 | return [0, 1]. 17 | 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def twoSum(self, nums, target): 23 | """ 24 | :type nums: List[int] 25 | :type target: int 26 | :rtype: List[int] 27 | """ 28 | if not nums: 29 | return [] 30 | 31 | ans = [] 32 | hp = {} 33 | for i, n in enumerate(nums): 34 | if target - n in hp: 35 | ans.append(hp[target - n]) 36 | ans.append(i) 37 | return ans 38 | 39 | hp[n] = i 40 | 41 | return ans 42 | -------------------------------------------------------------------------------- /HashTable/1_TwoSum.rb: -------------------------------------------------------------------------------- 1 | # ================================================================================ 2 | # LeetCode - Algorithms - 1. Two Sum 3 | # https://leetcode.com/problems/two-sum/description 4 | # 5 | # Language: Ruby 6 | # Author: ConradG 7 | # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8 | # 第一反应为双循环遍历,发现题目归类于 Hash Table 中后也尝试使Hash Table 进行处理。 9 | # 在单线程场景下,使用Hash的方式有更优秀的时间复杂度,而双循环则更易拆分为多个线程。 10 | # 11 | # * Ruby中 []= 的优先级和 [] 一致,为除 () 外的最高优先级 12 | # ================================================================================ 13 | 14 | # @param {Integer[]} nums 15 | # @param {Integer} target 16 | # @return {Integer[]} 17 | 18 | def two_sum(nums, target) 19 | s = Hash.new 20 | num, i = nums.each_with_index.detect {|(num, i)| s[target - num] || !s[num] = i} 21 | [s[target - num], i] 22 | end 23 | 24 | # 25 | # 19 / 19 test cases passed. 26 | # Status: Accepted 27 | # Runtime: 57 ms 28 | # Your runtime beats 75.07 % of ruby submissions. 29 | # 30 | -------------------------------------------------------------------------------- /HashTable/217_ContainsDuplicate.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/contains-duplicate/description. 6 | 题目描述: 7 | 8 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any 9 | value appears at least twice in the array, and it should return false if every element is distinct. 10 | 11 | """ 12 | 13 | 14 | class Solution(object): 15 | def containsDuplicate(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: bool 19 | """ 20 | if not nums: 21 | return False 22 | 23 | # 查重 24 | return len(nums) != len(set(nums)) 25 | -------------------------------------------------------------------------------- /HashTable/349_IntersectionOfTwoArrays.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/intersection-of-two-arrays/description. 6 | 题目描述: 7 | 8 | Given two arrays, write a function to compute their intersection. 9 | 10 | Example: 11 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 12 | 13 | Note: 14 | Each element in the result must be unique. 15 | The result can be in any order. 16 | 17 | """ 18 | 19 | 20 | class Solution(object): 21 | def intersection(self, nums1, nums2): 22 | """ 23 | :type nums1: List[int] 24 | :type nums2: List[int] 25 | :rtype: List[int] 26 | """ 27 | if not nums1 or not nums2: 28 | return [] 29 | 30 | # 交集 31 | return list(set(nums1) & set(nums2)) 32 | -------------------------------------------------------------------------------- /HashTable/3_LongestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | # ================================================================================ 3 | # LeetCode - Algorithms - 3. Longest Substring Without Repeating Characters 4 | # https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ 5 | # 6 | # Language: C++ 7 | # Author: ConradG 8 | # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9 | # 比较典型的滑动窗口结构。 10 | # ================================================================================ 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int lengthOfLongestSubstring(string s) { 16 | 17 | // 记录每一个字符在滑动窗口中出现的绝对位置 18 | int pos[256]; 19 | for(int &e : pos) e = -1; 20 | 21 | int left = 0, right = 0, max = 0; 22 | for(char ch : s){ 23 | 24 | // 如果当前字符在记录的绝对位置不为-1,窗口的左边界移动到上次出现位置的右侧 25 | if(pos[ch] > -1){ 26 | int temp = pos[ch]; 27 | for(int i = left; i <= pos[ch]; i++) pos[s[i]] = -1; 28 | left = temp + 1; 29 | } 30 | 31 | // 滑动右边界 32 | pos[ch] = right++; 33 | 34 | // 更新最大值 35 | if(right - left > max) max = right - left; 36 | } 37 | 38 | return max; 39 | } 40 | }; 41 | 42 | /* 43 | # 983 / 983 test cases passed. 44 | # Status: Accepted 45 | # Runtime: 20 ms 46 | # Your runtime beats 87.30 % of cpp submissions. 47 | */ 48 | -------------------------------------------------------------------------------- /HashTable/llb/136. Single Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array of integers, every element appears twice except for one. Find that single one. 4 | 5 | Note: 6 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 7 | */ 8 | 9 | /* 10 | 思路:要求是在线性时间完成,并且不适用额外的空间 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int singleNumber(vector& nums) { 16 | //思路一:先排序,然后两两比较,不相同则,单独元素就是就是这组的前一个 17 | // sort(nums.begin(), nums.end()); 18 | // for (int i=0; i s; 28 | while (n != 1) { 29 | int temp = 0; 30 | while (n) { 31 | temp += (n%10)*(n%10); //计算各位的平方,然后相加 32 | n /= 10; 33 | } 34 | n = temp; //将计算的和赋值给n 35 | if (s.count(n) > 0) //陷入重复循环了,判断n是否在set中了 36 | break; 37 | else 38 | s.insert(n); 39 | } 40 | 41 | return n==1; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /HashTable/llb/217. Contains Duplicate.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array of integers, find if the array contains any duplicates. 4 | Your function should return true if any value appears at least twice in the array, 5 | and it should return false if every element is distinct. 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool containsDuplicate(vector& nums) { 11 | /* 12 | //基本思路:逐个遍历找寻是否有相同的 13 | for (int i=0; i& nums, int k) { 10 | //题目的意思是:是否包含了一走路相同的值的数字,并且他们的下标不大于k 11 | //思路:借助map来实现,key存nums的值,value存下标i 12 | map myMap; 13 | for (int i=0; i intersection(vector& nums1, vector& nums2) { 16 | //思路一:先排序,然后利用两个下标从两个容器开始,比较大小,把小的向后移动。 17 | //如果相等的话,再比较是结果的容器内是否已经有了该值 18 | int i=0, j=0; 19 | vector vec; 20 | sort(nums1.begin(), nums1.end()); 21 | sort(nums2.begin(), nums2.end()); 22 | while(i < nums1.size() && j < nums2.size()) { 23 | if (nums1[i] > nums2[j]) { 24 | j++; 25 | } 26 | else if (nums1[i] < nums2[j]) { 27 | i++; 28 | } 29 | else { 30 | if (vec.empty() || vec.back() != nums1[i]) { 31 | vec.push_back(nums1[i]); 32 | } 33 | i++; 34 | j++; 35 | } 36 | } 37 | 38 | return vec; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Heap/Heap.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LinkedList/141. Linked List Cycle(判断链表是否有回路).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a linked list, determine if it has a cycle in it. 4 | 5 | Follow up: 6 | Can you solve it without using extra space? 7 | */ 8 | 9 | 10 | /* 11 | 思路:利用快慢指针的思想,看能否交汇,知道快指针下个点为空(如果有环那么next不会有尾,没环就会有尾) 12 | */ 13 | 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | bool hasCycle(ListNode *head) { 26 | if (head == nullptr) { 27 | return false; 28 | } 29 | 30 | ListNode *fast = head->next; 31 | ListNode *slow = head; 32 | while(fast != nullptr && fast->next != nullptr) { 33 | if (fast == slow) { 34 | return true; 35 | } 36 | 37 | fast = fast->next->next; //快指针每次走两步 38 | slow = slow->next; //慢指针每次走一步 39 | } 40 | 41 | return false; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /LinkedList/141_LinkedListCycle.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/linked-list-cycle/description. 6 | 题目描述: 7 | 8 | Given a linked list, determine if it has a cycle in it. 9 | 10 | Follow up: 11 | Can you solve it without using extra space? 12 | 13 | """ 14 | 15 | 16 | # Definition for singly-linked list. 17 | class ListNode(object): 18 | def __init__(self, x): 19 | self.val = x 20 | self.next = None 21 | 22 | 23 | class Solution(object): 24 | def hasCycle(self, head): 25 | """ 26 | :type head: ListNode 27 | :rtype: bool 28 | """ 29 | if not head or not head.next: 30 | return False 31 | 32 | pre = head 33 | ptr = head.next 34 | 35 | while ptr and ptr.next: 36 | if pre == ptr: 37 | return True 38 | pre = pre.next 39 | ptr = ptr.next.next 40 | 41 | return False 42 | -------------------------------------------------------------------------------- /LinkedList/142. Linked List Cycle II(找含环链表入环口).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 4 | 5 | Note: Do not modify the linked list. 6 | */ 7 | 8 | /* 9 | 思路: 10 | 和找链表是否有环一样,利用快慢指针的思路。 11 | 1.利用快慢指针找到第一次相遇点 12 | 2.然后将快指针(慢指针)指向链表头,慢指针(快指针)继续指向相遇点。注:这时步数每次均都为1 13 | 3.知道这次相遇,相遇点即为入环口。(至于原因解析请看md文件) 14 | */ 15 | 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * struct ListNode { 20 | * int val; 21 | * ListNode *next; 22 | * ListNode(int x) : val(x), next(NULL) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | ListNode *detectCycle(ListNode *head) { 28 | if (head == nullptr || head->next == nullptr) { 29 | return nullptr; 30 | } 31 | 32 | ListNode* fast = head; 33 | ListNode* slow = head; 34 | while(fast->next != nullptr && fast->next->next != nullptr) { 35 | //先走一次,再判断 36 | fast = fast->next->next; 37 | slow = slow->next; 38 | //走到第一个相遇点,把fast又赋给头,继续每次走一步,直到相遇点 39 | if (fast == slow) { 40 | fast = head; 41 | while(fast != slow) { 42 | fast = fast->next; 43 | slow = slow->next; 44 | } 45 | return fast; 46 | } 47 | } 48 | 49 | return nullptr; 50 | } 51 | }; 52 | 53 | -------------------------------------------------------------------------------- /LinkedList/19. Remove Nth Node From End of List(尾部第n个节点删除).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a linked list, remove the nth node from the end of list and return its head. 4 | 5 | For example, 6 | 7 | Given linked list: 1->2->3->4->5, and n = 2. 8 | 9 | After removing the second node from the end, the linked list becomes 1->2->3->5. 10 | Note: 11 | Given n will always be valid. 12 | Try to do this in one pass. 13 | */ 14 | 15 | 16 | /* 17 | 思路:先找到总长,再减去n,那个位置就是要删除的节点的前一个节点 18 | 注意:细节,删除第一点、n大于链表长度的情况 19 | */ 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * struct ListNode { 24 | * int val; 25 | * ListNode *next; 26 | * ListNode(int x) : val(x), next(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | ListNode* removeNthFromEnd(ListNode* head, int n) { 32 | 33 | if (head == nullptr) { 34 | return nullptr; 35 | } 36 | 37 | ListNode *pDummy = new ListNode(0); 38 | pDummy->next = head; 39 | ListNode *pIter = head; 40 | int len = 0; 41 | while(pIter != nullptr) { 42 | len++; 43 | pIter = pIter->next; 44 | } 45 | 46 | //分别进行长度的判断 47 | if (n > len) { //n大于长度,没有改点 48 | return nullptr; 49 | } 50 | else if (n == len) { //n等于长度,意思是要删除第一个元素的情况 51 | pDummy->next = head->next; 52 | delete head; 53 | return pDummy->next; 54 | } 55 | else { 56 | ListNode* pTemp = pDummy->next; 57 | int index = 0; 58 | while(pTemp != nullptr && pTemp->next != nullptr) { 59 | index++; 60 | //达到要求就删除节点 61 | if (index + n == len) { 62 | pTemp->next = pTemp->next->next; 63 | break; 64 | } 65 | pTemp = pTemp->next; 66 | } 67 | return pDummy->next; 68 | } 69 | } 70 | }; 71 | -------------------------------------------------------------------------------- /LinkedList/2. Add Two Numbers(链表数相加).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 4 | 5 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 6 | 7 | Example 8 | 9 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 10 | Output: 7 -> 0 -> 8 11 | Explanation: 342 + 465 = 807. 12 | */ 13 | 14 | 15 | /* 16 | 思路:每次移动两个指针,将两数相加,每次创建一个新node,生成一个链表。 17 | 注意:计算它的溢出值,得移动到下位相加时也用到。 18 | */ 19 | 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * struct ListNode { 24 | * int val; 25 | * ListNode *next; 26 | * ListNode(int x) : val(x), next(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 32 | ListNode* head = new ListNode(0); 33 | ListNode* ptr = head; 34 | int carry = 0; //记录每位运算值 35 | while(true) { 36 | if (l1 != nullptr) { 37 | carry += l1->val; 38 | l1 = l1->next; 39 | } 40 | if (l2 != nullptr) { 41 | carry += l2->val; 42 | l2 = l2->next; 43 | } 44 | 45 | ptr->val = carry%10; 46 | carry = carry/10; 47 | //如果两个链表还有未空的或者还有进位,就继续运算 48 | if (l1 != nullptr || l2 != nullptr || carry != 0) { 49 | ptr->next = new ListNode(0); 50 | ptr = ptr->next; 51 | }else { 52 | break; 53 | } 54 | } 55 | 56 | return head; 57 | } 58 | 59 | }; 60 | -------------------------------------------------------------------------------- /LinkedList/203. Remove Linked List Elements(删除值为val的所有节点).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Remove all elements from a linked list of integers that have value val. 4 | 5 | Example 6 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 7 | Return: 1 --> 2 --> 3 --> 4 --> 5 8 | */ 9 | 10 | /*思路: 11 | 遍历整个链表,相等的删掉(利用上个节点指针的next指向下个node),不同的继续向下进行 12 | 注意:第一个节点的判断,所以可以加上个节点,next指向头结点来处理 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode(int x) : val(x), next(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | ListNode* removeElements(ListNode* head, int val) { 26 | ListNode* temp = new ListNode(0); //作为头结点的上一个节点,为了方便处理头结点 27 | temp->next = head; 28 | 29 | ListNode* pCur = temp; //加一个当前指针来操作链表 30 | while(pCur->next != nullptr) { 31 | if (pCur->next->val == val) { 32 | pCur->next = pCur->next->next; 33 | }else { 34 | pCur = pCur->next; 35 | } 36 | } 37 | 38 | return temp->next; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /LinkedList/203_RemoveLinkedListElements.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/remove-linked-list-elements/description. 6 | 题目描述: 7 | 8 | Remove all elements from a linked list of integers that have value val. 9 | 10 | Example 11 | Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 12 | Return: 1 --> 2 --> 3 --> 4 --> 5 13 | 14 | Credits: 15 | Special thanks to @mithmatt for adding this problem and creating all test cases. 16 | 17 | """ 18 | 19 | 20 | # Definition for singly-linked list. 21 | class ListNode(object): 22 | def __init__(self, x): 23 | self.val = x 24 | self.next = None 25 | 26 | 27 | class Solution(object): 28 | def removeElements(self, head, val): 29 | """ 30 | :type head: ListNode 31 | :type val: int 32 | :rtype: ListNode 33 | """ 34 | fake_head = ListNode(0) 35 | fake_head.next = head 36 | ptr = fake_head 37 | 38 | while ptr and ptr.next: 39 | n = ptr.next 40 | if n.val == val: 41 | ptr.next = n.next 42 | n.next = None 43 | else: 44 | ptr = ptr.next 45 | 46 | return fake_head.next 47 | -------------------------------------------------------------------------------- /LinkedList/206. Reverse Linked List(翻转单链表).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Reverse a singly linked list. 4 | */ 5 | 6 | /* 7 | 思路:定义一个头结点和头结点之前的指针,每步生成一个指针保存下个节点地址,然后翻转指针指向,之后一步步向后移动 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | * int val; 14 | * ListNode *next; 15 | * ListNode(int x) : val(x), next(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* reverseList(ListNode* head) { 21 | ListNode* pPrev = nullptr; 22 | while(head) { 23 | ListNode* pNode = head->next; 24 | head->next = pPrev; 25 | pPrev = head; 26 | head = pNode; 27 | } 28 | 29 | return pPrev; 30 | } 31 | }; 32 | 33 | 34 | //拆分出来的代码,步骤细分的 35 | class Solution { 36 | public: 37 | ListNode * reverse(ListNode * head) { 38 | // write your code here 39 | ListNode* pReverseHead = nullptr; //翻转后的指针头结点 40 | ListNode* pNode = head; //当前结点 41 | ListNode* pPrev = nullptr; //前一节点 42 | while (pNode != nullptr) { 43 | ListNode* pNext = pNode->next; //next保存当前结点的下个结点,防止丢失 44 | if (pNext == nullptr) { 45 | pReverseHead = pNode; //如果下个结点直接为nullptr结束了,那么翻转头就是本结点了 46 | } 47 | pNode->next = pPrev; //将当前结点指向前一个结点,翻转 48 | //结点向后移动 49 | pPrev = pNode; 50 | pNode = pNext; 51 | } 52 | 53 | return pReverseHead; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /LinkedList/206_ReverseLinkedList.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/reverse-linked-list/description. 6 | 题目描述: 7 | 8 | Reverse a singly linked list. 9 | 10 | click to show more hints. 11 | 12 | Hint: 13 | A linked list can be reversed either iteratively or recursively. Could you implement both? 14 | 15 | """ 16 | 17 | 18 | # Definition for singly-linked list. 19 | class ListNode(object): 20 | def __init__(self, x): 21 | self.val = x 22 | self.next = None 23 | 24 | 25 | class Solution(object): 26 | def reverseList_v1(self, head): 27 | """ 28 | :type head: ListNode 29 | :rtype: ListNode 30 | """ 31 | cursor = None 32 | while head: 33 | node = head.next 34 | head.next = cursor 35 | cursor = head 36 | head = node 37 | 38 | return cursor 39 | 40 | def reverseList_v2(self, head): 41 | """ 42 | :type head: ListNode 43 | :rtype: ListNode 44 | """ 45 | if not head: 46 | return None 47 | if not head.next: 48 | return head 49 | 50 | node = self.reverseList_v2(head.next) 51 | head.next.next = head 52 | head.next = None 53 | 54 | return node 55 | -------------------------------------------------------------------------------- /LinkedList/21. Merge Two Sorted Lists(合并有序链表).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 4 | 5 | Example: 6 | Input: 1->2->4, 1->3->4 7 | Output: 1->1->2->3->4->4 8 | 9 | */ 10 | 11 | /* 12 | 思路:每步分别移动两个链表,然后判断两个对应值的大小,如果小的,链接到当前指针,并且只移动当前直小的链表,下次在对比,知道有一个链表为空时 13 | 注意:当一个链接结束后还要链接上未完的链表 14 | */ 15 | 16 | 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * struct ListNode { 21 | * int val; 22 | * ListNode *next; 23 | * ListNode(int x) : val(x), next(NULL) {} 24 | * }; 25 | */ 26 | class Solution { 27 | public: 28 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 29 | 30 | if ((l1 == NULL) && (l2 != NULL)) 31 | return l2; 32 | else if ((l1 != NULL) && (l2 == NULL)) 33 | return l1; 34 | else if ((l1 == NULL) && (l2 == NULL)) 35 | return NULL; 36 | 37 | //***这个方法是没有生成新的node串联,而是生成一个新的指针串联当前l1、l2中的node*** 38 | ListNode* dummy = new ListNode(0); 39 | ListNode* pTemp = dummy; //比较后串联生成链表的指针 40 | while(l1 != nullptr && l2 != nullptr) { 41 | if (l1->val < l2->val) { 42 | pTemp->next = l1; 43 | l1 = l1->next; 44 | } else { 45 | pTemp->next = l2; 46 | l2 = l2->next; 47 | } 48 | //再把比较temp向后移动 49 | pTemp = pTemp->next; 50 | } 51 | 52 | //串联起剩余未完的链表 53 | if (l1 != nullptr) { 54 | pTemp->next = l1; 55 | } else { 56 | pTemp->next = l2; 57 | } 58 | 59 | //返回头结点 60 | return dummy->next; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /LinkedList/21_MergeTwoSortedLists.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/merge-two-sorted-lists/description. 6 | 题目描述: 7 | 8 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the 9 | nodes of the first two lists. 10 | 11 | Example: 12 | 13 | Input: 1->2->4, 1->3->4 14 | Output: 1->1->2->3->4->4 15 | 16 | """ 17 | 18 | 19 | # Definition for singly-linked list. 20 | class ListNode(object): 21 | def __init__(self, x): 22 | self.val = x 23 | self.next = None 24 | 25 | 26 | class Solution(object): 27 | def mergeTwoLists(self, l1, l2): 28 | """ 29 | :type l1: ListNode 30 | :type l2: ListNode 31 | :rtype: ListNode 32 | """ 33 | head = cursor = ListNode(0) 34 | while l1 and l2: 35 | if l1.val > l2.val: 36 | cursor.next = l2 37 | l2 = l2.next 38 | else: 39 | cursor.next = l1 40 | l1 = l1.next 41 | cursor = cursor.next 42 | if l1: 43 | cursor.next = l1 44 | else: 45 | cursor.next = l2 46 | 47 | return head.next 48 | -------------------------------------------------------------------------------- /LinkedList/234_PalindromeLinkedList.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/palindrome-linked-list/description. 6 | 题目描述: 7 | 8 | Given a singly linked list, determine if it is a palindrome. 9 | 10 | Follow up: 11 | Could you do it in O(n) time and O(1) space? 12 | 13 | """ 14 | 15 | 16 | # Definition for singly-linked list. 17 | class ListNode(object): 18 | def __init__(self, x): 19 | self.val = x 20 | self.next = None 21 | 22 | def __repr__(self): 23 | return 'val: {0}'.format(self.val) 24 | 25 | 26 | class Solution(object): 27 | def isPalindrome(self, head): 28 | """ 29 | :type head: ListNode 30 | :rtype: bool 31 | """ 32 | # @TODO: 优化: 反转链表后半段(空间复杂度O(n)->O(1)) 33 | if not head or not head.next: 34 | return True 35 | 36 | copy_head = ListNode(head.val) 37 | ctr = copy_head 38 | ptr = head.next 39 | while ptr: 40 | ctr.next = ListNode(ptr.val) 41 | ctr = ctr.next 42 | ptr = ptr.next 43 | 44 | reversed_head = None 45 | ptr = copy_head 46 | 47 | while ptr: 48 | node = ptr.next 49 | ptr.next = reversed_head 50 | reversed_head = ptr 51 | ptr = node 52 | 53 | while head and reversed_head and head.val == reversed_head.val: 54 | head = head.next 55 | reversed_head = reversed_head.next 56 | 57 | return not head 58 | -------------------------------------------------------------------------------- /LinkedList/237_Delete Node in a Linked List(删除节点).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 4 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, 5 | the linked list should become 1 -> 2 -> 4 after calling your function. 6 | */ 7 | 8 | 9 | /*思路: 10 | 用当前要删除的节点的下个节点值替换当前值,然后删除下个节点即可(实际删除的是下个节点) 11 | */ 12 | 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * struct ListNode { 17 | * int val; 18 | * ListNode *next; 19 | * ListNode(int x) : val(x), next(NULL) {} 20 | * }; 21 | */ 22 | class Solution { 23 | public: 24 | void deleteNode(ListNode* node) { 25 | node->val = node->next->val; 26 | ListNode* temp = node->next; 27 | node->next = temp->next; 28 | delete temp; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /LinkedList/24_SwapNodesInPairs.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/swap-nodes-in-pairs/description. 6 | 题目描述: 7 | 8 | Given a linked list, swap every two adjacent nodes and return its head. 9 | 10 | For example, 11 | Given 1->2->3->4, you should return the list as 2->1->4->3. 12 | 13 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be 14 | changed. 15 | 16 | """ 17 | 18 | 19 | # Definition for singly-linked list. 20 | class ListNode(object): 21 | def __init__(self, x): 22 | self.val = x 23 | self.next = None 24 | 25 | def __repr__(self): 26 | return 'val: {0}'.format(self.val) 27 | 28 | 29 | class Solution(object): 30 | def swapPairs(self, head): 31 | """ 32 | :type head: ListNode 33 | :rtype: ListNode 34 | """ 35 | if not head or not head.next: 36 | return head 37 | 38 | cursor = head 39 | pre = ListNode(0) 40 | head = head.next 41 | 42 | while cursor and cursor.next: 43 | n = cursor.next 44 | cursor.next = n.next 45 | n.next = cursor 46 | pre.next = n 47 | pre = cursor 48 | cursor = cursor.next 49 | 50 | return head 51 | -------------------------------------------------------------------------------- /LinkedList/2_AddTwoNumbers.py3: -------------------------------------------------------------------------------- 1 | # ================================================================================ 2 | # LeetCode - Algorithms - 2. Add Two Numbers 3 | # https://leetcode.com/problems/add-two-numbers/description/ 4 | # 5 | # Language: Python3 6 | # Author: ConradG 7 | # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8 | # 第一反应竟然是反转后转换成数字进行加法 XD 9 | # 基本的链表操作,不过请教使用python的小伙伴为什么这么慢 T.T 10 | # ================================================================================ 11 | 12 | # Definition for singly-linked list. 13 | # class ListNode: 14 | # def __init__(self, x): 15 | # self.val = x 16 | # self.next = None 17 | 18 | class Solution: 19 | def addTwoNumbers(self, l1, l2): 20 | 21 | """ 22 | :type l1: ListNode 23 | :type l2: ListNode 24 | :rtype: ListNode 25 | """ 26 | 27 | p = 0 28 | result = t = ListNode(0) 29 | while (l1 or l2 or p > 0): 30 | 31 | a = l1.val if l1 != None else 0 32 | b = l2.val if l2 != None else 0 33 | 34 | t.next = ListNode((a + b + p) % 10) 35 | t = t.next 36 | 37 | l1, l2, p = l1.next if l1 else None, l2.next if l2 else None, (a + b + p) // 10 38 | 39 | return result.next 40 | 41 | # 1562 / 1562 test cases passed. 42 | # Status: Accepted 43 | # Runtime: 215 ms 44 | # Your runtime beats 40.06 % of python3 submissions. 45 | -------------------------------------------------------------------------------- /LinkedList/445. Add Two Numbers II(链表逆序相加).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 4 | 5 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 6 | 7 | Follow up: 8 | What if you cannot modify the input lists? In other words, reversing the lists is not allowed. 9 | 10 | Example: 11 | 12 | Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 13 | Output: 7 -> 8 -> 0 -> 7 14 | */ 15 | 16 | 17 | /* 18 | 思路:由于是链表逆序相加,何不把两条链表值放入到栈中,然后再相加连接起来。 19 | 注意:注意链接过程中需要再把链表翻转过来 20 | */ 21 | 22 | 23 | /** 24 | * Definition for singly-linked list. 25 | * struct ListNode { 26 | * int val; 27 | * ListNode *next; 28 | * ListNode(int x) : val(x), next(NULL) {} 29 | * }; 30 | */ 31 | class Solution { 32 | public: 33 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 34 | stack s1, s2; 35 | while (l1) { 36 | s1.push(l1->val); 37 | l1 = l1->next; 38 | } 39 | while (l2) { 40 | s2.push(l2->val); 41 | l2 = l2->next; 42 | } 43 | 44 | int sum = 0; 45 | ListNode* pHead = new ListNode(0); 46 | while(!s1.empty() || !s2.empty()) { 47 | if(!s1.empty()) { 48 | sum += s1.top(); 49 | s1.pop(); 50 | } 51 | if (!s2.empty()) { 52 | sum += s2.top(); 53 | s2.pop(); 54 | } 55 | 56 | pHead->val = sum%10; 57 | //这块处理在两个链表都为结束时是没有意义的,当为最后一个时相加时才有意义, 58 | //因为是最后一遍循环,下次不能再循环赋值了,即不能在执行pHead->val = sum%10; 59 | ListNode* pNewNode = new ListNode(sum/10); 60 | pNewNode->next = pHead; 61 | pHead = pNewNode; 62 | sum = sum/10; 63 | } 64 | 65 | return pHead->val==0 ? pHead->next : pHead; 66 | } 67 | }; 68 | -------------------------------------------------------------------------------- /LinkedList/61. Rotate List(旋转链表).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a list, rotate the list to the right by k places, where k is non-negative. 4 | 5 | Example: 6 | 7 | Given 1->2->3->4->5->NULL and k = 2, 8 | return 4->5->1->2->3->NULL. 9 | */ 10 | 11 | 12 | /* 13 | 思路一: 14 | 利用指针找到分割点,然后拆分,再拼接起来 15 | 思路二: 16 | 利用容器等将node放入再拼接 17 | 18 | 注意: 19 | 注意k远大于链表长度的情况,所以要对他取余 20 | */ 21 | 22 | 23 | /** 24 | * Definition for singly-linked list. 25 | * struct ListNode { 26 | * int val; 27 | * ListNode *next; 28 | * ListNode(int x) : val(x), next(NULL) {} 29 | * }; 30 | */ 31 | class Solution { 32 | public: 33 | ListNode* rotateRight(ListNode* head, int k) { 34 | if (head == nullptr) { 35 | return nullptr; 36 | } 37 | 38 | int len = 1; 39 | ListNode* ptr = head; 40 | while(ptr->next) { 41 | len++; 42 | ptr = ptr->next; 43 | } 44 | 45 | //把尾节点指向头部 46 | ptr->next = head; 47 | int step = len - k%len; //k可以很大 48 | //找到分割点的前一个点 49 | for(int i=0; inext; 51 | } 52 | 53 | ListNode* newHead = ptr->next; 54 | ptr->next = nullptr; 55 | 56 | return newHead; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /LinkedList/61_RotateList.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/rotate-list/description. 6 | 题目描述: 7 | 8 | Given a list, rotate the list to the right by k places, where k is non-negative. 9 | 10 | Example: 11 | 12 | Given 1->2->3->4->5->NULL and k = 2, 13 | 14 | return 4->5->1->2->3->NULL. 15 | 16 | """ 17 | 18 | 19 | # Definition for singly-linked list. 20 | class ListNode(object): 21 | def __init__(self, x): 22 | self.val = x 23 | self.next = None 24 | 25 | 26 | class Solution(object): 27 | def rotateRight(self, head, k): 28 | """ 29 | :type head: ListNode 30 | :type k: int 31 | :rtype: ListNode 32 | """ 33 | if not head or not head.next or k == 0: 34 | return head 35 | 36 | def reverse_partial_list(node, start, end): 37 | """反转指定区间的链表""" 38 | fake_head = ListNode(0) 39 | fake_head.next = node 40 | pre = fake_head 41 | for _ in range(1, start): 42 | pre = pre.next 43 | 44 | ptr = pre.next 45 | ctr = ptr.next 46 | 47 | for _ in range(0, end - start): 48 | ptr.next = ctr.next 49 | ctr.next = pre.next 50 | pre.next = ctr 51 | ctr = ptr.next 52 | 53 | return fake_head.next 54 | 55 | ll = 0 56 | p = head 57 | while p: 58 | ll += 1 59 | p = p.next 60 | 61 | k %= ll 62 | l1 = reverse_partial_list(head, 1, ll) 63 | l2 = reverse_partial_list(l1, 1, k) 64 | l3 = reverse_partial_list(l2, k + 1, ll) 65 | 66 | return l3 67 | -------------------------------------------------------------------------------- /LinkedList/82_RemoveDuplicatesFromSortedListII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description. 6 | 题目描述: 7 | 8 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the 9 | original list. 10 | 11 | For example, 12 | Given 1->2->3->3->4->4->5, return 1->2->5. 13 | Given 1->1->1->2->3, return 2->3. 14 | 15 | """ 16 | 17 | 18 | # Definition for singly-linked list. 19 | class ListNode(object): 20 | def __init__(self, x): 21 | self.val = x 22 | self.next = None 23 | 24 | 25 | class Solution(object): 26 | def deleteDuplicates(self, head): 27 | """ 28 | :type head: ListNode 29 | :rtype: ListNode 30 | """ 31 | if not head or not head.next: 32 | return head 33 | 34 | # 新生成一个节点, 保存原链表头部 35 | fake_head = ListNode(0) 36 | fake_head.next = head 37 | first_ptr = fake_head 38 | # pre指针保存前一个数值首次出现的节点位置 39 | pre = head 40 | ptr = head.next 41 | 42 | while ptr: 43 | if ptr.val != pre.val: 44 | # 核心: 仅相邻两个节点数值不同, 才说明该节点只出现一次 45 | if pre.next == ptr: 46 | first_ptr.next = pre 47 | first_ptr = first_ptr.next 48 | pre = ptr 49 | ptr = ptr.next 50 | 51 | # 加入最后一个节点 52 | first_ptr.next = None if pre.next else pre 53 | 54 | return fake_head.next 55 | -------------------------------------------------------------------------------- /LinkedList/83. Remove Duplicates from Sorted List(已排序列表去重).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a sorted linked list, delete all duplicates such that each element appear only once. 4 | 5 | For example, 6 | Given 1->1->2, return 1->2. 7 | Given 1->1->2->3->3, return 1->2->3. 8 | */ 9 | 10 | /* 11 | 思路:由于是已经排序好的了,所以每个节点只需和自己下个元素排序,如果相同则删除,否则继续 12 | */ 13 | 14 | class Solution { 15 | public: 16 | ListNode* deleteDuplicates(ListNode* head) { 17 | //思路,由于是排序的,所以从头遍历,如果值和下一个相同那么把改node删掉 18 | if (!head) { 19 | return nullptr; 20 | } 21 | 22 | ListNode *pNode = head; 23 | while(pNode->next != nullptr) { 24 | if (pNode->val == pNode->next->val) { 25 | pNode->next = pNode->next->next; 26 | }else { 27 | pNode = pNode->next; 28 | } 29 | } 30 | return head; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /LinkedList/83_RemoveDuplicatesFromSortedList.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/remove-duplicates-from-sorted-list/description. 6 | 题目描述: 7 | 8 | Given a sorted linked list, delete all duplicates such that each element appear only once. 9 | 10 | For example, 11 | Given 1->1->2, return 1->2. 12 | Given 1->1->2->3->3, return 1->2->3. 13 | 14 | """ 15 | 16 | 17 | # Definition for singly-linked list. 18 | class ListNode(object): 19 | def __init__(self, x): 20 | self.val = x 21 | self.next = None 22 | 23 | 24 | class Solution(object): 25 | def deleteDuplicates(self, head): 26 | """ 27 | :type head: ListNode 28 | :rtype: ListNode 29 | """ 30 | if not head or not head.next: 31 | return head 32 | 33 | # 游标指针, 比较下一个节点的值 34 | # 若相同, 删除; 反之, 移动游标, 指向下一个节点 35 | ptr = head 36 | while ptr and ptr.next: 37 | n = ptr.next 38 | if ptr.val == n.val: 39 | ptr.next = n.next 40 | n.next = None 41 | else: 42 | ptr = ptr.next 43 | 44 | return head 45 | -------------------------------------------------------------------------------- /LinkedList/92_ReverseLinkedListII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/reverse-linked-list-ii/description. 6 | 题目描述: 7 | 8 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 9 | 10 | For example: 11 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 12 | 13 | return 1->4->3->2->5->NULL. 14 | 15 | Note: 16 | Given m, n satisfy the following condition: 17 | 1 ≤ m ≤ n ≤ length of list. 18 | 19 | """ 20 | 21 | 22 | # Definition for singly-linked list. 23 | class ListNode(object): 24 | def __init__(self, x): 25 | self.val = x 26 | self.next = None 27 | 28 | 29 | class Solution(object): 30 | def reverseBetween(self, head, m, n): 31 | """ 32 | :type head: ListNode 33 | :type m: int 34 | :type n: int 35 | :rtype: ListNode 36 | """ 37 | if not head or not head.next or m == n: 38 | return head 39 | 40 | fake_head = ListNode(0) 41 | fake_head.next = head 42 | pre = fake_head 43 | for _ in range(1, m): 44 | pre = pre.next 45 | 46 | ptr = pre.next 47 | ctr = ptr.next 48 | 49 | for _ in range(0, n - m): 50 | ptr.next = ctr.next 51 | ctr.next = pre.next 52 | pre.next = ctr 53 | ctr = ptr.next 54 | 55 | return fake_head.next 56 | -------------------------------------------------------------------------------- /Math/Math.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | leetcode刷题, 直接用leetcode的分类方式. 3 | 4 | - [x] 数组 (完成时间: 2018-01-23) 5 | - 字符串 6 | - [x] 链表 (完成时间: 2018-01-28) 7 | - 哈希表 8 | - [x] 堆栈 (完成时间: 2018-02-07) 9 | - 双指针 10 | - [x] 树 (完成时间: 2018-02-04) 11 | - 图 12 | - 深搜/广搜 13 | - [x] 二分搜索 (完成时间: 2018-02-06) 14 | - 动规 15 | - 其他: 数学, 位操作, 设计题等 16 | 17 | ps: [刷题列表](ProblemsList.md) 18 | 19 | ## Contributors: 20 | 21 | - [llb19911212](https://github.com/llb19911212) 22 | - [conradgcn](https://github.com/conradgcn) 23 | - [heaven-fox](https://github.com/heaven-fox) 24 | -------------------------------------------------------------------------------- /Stack/150_EvaluateReversePolishNotation.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/evaluate-reverse-polish-notation/description. 6 | 题目描述: 7 | 8 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 9 | 10 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 11 | 12 | Some examples: 13 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 14 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 15 | 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def evalRPN(self, tokens): 21 | """ 22 | :type tokens: List[str] 23 | :rtype: int 24 | """ 25 | stack = [] 26 | operators = { 27 | '+': lambda x, y: y + x, 28 | '-': lambda x, y: y - x, 29 | '*': lambda x, y: y * x, 30 | '/': lambda x, y: int(float(y) / float(x)) 31 | } 32 | for op in tokens: 33 | if op in operators: 34 | stack.append(operators[op](stack.pop(), stack.pop())) 35 | else: 36 | stack.append(int(op)) 37 | 38 | return stack[0] 39 | -------------------------------------------------------------------------------- /Stack/155_MinStack.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/min-stack/description. 6 | 题目描述: 7 | 8 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 9 | 10 | push(x) -- Push element x onto stack. 11 | pop() -- Removes the element on top of the stack. 12 | top() -- Get the top element. 13 | getMin() -- Retrieve the minimum element in the stack. 14 | Example: 15 | MinStack minStack = new MinStack(); 16 | minStack.push(-2); 17 | minStack.push(0); 18 | minStack.push(-3); 19 | minStack.getMin(); --> Returns -3. 20 | minStack.pop(); 21 | minStack.top(); --> Returns 0. 22 | minStack.getMin(); --> Returns -2. 23 | 24 | """ 25 | 26 | 27 | class MinStack(object): 28 | 29 | def __init__(self): 30 | """ 31 | initialize your data structure here. 32 | """ 33 | self.stack = [] 34 | # 记录stack当前最小值 35 | self.min = [] 36 | 37 | def push(self, x): 38 | """ 39 | :type x: int 40 | :rtype: void 41 | """ 42 | if not self.min or x <= self.min[-1]: 43 | self.min.append(x) 44 | self.stack.append(x) 45 | 46 | def pop(self): 47 | """ 48 | :rtype: void 49 | """ 50 | if not self.stack: 51 | return 52 | 53 | if self.stack[-1] == self.min[-1]: 54 | self.min.pop() 55 | self.stack.pop() 56 | 57 | def top(self): 58 | """ 59 | :rtype: int 60 | """ 61 | if not self.stack: 62 | return -1 63 | 64 | return self.stack[-1] 65 | 66 | def getMin(self): 67 | """ 68 | :rtype: int 69 | """ 70 | if not self.min: 71 | return -1 72 | 73 | return self.min[-1] 74 | 75 | # Your MinStack object will be instantiated and called as such: 76 | # obj = MinStack() 77 | # obj.push(x) 78 | # obj.pop() 79 | # param_3 = obj.top() 80 | # param_4 = obj.getMin() 81 | -------------------------------------------------------------------------------- /Stack/20_ValidParentheses.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/valid-parentheses/description. 6 | 题目描述: 7 | 8 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is 9 | valid. 10 | 11 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 12 | 13 | """ 14 | 15 | 16 | class Solution(object): 17 | def isValid(self, s): 18 | """ 19 | :type s: str 20 | :rtype: bool 21 | """ 22 | if not s: 23 | return True 24 | 25 | if s[0] in [')', ']', '}']: 26 | return False 27 | 28 | stack = [s[0]] 29 | for i in range(1, len(s)): 30 | if s[i] == ')' and stack and stack[-1] == '(': 31 | stack.pop() 32 | elif s[i] == ']' and stack and stack[-1] == '[': 33 | stack.pop() 34 | elif s[i] == '}' and stack and stack[-1] == '{': 35 | stack.pop() 36 | else: 37 | stack.append(s[i]) 38 | 39 | return True if not stack else False 40 | -------------------------------------------------------------------------------- /Stack/316_RemoveDuplicateLetters.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/remove-duplicate-letters/description. 6 | 题目描述: 7 | 8 | Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and 9 | only once. You must make sure your result is the smallest in lexicographical order among all possible results. 10 | 11 | Example: 12 | Given "bcabc" 13 | Return "abc" 14 | 15 | Given "cbacdcbc" 16 | Return "acdb" 17 | 18 | Credits: 19 | Special thanks to @dietpepsi for adding this problem and creating all test cases. 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def removeDuplicateLetters(self, s): 26 | """ 27 | :type s: str 28 | :rtype: str 29 | """ 30 | if not s or len(s) < 2: 31 | return s 32 | 33 | vis = [0] * 26 34 | cnt = [0] * 26 35 | ans = [] 36 | for c in s: 37 | cnt[ord(c) - 97] += 1 38 | # 遍历, 若当前字符已入栈, 跳过 39 | # 否则, 与栈顶字符比较, 若小于栈顶字符且cnt[c] > 0(证明后面还会出现该字符), 出栈, 同时访问标记置为0 40 | # 当前字符入栈, 访问标记置为1 41 | for c in s: 42 | idx = ord(c) - 97 43 | cnt[idx] -= 1 44 | if vis[idx]: 45 | continue 46 | while ans and c < ans[-1] and cnt[ord(ans[-1]) - 97]: 47 | vis[ord(ans[-1]) - 97] = 0 48 | ans.pop() 49 | ans.append(c) 50 | vis[idx] = 1 51 | 52 | return ''.join(ans) 53 | -------------------------------------------------------------------------------- /Stack/71_SimplifyPath.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/simplify-path/description. 6 | 题目描述: 7 | 8 | Given an absolute path for a file (Unix-style), simplify it. 9 | 10 | For example, 11 | path = "/home/", => "/home" 12 | path = "/a/./b/../../c/", => "/c" 13 | click to show corner cases. 14 | 15 | Corner Cases: 16 | Did you consider the case where path = "/../"? 17 | In this case, you should return "/". 18 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 19 | In this case, you should ignore redundant slashes and return "/home/foo". 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def simplifyPath(self, path): 26 | """ 27 | :type path: str 28 | :rtype: str 29 | """ 30 | if not path: 31 | return '' 32 | 33 | # 记录所有子目录 34 | stack = [] 35 | i = 0 36 | while i < len(path): 37 | # 跳过类似'///'开头 38 | while i < len(path) and path[i] == '/': 39 | i += 1 40 | if i == len(path): 41 | break 42 | start = i 43 | while i < len(path) and path[i] != '/': 44 | i += 1 45 | end = i 46 | # 截取子目录 47 | sub = path[start:end] 48 | if sub == '..': 49 | if stack: 50 | stack.pop() 51 | elif sub and sub != '.': 52 | stack.append(sub) 53 | 54 | if not stack: 55 | return '/' 56 | 57 | ans = '' 58 | for s in stack: 59 | ans += '/' + s 60 | 61 | return ans 62 | -------------------------------------------------------------------------------- /Stack/llb/144. Binary Tree Preorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a binary tree, return the preorder traversal of its nodes' values. 4 | 5 | For example: 6 | Given binary tree [1,null,2,3], 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | return [1,2,3]. 13 | */ 14 | 15 | 16 | /** 17 | * Definition for a binary tree node. 18 | * struct TreeNode { 19 | * int val; 20 | * TreeNode *left; 21 | * TreeNode *right; 22 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | //前序遍历:根->左->右 28 | 29 | //思路一:递归 30 | // vector preorderTraversal(TreeNode* root) { 31 | // vector resVec; 32 | // preorder(root, resVec); 33 | // return resVec; 34 | // } 35 | 36 | // void preorder(TreeNode* root, vector &vec) { 37 | // if (root == NULL) { 38 | // return; 39 | // } 40 | 41 | // vec.push_back(root->val); 42 | // preorder(root->left, vec); 43 | // preorder(root->right, vec); 44 | // } 45 | 46 | //思路二:利用栈。 47 | //1.把根节点压入到栈中。 48 | //2.循环检测栈是否为空,若不为空,则取出栈顶元素,保存值。 49 | //3.判断该值的右子树是否为空,若存在则push到栈中。再判断其左子树是否为空,若存在则push到栈中。 50 | vector preorderTraversal(TreeNode* root) { 51 | if (root == NULL) { 52 | return {}; 53 | } 54 | 55 | vector resVec; 56 | stack s; 57 | s.push(root); 58 | while (!s.empty()) { 59 | TreeNode* pTemp = s.top(); 60 | s.pop(); 61 | resVec.push_back(pTemp->val); 62 | if (pTemp->right) 63 | s.push(pTemp->right); 64 | if (pTemp->left) 65 | s.push(pTemp->left); 66 | } 67 | 68 | return resVec; 69 | } 70 | }; 71 | -------------------------------------------------------------------------------- /Stack/llb/145. Binary Tree Postorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a binary tree, return the postorder traversal of its nodes' values. 4 | 5 | For example: 6 | Given binary tree [1,null,2,3], 7 | 8 | 1 9 | \ 10 | 2 11 | / 12 | 3 13 | 14 | return [3,2,1]. 15 | 16 | 二叉树的后序遍历 17 | */ 18 | 19 | /* 20 | 非递归核心思想:利用栈,在二叉树的前序遍历基础上改动一下,再逆序就是后序遍历了 21 | */ 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * struct TreeNode { 26 | * int val; 27 | * TreeNode *left; 28 | * TreeNode *right; 29 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 30 | * }; 31 | */ 32 | class Solution { 33 | public: 34 | 35 | //思路一:递归 36 | // vector postorderTraversal(TreeNode* root) { 37 | // vector vec; 38 | // postorder(root, vec); 39 | // return vec; 40 | // } 41 | 42 | // void postorder(TreeNode* root, vector &vec) { 43 | // if (root == NULL) { 44 | // return; 45 | // } 46 | 47 | // postorder(root->left, vec); 48 | // postorder(root->right, vec); 49 | // vec.push_back(root->val); 50 | // } 51 | 52 | 53 | //思路二:利用栈的思想 54 | //先序遍历是:根->左->右,而后序遍历是:左->右->根. 55 | //所以可以修改一下先序遍历为:根->右->左,然后给值倒叙出来即可 56 | vector postorderTraversal(TreeNode* root) { 57 | if (!root) { 58 | return {}; 59 | } 60 | 61 | vector resVec; 62 | stack s1, s2; 63 | s1.push(root); 64 | while(!s1.empty()) { 65 | TreeNode* pTemp = s1.top(); 66 | s1.pop(); 67 | s2.push(pTemp); //将节点依次放入s2栈中,之后再倒序即可 68 | if (pTemp->left) 69 | s1.push(pTemp->left); 70 | if (pTemp->right) 71 | s1.push(pTemp->right); 72 | } 73 | 74 | while (!s2.empty()) { 75 | resVec.push_back(s2.top()->val); 76 | s2.pop(); 77 | } 78 | 79 | return resVec; 80 | } 81 | }; 82 | -------------------------------------------------------------------------------- /Stack/llb/150. Evaluate Reverse Polish Notation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 4 | 5 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 6 | 7 | Some examples: 8 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 9 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 10 | 11 | 其实就是计算逆波兰数 12 | */ 13 | 14 | /* 15 | 思路:由于是数字运算,且都是二位运算。可以考虑简单的使用栈进行。 16 | 注意:注意弹出来的两个的值的运算顺序 17 | */ 18 | 19 | class Solution { 20 | public: 21 | int evalRPN(vector& tokens) { 22 | if (tokens.size() == 0) 23 | return 0; 24 | else if (tokens.size() == 1) 25 | return stoi(tokens[0]); 26 | 27 | stack numStack; 28 | for (int i=0; i < tokens.size(); ++i) { 29 | string token = tokens[i]; 30 | if (token == "+" || token == "-" || token == "*" || token == "/") { 31 | int num1 = numStack.top(); 32 | numStack.pop(); 33 | int num2 = numStack.top(); 34 | numStack.pop(); 35 | if (token == "+") 36 | numStack.push(num2 + num1); 37 | else if (token == "-") 38 | numStack.push(num2 - num1); 39 | else if (token == "*") 40 | numStack.push(num2 * num1); 41 | else if (token == "/") 42 | numStack.push(num2 / num1); 43 | } 44 | else { 45 | numStack.push(stoi(token)); 46 | } 47 | } 48 | 49 | return numStack.top(); 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Stack/llb/155. Min Stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | 利用栈实现最小栈 4 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 5 | 6 | push(x) -- Push element x onto stack. 7 | pop() -- Removes the element on top of the stack. 8 | top() -- Get the top element. 9 | getMin() -- Retrieve the minimum element in the stack. 10 | Example: 11 | MinStack minStack = new MinStack(); 12 | minStack.push(-2); 13 | minStack.push(0); 14 | minStack.push(-3); 15 | minStack.getMin(); --> Returns -3. 16 | minStack.pop(); 17 | minStack.top(); --> Returns 0. 18 | minStack.getMin(); --> Returns -2. 19 | */ 20 | 21 | class MinStack { 22 | private: 23 | stack s; 24 | stack sm; 25 | 26 | public: 27 | /** initialize your data structure here. */ 28 | //题意意思用栈实现最小栈 29 | 30 | MinStack() { 31 | 32 | } 33 | 34 | void push(int x) { 35 | s.push(x); 36 | if (sm.empty() || sm.top() >= x) { //注意等于也要入栈的 37 | sm.push(x); 38 | } 39 | } 40 | 41 | void pop() { 42 | if (sm.top() == s.top()) { 43 | sm.pop(); 44 | } 45 | s.pop(); 46 | } 47 | 48 | int top() { 49 | return s.top(); 50 | } 51 | 52 | int getMin() { 53 | return sm.top(); 54 | } 55 | }; 56 | 57 | /** 58 | * Your MinStack object will be instantiated and called as such: 59 | * MinStack obj = new MinStack(); 60 | * obj.push(x); 61 | * obj.pop(); 62 | * int param_3 = obj.top(); 63 | * int param_4 = obj.getMin(); 64 | */ 65 | -------------------------------------------------------------------------------- /Stack/llb/331. Verify Preorder Serialization of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. 4 | 5 | _9_ 6 | / \ 7 | 3 2 8 | / \ / \ 9 | 4 1 # 6 10 | / \ / \ / \ 11 | # # # # # # 12 | For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. 13 | 14 | Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree. 15 | 16 | Each comma separated value in the string must be either an integer or a character '#' representing null pointer. 17 | 18 | You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3". 19 | 20 | Example 1: 21 | "9,3,4,#,#,1,#,#,2,#,6,#,#" 22 | Return true 23 | 24 | Example 2: 25 | "1,#" 26 | Return false 27 | 28 | Example 3: 29 | "9,#,#,1" 30 | Return false 31 | 32 | */ 33 | 34 | /* 35 | 思路: 36 | 我们先发现规律: 37 | 1.数字的个数总比#少一个 38 | 2.最后一个一定是# 39 | 所以我们加入字符的时候不考虑最后一个#,所以此时数字和#那么总是相等的。 40 | 初始化一个为0的计数器,遇到数字加1,遇到#减一,合理的二叉树到最后计数器应该为0; 41 | 不能有连续三个及以上的#,如果计数器已经为0了,遇到#那就不对了(因为在正确的序列里,一个范围内的#是不可能大于数字的) 42 | */ 43 | 44 | class Solution { 45 | public: 46 | bool isValidSerialization(string preorder) { 47 | //先解析字符串 48 | istringstream in(preorder); 49 | vector v; 50 | string t = ""; 51 | int count = 0; 52 | while (getline(in, t, ',')) 53 | v.push_back(t); 54 | for (int i = 0; i < v.size()-1; i++) { 55 | if (v[i] == "#") { 56 | if (count == 0) 57 | return false; 58 | count--; 59 | } 60 | else { 61 | count++; 62 | } 63 | } 64 | 65 | if (count == 0 && v.back() == "#") { 66 | return true; 67 | } 68 | else { 69 | return false; 70 | } 71 | } 72 | }; 73 | -------------------------------------------------------------------------------- /Stack/llb/394. Decode String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an encoded string, return it's decoded string. 4 | 5 | The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. 6 | 7 | You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. 8 | 9 | Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. 10 | 11 | Examples: 12 | 13 | s = "3[a]2[bc]", return "aaabcbc". 14 | s = "3[a2[c]]", return "accaccacc". 15 | s = "2[abc]3[cd]ef", return "abcabccdcdcdef". 16 | 17 | 解析字符串 18 | */ 19 | 20 | /* 21 | 思路:借助递归的思想,找到每段括号内的字符。然后其他判断各类型的字符 22 | */ 23 | 24 | class Solution { 25 | public: 26 | string decodeString(string s) { 27 | int pos = 0; 28 | return helper(pos, s); 29 | } 30 | 31 | string helper(int &pos, string s) { 32 | int num = 0; //记录数字的值 33 | string word = ""; 34 | for (; pos < s.size(); pos++) { 35 | char cur = s[pos]; 36 | if (cur == '[') { 37 | string curStr = helper(++pos, s); //数字重复,递归调用获取[]内的字符串 38 | while (num > 0) { 39 | word += curStr; 40 | num--; 41 | } 42 | } 43 | else if (cur == ']') { 44 | return word; 45 | } 46 | else if (cur >= '0' && cur <= '9') { 47 | num = num*10 + cur - '0'; //cur转为数字 48 | } 49 | else { 50 | word += cur; 51 | } 52 | } 53 | return word; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /Stack/llb/71. Simplify Path.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an absolute path for a file (Unix-style), simplify it. 4 | 5 | For example, 6 | path = "/home/", => "/home" 7 | path = "/a/./b/../../c/", => "/c" 8 | click to show corner cases. 9 | 10 | Corner Cases: 11 | Did you consider the case where path = "/../"? 12 | In this case, you should return "/". 13 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 14 | In this case, you should ignore redundant slashes and return "/home/foo". 15 | */ 16 | 17 | /* 18 | 题目理解: 19 | 1.连续出现的'/',按照一个处理,即跳过重复的'/'; 20 | 2.如果是'.',则不处理; 21 | 3.如果出现'..',则需要弹栈,如果栈为空,则不处理; 22 | 4.如果为其他元素,则入栈。 23 | 最后,再逐个取出栈中元素(即已保存的路径名),用'/'分隔并连接起来,不过要注意顺序。 24 | */ 25 | 26 | class Solution { 27 | public: 28 | string simplifyPath(string path) { 29 | stack ss; 30 | for (int i=0; i < path.size(); ) { 31 | //1.跳过斜线 32 | while (i < path.size() && path[i] == '/') { 33 | ++i; 34 | } 35 | //记录下路径名 36 | string s = ""; 37 | while (i < path.size() && path[i] != '/') { 38 | s += path[i++]; 39 | } 40 | 41 | //..需要弹栈,其他入栈 42 | if (".." == s && !ss.empty()) { 43 | ss.pop(); 44 | } 45 | else if (s != "" && s != "." && s != "..") { 46 | ss.push(s); 47 | } 48 | } 49 | 50 | //中间条件判断, 51 | //如果栈为空,说明为根目录,只有斜线'/' 52 | if (ss.empty()) { 53 | return "/"; 54 | } 55 | 56 | //如果栈里有元素,那么再逐个链接栈里的元素 57 | string s = ""; 58 | while (!ss.empty()) { 59 | s = "/" + ss.top() + s; 60 | ss.pop(); 61 | } 62 | 63 | return s; 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /String/14_LongestCommonPrefix.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/longest-common-prefix/description. 6 | 题目描述: 7 | 8 | Write a function to find the longest common prefix string amongst an array of strings. 9 | 10 | """ 11 | 12 | 13 | class Solution(object): 14 | def longestCommonPrefix(self, strs): 15 | """ 16 | :type strs: List[str] 17 | :rtype: str 18 | """ 19 | pass 20 | -------------------------------------------------------------------------------- /String/151_ReverseWordsInAString.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/reverse-words-in-a-string/description. 6 | 题目描述: 7 | 8 | Given an input string, reverse the string word by word. 9 | 10 | For example, 11 | Given s = "the sky is blue", 12 | return "blue is sky the". 13 | 14 | Update (2015-02-12): 15 | For C programmers: Try to solve it in-place in O(1) space. 16 | 17 | click to show clarification. 18 | 19 | Clarification: 20 | What constitutes a word? 21 | A sequence of non-space characters constitutes a word. 22 | Could the input string contain leading or trailing spaces? 23 | Yes. However, your reversed string should not contain leading or trailing spaces. 24 | How about multiple spaces between two words? 25 | Reduce them to a single space in the reversed string. 26 | 27 | """ 28 | 29 | 30 | class Solution(object): 31 | def reverseWords(self, s): 32 | """ 33 | :type s: str 34 | :rtype: str 35 | """ 36 | pass 37 | -------------------------------------------------------------------------------- /String/165_CompareVersionNumbers.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/compare-version-numbers/description. 6 | 题目描述: 7 | 8 | Compare two version numbers version1 and version2. 9 | If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. 10 | 11 | You may assume that the version strings are non-empty and contain only digits and the . character. 12 | The . character does not represent a decimal point and is used to separate number sequences. 13 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of 14 | the second first-level revision. 15 | 16 | Here is an example of version numbers ordering: 17 | 18 | 0.1 < 1.1 < 1.2 < 13.37 19 | Credits: 20 | Special thanks to @ts for adding this problem and creating all test cases. 21 | 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def compareVersion(self, version1, version2): 27 | """ 28 | :type version1: str 29 | :type version2: str 30 | :rtype: int 31 | """ 32 | pass 33 | -------------------------------------------------------------------------------- /String/28_ImplementstrStr.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/implement-strstr/description. 6 | 题目描述: 7 | 8 | Implement strStr(). 9 | 10 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 11 | 12 | Example 1: 13 | 14 | Input: haystack = "hello", needle = "ll" 15 | Output: 2 16 | Example 2: 17 | 18 | Input: haystack = "aaaaa", needle = "bba" 19 | Output: -1 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def strStr_v1(self, haystack, needle): 26 | """ 27 | :type haystack: str 28 | :type needle: str 29 | :rtype: int 30 | """ 31 | if not needle: 32 | return 0 33 | 34 | la = len(haystack) 35 | lb = len(needle) 36 | 37 | for i in range(la - lb + 1): 38 | start = i 39 | for j in range(lb): 40 | if haystack[start] != needle[j]: 41 | break 42 | start += 1 43 | 44 | if start - i == lb: 45 | return i 46 | 47 | return -1 48 | -------------------------------------------------------------------------------- /String/344_ReverseString.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/reverse-string/description. 6 | 题目描述: 7 | 8 | Write a function that takes a string as input and returns the string reversed. 9 | 10 | Example: 11 | Given s = "hello", return "olleh". 12 | 13 | """ 14 | 15 | 16 | class Solution(object): 17 | def reverseString(self, s): 18 | """ 19 | :type s: str 20 | :rtype: str 21 | """ 22 | pass 23 | -------------------------------------------------------------------------------- /String/38_CountAndSay.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/count-and-say/description. 6 | 题目描述: 7 | 8 | The count-and-say sequence is the sequence of integers with the first five terms as following: 9 | 10 | 1. 1 11 | 2. 11 12 | 3. 21 13 | 4. 1211 14 | 5. 111221 15 | 1 is read off as "one 1" or 11. 16 | 11 is read off as "two 1s" or 21. 17 | 21 is read off as "one 2, then one 1" or 1211. 18 | Given an integer n, generate the nth term of the count-and-say sequence. 19 | 20 | Note: Each term of the sequence of integers will be represented as a string. 21 | 22 | Example 1: 23 | 24 | Input: 1 25 | Output: "1" 26 | Example 2: 27 | 28 | Input: 4 29 | Output: "1211" 30 | 31 | """ 32 | 33 | 34 | class Solution(object): 35 | def countAndSay(self, n): 36 | """ 37 | :type n: int 38 | :rtype: str 39 | """ 40 | pass 41 | -------------------------------------------------------------------------------- /String/58_LengthOfLastWord.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/length-of-last-word/description. 6 | 题目描述: 7 | 8 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last 9 | word in the string. 10 | 11 | If the last word does not exist, return 0. 12 | 13 | Note: A word is defined as a character sequence consists of non-space characters only. 14 | 15 | Example: 16 | 17 | Input: "Hello World" 18 | Output: 5 19 | 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def lengthOfLastWord(self, s): 25 | """ 26 | :type s: str 27 | :rtype: int 28 | """ 29 | if not s: 30 | return 0 31 | 32 | return len(s.strip().split(' ')[-1]) 33 | -------------------------------------------------------------------------------- /String/67_AddBinary.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/add-binary/description. 6 | 题目描述: 7 | 8 | Given two binary strings, return their sum (also a binary string). 9 | 10 | For example, 11 | a = "11" 12 | b = "1" 13 | Return "100". 14 | 15 | """ 16 | 17 | 18 | class Solution(object): 19 | def addBinary(self, a, b): 20 | """ 21 | :type a: str 22 | :type b: str 23 | :rtype: str 24 | """ 25 | if not a: 26 | return b 27 | if not b: 28 | return a 29 | 30 | result = [] 31 | la = len(a) 32 | lb = len(b) 33 | ll = min(la, lb) 34 | lr = max(la, lb) 35 | ra = a[::-1] 36 | rb = b[::-1] 37 | carry = 0 38 | 39 | for i in range(ll): 40 | vs = int(ra[i]) + int(rb[i]) + carry 41 | if vs >= 2: 42 | carry = 1 43 | else: 44 | carry = 0 45 | result.append(str(vs % 2)) 46 | 47 | for i in range(ll, lr): 48 | if lr == la: 49 | vs = int(ra[i]) + carry 50 | else: 51 | vs = int(rb[i]) + carry 52 | if vs >= 2: 53 | carry = 1 54 | else: 55 | carry = 0 56 | result.append(str(vs % 2)) 57 | 58 | if carry: 59 | result.append(str(carry)) 60 | 61 | result.reverse() 62 | 63 | return ''.join(result) 64 | -------------------------------------------------------------------------------- /String/68_TextJustification.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/text-justification/description. 6 | 题目描述: 7 | 8 | Given an array of words and a length L, format the text such that each line has exactly L characters and is fully 9 | (left and right) justified. 10 | 11 | You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra 12 | spaces ' ' when necessary so that each line has exactly L characters. 13 | 14 | Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not 15 | divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. 16 | 17 | For the last line of text, it should be left justified and no extra space is inserted between words. 18 | 19 | For example, 20 | words: ["This", "is", "an", "example", "of", "text", "justification."] 21 | L: 16. 22 | 23 | Return the formatted lines as: 24 | [ 25 | "This is an", 26 | "example of text", 27 | "justification. " 28 | ] 29 | Note: Each word is guaranteed not to exceed L in length. 30 | 31 | click to show corner cases. 32 | 33 | Corner Cases: 34 | A line other than the last line might contain only one word. What should you do in this case? 35 | In this case, that line should be left-justified. 36 | 37 | """ 38 | 39 | 40 | class Solution(object): 41 | def fullJustify(self, words, maxWidth): 42 | """ 43 | :type words: List[str] 44 | :type maxWidth: int 45 | :rtype: List[str] 46 | """ 47 | pass 48 | -------------------------------------------------------------------------------- /String/6_ZigZagConversion.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/zigzag-conversion/description. 6 | 题目描述: 7 | 8 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to 9 | display this pattern in a fixed font for better legibility) 10 | 11 | P A H N 12 | A P L S I I G 13 | Y I R 14 | 15 | And then read line by line: "PAHNAPLSIIGYIR" 16 | Write the code that will take a string and make this conversion given a number of rows: 17 | 18 | string convert(string text, int nRows); 19 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def convert(self, s, numRows): 26 | """ 27 | :type s: str 28 | :type numRows: int 29 | :rtype: str 30 | """ 31 | pass 32 | -------------------------------------------------------------------------------- /String/8_StringToInteger.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/string-to-integer-atoi/description. 6 | 题目描述: 7 | 8 | Implement atoi to convert a string to an integer. 9 | 10 | Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself 11 | what are the possible input cases. 12 | 13 | Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to 14 | gather all the input requirements up front. 15 | 16 | Update (2015-02-10): 17 | The signature of the C++ function had been updated. If you still see your function signature accepts a const char * 18 | argument, please click the reload button to reset your code definition. 19 | 20 | spoilers alert... click to show requirements for atoi. 21 | 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def myAtoi(self, str): 27 | """ 28 | :type str: str 29 | :rtype: int 30 | """ 31 | pass 32 | -------------------------------------------------------------------------------- /Tree/102_BinaryTreeLevelOrderTraversal.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/binary-tree-level-order-traversal/description. 6 | 题目描述: 7 | 8 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by 9 | level). 10 | 11 | For example: 12 | Given binary tree [3,9,20,null,null,15,7], 13 | 3 14 | / \ 15 | 9 20 16 | / \ 17 | 15 7 18 | return its level order traversal as: 19 | [ 20 | [3], 21 | [9,20], 22 | [15,7] 23 | ] 24 | 25 | """ 26 | 27 | 28 | # Definition for a binary tree node. 29 | class TreeNode(object): 30 | def __init__(self, x): 31 | self.val = x 32 | self.left = None 33 | self.right = None 34 | 35 | 36 | class Solution(object): 37 | def levelOrder(self, root): 38 | """ 39 | :type root: TreeNode 40 | :rtype: List[List[int]] 41 | """ 42 | if not root: 43 | return [] 44 | 45 | queue = [] 46 | ans = [] 47 | # 非递归解法 48 | # 模拟队列, 辅助变量: 记录队列头尾节点 49 | front = 0 50 | rear = 1 51 | queue.append(root) 52 | 53 | while front < rear: 54 | # 记录上一层节点数 55 | last = rear 56 | level = [] 57 | while front < last: 58 | root = queue[front] 59 | level.append(root.val) 60 | front += 1 61 | # 左右子树入队 62 | if root.left: 63 | queue.append(root.left) 64 | rear += 1 65 | if root.right: 66 | queue.append(root.right) 67 | rear += 1 68 | 69 | ans.append(level) 70 | 71 | return ans 72 | -------------------------------------------------------------------------------- /Tree/104_MaximumDepthOfBinaryTree.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/maximum-depth-of-binary-tree/description. 6 | 题目描述: 7 | 8 | Given a binary tree, find its maximum depth. 9 | 10 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 11 | 12 | For example: 13 | Given binary tree [3,9,20,null,null,15,7], 14 | 15 | 3 16 | / \ 17 | 9 20 18 | / \ 19 | 15 7 20 | return its depth = 3. 21 | 22 | """ 23 | 24 | 25 | # Definition for a binary tree node. 26 | class TreeNode(object): 27 | def __init__(self, x): 28 | self.val = x 29 | self.left = None 30 | self.right = None 31 | 32 | 33 | class Solution(object): 34 | def maxDepth(self, root): 35 | """ 36 | :type root: TreeNode 37 | :rtype: int 38 | """ 39 | if not root: 40 | return 0 41 | 42 | # return self.recursive_tree_of_max_depth(root) 43 | return self.iterative_tree_of_max_depth(root) 44 | 45 | # 递归解法, 基本操作 46 | def recursive_tree_of_max_depth(self, root): 47 | if not root: 48 | return 0 49 | 50 | return max(self.recursive_tree_of_max_depth(root.left), self.recursive_tree_of_max_depth(root.right)) + 1 51 | 52 | # 非递归解法 53 | # 类似于二叉树的层序遍历 54 | def iterative_tree_of_max_depth(self, root): 55 | queue = [] 56 | front = 0 57 | rear = 1 58 | depth = 0 59 | queue.append(root) 60 | 61 | while front < rear: 62 | last = rear 63 | while front < last: 64 | root = queue[front] 65 | front += 1 66 | if root.left: 67 | queue.append(root.left) 68 | rear += 1 69 | if root.right: 70 | queue.append(root.right) 71 | rear += 1 72 | 73 | # 整层访问完毕 74 | depth += 1 75 | 76 | return depth 77 | -------------------------------------------------------------------------------- /Tree/105_ConstructBinaryTreeFromPreorderAndInorderTraversal.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description. 6 | 题目描述: 7 | 8 | Given preorder and inorder traversal of a tree, construct the binary tree. 9 | 10 | Note: 11 | You may assume that duplicates do not exist in the tree. 12 | 13 | For example, given 14 | 15 | preorder = [3,9,20,15,7] 16 | inorder = [9,3,15,20,7] 17 | Return the following binary tree: 18 | 19 | 3 20 | / \ 21 | 9 20 22 | / \ 23 | 15 7 24 | 25 | """ 26 | 27 | 28 | # Definition for a binary tree node. 29 | class TreeNode(object): 30 | def __init__(self, x): 31 | self.val = x 32 | self.left = None 33 | self.right = None 34 | 35 | 36 | class Solution(object): 37 | def buildTree(self, preorder, inorder): 38 | """ 39 | :type preorder: List[int] 40 | :type inorder: List[int] 41 | :rtype: TreeNode 42 | """ 43 | if not preorder or not inorder: 44 | return None 45 | 46 | return self.construct_tree_with_preorder_and_inorder(preorder, inorder, 0, len(preorder) - 1, 47 | 0, len(inorder) - 1) 48 | 49 | def construct_tree_with_preorder_and_inorder(self, preorder, inorder, pb, pe, ib, ie): 50 | if pb > pe: 51 | return None 52 | 53 | # 查找该节点在中序序列中的索引 54 | # 递归构造左右子树 55 | idx = inorder.index(preorder[pb]) 56 | left = self.construct_tree_with_preorder_and_inorder(preorder, inorder, pb + 1, pb + idx - ib, ib, idx - 1) 57 | right = self.construct_tree_with_preorder_and_inorder(preorder, inorder, pb + idx - ib + 1, pe, idx + 1, ie) 58 | root = TreeNode(preorder[pb]) 59 | root.left, root.right = left, right 60 | 61 | return root 62 | -------------------------------------------------------------------------------- /Tree/106_ConstructBinaryTreeFromInorderAndPostorderTraversal.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description. 6 | 题目描述: 7 | 8 | Given inorder and postorder traversal of a tree, construct the binary tree. 9 | 10 | Note: 11 | You may assume that duplicates do not exist in the tree. 12 | 13 | For example, given 14 | 15 | inorder = [9,3,15,20,7] 16 | postorder = [9,15,7,20,3] 17 | Return the following binary tree: 18 | 19 | 3 20 | / \ 21 | 9 20 22 | / \ 23 | 15 7 24 | 25 | """ 26 | 27 | 28 | # Definition for a binary tree node. 29 | class TreeNode(object): 30 | def __init__(self, x): 31 | self.val = x 32 | self.left = None 33 | self.right = None 34 | 35 | 36 | class Solution(object): 37 | def buildTree(self, inorder, postorder): 38 | """ 39 | :type inorder: List[int] 40 | :type postorder: List[int] 41 | :rtype: TreeNode 42 | """ 43 | if not inorder or not postorder: 44 | return None 45 | 46 | return self.construct_tree_with_inorder_and_postorder(inorder, postorder, 0, len(inorder) - 1, 47 | 0, len(postorder) - 1) 48 | 49 | def construct_tree_with_inorder_and_postorder(self, inorder, postorder, ib, ie, pb, pe): 50 | if pb > pe: 51 | return None 52 | 53 | # 查找该节点在中序序列中的索引 54 | # 递归构造左右子树 55 | idx = inorder.index(postorder[pe]) 56 | left = self.construct_tree_with_inorder_and_postorder(inorder, postorder, ib, idx - 1, pb, pb + idx - ib - 1) 57 | right = self.construct_tree_with_inorder_and_postorder(inorder, postorder, idx + 1, ie, pb + idx - ib, pe - 1) 58 | root = TreeNode(postorder[pe]) 59 | root.left, root.right = left, right 60 | 61 | return root 62 | -------------------------------------------------------------------------------- /Tree/108_ConvertSortedArrayToBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description. 6 | 题目描述: 7 | 8 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 9 | 10 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees 11 | of every node never differ by more than 1. 12 | 13 | 14 | Example: 15 | 16 | Given the sorted array: [-10,-3,0,5,9], 17 | 18 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 19 | 20 | 0 21 | / \ 22 | -3 9 23 | / / 24 | -10 5 25 | 26 | """ 27 | 28 | 29 | # Definition for a binary tree node. 30 | class TreeNode(object): 31 | def __init__(self, x): 32 | self.val = x 33 | self.left = None 34 | self.right = None 35 | 36 | 37 | class Solution(object): 38 | def sortedArrayToBST(self, nums): 39 | """ 40 | :type nums: List[int] 41 | :rtype: TreeNode 42 | """ 43 | return self.construct_binary_search_tree(nums, 0, len(nums) - 1) 44 | 45 | # 二分, 递归建立二叉搜索树 46 | def construct_binary_search_tree(self, nums, nl, nr): 47 | if nl > nr: 48 | return None 49 | 50 | mid = nl + (nr - nl) / 2 51 | left = self.construct_binary_search_tree(nums, nl, mid - 1) 52 | right = self.construct_binary_search_tree(nums, mid + 1, nr) 53 | root = TreeNode(nums[mid]) 54 | root.left, root.right = left, right 55 | 56 | return root 57 | -------------------------------------------------------------------------------- /Tree/109_ConvertSortedListToBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description. 6 | 题目描述: 7 | Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 8 | 9 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees 10 | of every node never differ by more than 1. 11 | 12 | 13 | Example: 14 | 15 | Given the sorted linked list: [-10,-3,0,5,9], 16 | 17 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 18 | 19 | 0 20 | / \ 21 | -3 9 22 | / / 23 | -10 5 24 | 25 | """ 26 | 27 | 28 | # Definition for singly-linked list. 29 | class ListNode(object): 30 | def __init__(self, x): 31 | self.val = x 32 | self.next = None 33 | 34 | 35 | # Definition for a binary tree node. 36 | class TreeNode(object): 37 | def __init__(self, x): 38 | self.val = x 39 | self.left = None 40 | self.right = None 41 | 42 | 43 | class Solution(object): 44 | def sortedListToBST(self, head): 45 | """ 46 | :type head: ListNode 47 | :rtype: TreeNode 48 | """ 49 | return self.construct_binary_search_tree_with_fast_snow_pointers(head, None) 50 | 51 | # 快慢指针, 建立二叉搜索树 52 | def construct_binary_search_tree_with_fast_snow_pointers(self, head, last): 53 | if head == last: 54 | return None 55 | 56 | fast = snow = head 57 | while fast != last and fast.next != last: 58 | snow, fast = snow.next, fast.next.next 59 | 60 | left = self.construct_binary_search_tree_with_fast_snow_pointers(head, snow) 61 | right = self.construct_binary_search_tree_with_fast_snow_pointers(snow.next, last) 62 | root = TreeNode(snow.val) 63 | root.left, root.right = left, right 64 | 65 | return root 66 | -------------------------------------------------------------------------------- /Tree/110_BalancedBinaryTree.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/balanced-binary-tree/description. 6 | 题目描述: 7 | 8 | Given a binary tree, determine if it is height-balanced. 9 | 10 | For this problem, a height-balanced binary tree is defined as: 11 | 12 | a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 13 | 14 | Example 1: 15 | 16 | Given the following tree [3,9,20,null,null,15,7]: 17 | 18 | 3 19 | / \ 20 | 9 20 21 | / \ 22 | 15 7 23 | Return true. 24 | 25 | Example 2: 26 | 27 | Given the following tree [1,2,2,3,3,null,null,4,4]: 28 | 29 | 1 30 | / \ 31 | 2 2 32 | / \ 33 | 3 3 34 | / \ 35 | 4 4 36 | Return false. 37 | 38 | """ 39 | 40 | 41 | # Definition for a binary tree node. 42 | class TreeNode(object): 43 | def __init__(self, x): 44 | self.val = x 45 | self.left = None 46 | self.right = None 47 | 48 | 49 | class Solution(object): 50 | def isBalanced(self, root): 51 | """ 52 | :type root: TreeNode 53 | :rtype: bool 54 | """ 55 | if not root: 56 | return True 57 | 58 | return self.isBalanced(root.left) and self.isBalanced(root.right) and abs( 59 | self.recursive_tree_of_depth(root.left) - self.recursive_tree_of_depth(root.right)) <= 1 60 | 61 | def recursive_tree_of_depth(self, root): 62 | if not root: 63 | return 0 64 | 65 | return max(self.recursive_tree_of_depth(root.left), self.recursive_tree_of_depth(root.right)) + 1 66 | -------------------------------------------------------------------------------- /Tree/112_PathSum.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/path-sum/description. 6 | 题目描述: 7 | 8 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values 9 | along the path equals the given sum. 10 | 11 | For example: 12 | Given the below binary tree and sum = 22, 13 | 5 14 | / \ 15 | 4 8 16 | / / \ 17 | 11 13 4 18 | / \ \ 19 | 7 2 1 20 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 21 | 22 | """ 23 | 24 | 25 | # Definition for a binary tree node. 26 | class TreeNode(object): 27 | def __init__(self, x): 28 | self.val = x 29 | self.left = None 30 | self.right = None 31 | 32 | 33 | class Solution(object): 34 | def hasPathSum(self, root, sum): 35 | """ 36 | :type root: TreeNode 37 | :type sum: int 38 | :rtype: bool 39 | """ 40 | if not root: 41 | return False 42 | 43 | if not root.left and not root.right: 44 | return root.val == sum 45 | 46 | return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) 47 | -------------------------------------------------------------------------------- /Tree/113_PathSumII.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/path-sum-ii/description. 6 | 题目描述: 7 | 8 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 9 | 10 | For example: 11 | Given the below binary tree and sum = 22, 12 | 5 13 | / \ 14 | 4 8 15 | / / \ 16 | 11 13 4 17 | / \ / \ 18 | 7 2 5 1 19 | return 20 | [ 21 | [5,4,11,2], 22 | [5,8,4,5] 23 | ] 24 | 25 | """ 26 | 27 | 28 | # Definition for a binary tree node. 29 | class TreeNode(object): 30 | def __init__(self, x): 31 | self.val = x 32 | self.left = None 33 | self.right = None 34 | 35 | 36 | class Solution(object): 37 | def pathSum(self, root, sum): 38 | """ 39 | :type root: TreeNode 40 | :type sum: int 41 | :rtype: List[List[int]] 42 | """ 43 | if not root: 44 | return [] 45 | 46 | ans = [] 47 | sub = [] 48 | self.recursive_path_sum(root, sum, sub, ans) 49 | 50 | return ans 51 | 52 | def recursive_path_sum(self, root, sum, sub, ans): 53 | sub.append(root.val) 54 | if not root.left and not root.right and sum == root.val: 55 | ans.append(sub[:]) 56 | if root.left: 57 | self.recursive_path_sum(root.left, sum - root.val, sub, ans) 58 | if root.right: 59 | self.recursive_path_sum(root.right, sum - root.val, sub, ans) 60 | sub.pop() 61 | -------------------------------------------------------------------------------- /Tree/145_BinaryTreePostorderTraversal.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/binary-tree-postorder-traversal/description. 6 | 题目描述: 7 | 8 | Given a binary tree, return the postorder traversal of its nodes' values. 9 | 10 | For example: 11 | Given binary tree [1,null,2,3], 12 | 13 | 1 14 | \ 15 | 2 16 | / 17 | 3 18 | 19 | return [3,2,1]. 20 | 21 | Note: Recursive solution is trivial, could you do it iteratively? 22 | 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | class TreeNode(object): 28 | def __init__(self, x): 29 | self.val = x 30 | self.left = None 31 | self.right = None 32 | 33 | 34 | class Solution(object): 35 | def postorderTraversal(self, root): 36 | """ 37 | :type root: TreeNode 38 | :rtype: List[int] 39 | """ 40 | ans = [] 41 | self.recursive_postorder(root, ans) 42 | self.iterative_postorder(root, ans) 43 | 44 | return ans 45 | 46 | # 递归解法, 基本操作 47 | def recursive_postorder(self, root, ans): 48 | if not root: 49 | return 50 | 51 | self.recursive_postorder(root.left, ans) 52 | self.recursive_postorder(root.right, ans) 53 | ans.append(root.val) 54 | 55 | # 非递归解法 56 | # 需要加一个辅助变量, 标志上次访问的节点 57 | def iterative_postorder(self, root, ans): 58 | stack = [] 59 | last_visit_node = root 60 | while root or stack: 61 | while root: 62 | stack.append(root) 63 | root = root.left 64 | 65 | # 该节点的右子树为空或右子树已访问, 出栈 66 | # 否则, 继续遍历右子树 67 | root = stack[-1] 68 | if not root.right or root.right == last_visit_node: 69 | ans.append(root.val) 70 | stack.pop() 71 | last_visit_node = root 72 | root = None 73 | else: 74 | root = root.right 75 | -------------------------------------------------------------------------------- /Tree/173_BinarySearchTreeIterator.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/binary-search-tree-iterator/description. 6 | 题目描述: 7 | 8 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a 9 | BST. 10 | 11 | Calling next() will return the next smallest number in the BST. 12 | 13 | Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 14 | 15 | Credits: 16 | Special thanks to @ts for adding this problem and creating all test cases. 17 | 18 | """ 19 | 20 | 21 | # Definition for a binary tree node 22 | class TreeNode(object): 23 | def __init__(self, x): 24 | self.val = x 25 | self.left = None 26 | self.right = None 27 | 28 | 29 | class BSTIterator(object): 30 | def __init__(self, root): 31 | """ 32 | :type root: TreeNode 33 | """ 34 | self.stack = [] 35 | while root: 36 | self.stack.append(root) 37 | root = root.left 38 | 39 | def hasNext(self): 40 | """ 41 | :rtype: bool 42 | """ 43 | return True if self.stack else False 44 | 45 | def next(self): 46 | """ 47 | :rtype: int 48 | """ 49 | root = self.stack.pop() 50 | right = root.right 51 | while right: 52 | self.stack.append(right) 53 | right = right.left 54 | 55 | return root.val 56 | 57 | # Your BSTIterator will be called like this: 58 | # i, v = BSTIterator(root), [] 59 | # while i.hasNext(): v.append(i.next()) 60 | -------------------------------------------------------------------------------- /Tree/222_CountCompleteTreeNodes.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/count-complete-tree-nodes/description. 6 | 题目描述: 7 | 8 | Given a complete binary tree, count the number of nodes. 9 | 10 | Definition of a complete binary tree from Wikipedia: 11 | In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last 12 | level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 13 | 14 | """ 15 | 16 | 17 | # Definition for a binary tree node. 18 | class TreeNode(object): 19 | def __init__(self, x): 20 | self.val = x 21 | self.left = None 22 | self.right = None 23 | 24 | 25 | class Solution(object): 26 | def countNodes(self, root): 27 | """ 28 | :type root: TreeNode 29 | :rtype: int 30 | """ 31 | if not root: 32 | return 0 33 | 34 | # 满二叉树, 直接返回 35 | # 不然, leetcode大数据样例通不过测试 36 | lh = self.left_tree_height(root) 37 | rh = self.right_tree_height(root) 38 | if lh == rh: 39 | return pow(2, lh) - 1 40 | 41 | return 1 + self.countNodes(root.left) + self.countNodes(root.right) 42 | 43 | def left_tree_height(self, root): 44 | if not root: 45 | return 0 46 | 47 | return 1 + self.left_tree_height(root.left) 48 | 49 | def right_tree_height(self, root): 50 | if not root: 51 | return 0 52 | 53 | return 1 + self.right_tree_height(root.right) 54 | -------------------------------------------------------------------------------- /Tree/235_LowestCommonAncestorOfABinarySearchTree.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description. 6 | 题目描述: 7 | 8 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 9 | 10 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w 11 | as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 12 | 13 | _______6______ 14 | / \ 15 | ___2__ ___8__ 16 | / \ / \ 17 | 0 _4 7 9 18 | / \ 19 | 3 5 20 | For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, 21 | since a node can be a descendant of itself according to the LCA definition. 22 | 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | class TreeNode(object): 28 | def __init__(self, x): 29 | self.val = x 30 | self.left = None 31 | self.right = None 32 | 33 | 34 | class Solution(object): 35 | def lowestCommonAncestor(self, root, p, q): 36 | """ 37 | :type root: TreeNode 38 | :type p: TreeNode 39 | :type q: TreeNode 40 | :rtype: TreeNode 41 | """ 42 | if not root: 43 | return None 44 | 45 | # 公共祖先节点位于左子树中 46 | if root.val > max(p.val, q.val): 47 | return self.lowestCommonAncestor(root.left, p, q) 48 | # 公共祖先节点位于右子树中 49 | elif root.val < min(p.val, q.val): 50 | return self.lowestCommonAncestor(root.right, p, q) 51 | 52 | return root 53 | -------------------------------------------------------------------------------- /Tree/236_LowestCommonAncestorOfABinaryTree.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description. 6 | 题目描述: 7 | 8 | Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 9 | 10 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w 11 | as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 12 | 13 | _______3______ 14 | / \ 15 | ___5__ ___1__ 16 | / \ / \ 17 | 6 _2 0 8 18 | / \ 19 | 7 4 20 | For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, 21 | since a node can be a descendant of itself according to the LCA definition. 22 | 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | class TreeNode(object): 28 | def __init__(self, x): 29 | self.val = x 30 | self.left = None 31 | self.right = None 32 | 33 | 34 | class Solution(object): 35 | def lowestCommonAncestor(self, root, p, q): 36 | """ 37 | :type root: TreeNode 38 | :type p: TreeNode 39 | :type q: TreeNode 40 | :rtype: TreeNode 41 | """ 42 | if root in (None, p, q): 43 | return root 44 | 45 | left = self.lowestCommonAncestor(root.left, p, q) 46 | right = self.lowestCommonAncestor(root.right, p, q) 47 | if left and right: 48 | return root 49 | 50 | return left if left else right 51 | -------------------------------------------------------------------------------- /Tree/257_BinaryTreePaths.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/binary-tree-paths/description. 6 | 题目描述: 7 | 8 | Given a binary tree, return all root-to-leaf paths. 9 | 10 | For example, given the following binary tree: 11 | 12 | 1 13 | / \ 14 | 2 3 15 | \ 16 | 5 17 | All root-to-leaf paths are: 18 | 19 | ["1->2->5", "1->3"] 20 | Credits: 21 | Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 22 | 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | class TreeNode(object): 28 | def __init__(self, x): 29 | self.val = x 30 | self.left = None 31 | self.right = None 32 | 33 | 34 | class Solution(object): 35 | def binaryTreePaths(self, root): 36 | """ 37 | :type root: TreeNode 38 | :rtype: List[str] 39 | """ 40 | if not root: 41 | return [] 42 | 43 | ans = [] 44 | self.recursive_tree_path(root, '', ans) 45 | 46 | return ans 47 | 48 | def recursive_tree_path(self, root, path, ans): 49 | if not root.left and not root.right: 50 | ans.append(path + root.val) 51 | if root.left: 52 | self.recursive_tree_path(root.left, path + str(root.val) + '->', ans) 53 | if root.right: 54 | self.recursive_tree_path(root.right, path + str(root.val) + '->', ans) 55 | -------------------------------------------------------------------------------- /Tree/llb/104. Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述 3 | Given a binary tree, find its maximum depth. 4 | 5 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | 7 | For example: 8 | Given binary tree [3,9,20,null,null,15,7], 9 | 10 | 3 11 | / \ 12 | 9 20 13 | / \ 14 | 15 7 15 | return its depth = 3 16 | 17 | */ 18 | 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * struct TreeNode { 23 | * int val; 24 | * TreeNode *left; 25 | * TreeNode *right; 26 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | 32 | //计算树的深度 33 | //思路一:递归 34 | /* 35 | int maxDepth(TreeNode* root) { 36 | if (root == NULL) 37 | return 0; 38 | 39 | int leftDepth = maxDepth(root->left); 40 | int rightDepth = maxDepth(root->right); 41 | int depth = 1 + max(leftDepth, rightDepth); 42 | return depth; 43 | } 44 | */ 45 | 46 | //思路二:利用层序遍历计算(每层把自己的层的node全循环一遍,记到queue中,然后在该层全部弹出来,并且把下层的节点全部保存进去) 47 | int maxDepth(TreeNode* root) { 48 | if (root == NULL) 49 | return 0; 50 | int depth = 0; 51 | queue q; 52 | q.push(root); 53 | while (!q.empty()) { 54 | depth++; 55 | int n = q.size(); //计算当前层的节点数,然后每个弹出来,再加入下层的所有节点 56 | for (int i=0; ileft) 60 | q.push(temp->left); 61 | if (temp->right) 62 | q.push(temp->right); 63 | } 64 | } 65 | 66 | return depth; 67 | } 68 | 69 | 70 | 71 | 72 | }; 73 | -------------------------------------------------------------------------------- /Tree/llb/108. Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 4 | 5 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 6 | 7 | 8 | Example: 9 | 10 | Given the sorted array: [-10,-3,0,5,9], 11 | 12 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 13 | 14 | 0 15 | / \ 16 | -3 9 17 | / / 18 | -10 5 19 | */ 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | 33 | //思路:二叉搜索树始终满足:左<根<右, 34 | //所以,每次找到中间节点M,然后小于M的就是左子树,大于M的就是右子树。 35 | //然后模拟中序遍历生成树。 36 | 37 | TreeNode* sortedArrayToBST(vector& nums) { 38 | return doSortArrayToBST(nums, 0, nums.size()-1); 39 | } 40 | 41 | TreeNode* doSortArrayToBST(vector& nums, int left, int right) { 42 | if (left > right) 43 | return NULL; 44 | 45 | int mid = (left + right) / 2; 46 | //生成当前节点 47 | TreeNode* node = new TreeNode(nums[mid]); 48 | node->left = doSortArrayToBST(nums, left, mid-1); 49 | node->right = doSortArrayToBST(nums, mid+1, right); 50 | return node; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /Tree/llb/110. Balanced Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a binary tree, determine if it is height-balanced. 4 | 5 | For this problem, a height-balanced binary tree is defined as: 6 | 7 | a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 8 | 9 | Example 1: 10 | 11 | Given the following tree [3,9,20,null,null,15,7]: 12 | 13 | 3 14 | / \ 15 | 9 20 16 | / \ 17 | 15 7 18 | Return true. 19 | 20 | Example 2: 21 | 22 | Given the following tree [1,2,2,3,3,null,null,4,4]: 23 | 24 | 1 25 | / \ 26 | 2 2 27 | / \ 28 | 3 3 29 | / \ 30 | 4 4 31 | Return false. 32 | */ 33 | 34 | /** 35 | * Definition for a binary tree node. 36 | * struct TreeNode { 37 | * int val; 38 | * TreeNode *left; 39 | * TreeNode *right; 40 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 41 | * }; 42 | */ 43 | class Solution { 44 | public: 45 | 46 | //思考:还是要利用递归的思想,写个递归计算深度的方法,然后递归判断左右子树的方法 47 | 48 | bool isBalanced(TreeNode* root) { 49 | if (root == NULL) 50 | return true; 51 | 52 | int leftDepth = getDepth(root->left); 53 | int rightDepth = getDepth(root->right); 54 | 55 | return abs(leftDepth-rightDepth) <= 1 && isBalanced(root->left) && isBalanced(root->right); 56 | } 57 | 58 | int getDepth(TreeNode* root) { 59 | if (root == NULL) 60 | return 0; 61 | 62 | return max(getDepth(root->left), getDepth(root->right)) + 1; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /Tree/llb/111. Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a binary tree, find its minimum depth. 4 | 5 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 6 | */ 7 | 8 | /*思考: 9 | 因为如果一个节点如果只有左子树或者右子树,我们不能取它左右子树中小的作为深度,因为那样会是0。 10 | 我们只有在叶子节点才能判断深度,当左右子树都为空时才是叶子节点。 11 | */ 12 | 13 | 14 | /** 15 | * Definition for a binary tree node. 16 | * struct TreeNode { 17 | * int val; 18 | * TreeNode *left; 19 | * TreeNode *right; 20 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 21 | * }; 22 | */ 23 | class Solution { 24 | public: 25 | 26 | /*思考:因为如果一个节点如果只有左子树或者右子树,我们不能取它左右子树中小的作为深度,因为那样会是0。 27 | 我们只有在叶子节点才能判断深度,当左右子树都为空时才是叶子节点。 28 | */ 29 | 30 | //思路一:层序遍历,计算深度,直到出现某个节点的左右孩子都为NULL时,终止循环。 31 | /* 32 | int minDepth(TreeNode* root) { 33 | if (root == NULL) 34 | return 0; 35 | 36 | queue q; 37 | int depth = 0; 38 | q.push(root); 39 | while (!q.empty()) { 40 | depth++; 41 | int n = q.size(); 42 | for (int i=0; ileft) 46 | q.push(pTemp->left); 47 | if (pTemp->right) 48 | q.push(pTemp->right); 49 | if (!pTemp->left && !pTemp->right) 50 | return depth; 51 | } 52 | } 53 | } 54 | */ 55 | 56 | //思路二:利用递归的思想。 57 | int minDepth(TreeNode* root) { 58 | if (root == NULL) 59 | return 0; 60 | if (root->left == NULL) 61 | return minDepth(root->right) + 1; 62 | if (root->right == NULL) 63 | return minDepth(root->left) + 1; 64 | return min(minDepth(root->left), minDepth(root->right)) + 1; 65 | } 66 | 67 | }; 68 | -------------------------------------------------------------------------------- /Tree/llb/112. Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 7 | 5 8 | / \ 9 | 4 8 10 | / / \ 11 | 11 13 4 12 | / \ \ 13 | 7 2 1 14 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 15 | */ 16 | 17 | /*考虑 18 | 利用递归,对于每个根节点,只要左子树和右子树中有一个满足,就返回true; 19 | 每次访问一个节点,就将sum-该节点的val,作为新的Sum进行下一层的判断。 20 | 直到叶子节点,且sum与节点val相等,则表示存在这样的path,返回true. 21 | */ 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * struct TreeNode { 26 | * int val; 27 | * TreeNode *left; 28 | * TreeNode *right; 29 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 30 | * }; 31 | */ 32 | class Solution { 33 | public: 34 | bool hasPathSum(TreeNode* root, int sum) { 35 | if (!root) 36 | return false; 37 | if (!root->left && !root->right) 38 | return sum == root->val; 39 | 40 | return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val); 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Tree/llb/113. Path Sum II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 4 | 5 | For example: 6 | Given the below binary tree and sum = 22, 7 | 5 8 | / \ 9 | 4 8 10 | / / \ 11 | 11 13 4 12 | / \ / \ 13 | 7 2 5 1 14 | return 15 | [ 16 | [5,4,11,2], 17 | [5,8,4,5] 18 | ] 19 | */ 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | vector> pathSum(TreeNode* root, int sum) { 33 | vector> res; 34 | vector vec; 35 | help(root, sum, vec, res); 36 | return res; 37 | } 38 | 39 | void help(TreeNode* root, int sum, vector vec, vector> &res) { 40 | if (!root) { 41 | return; 42 | } 43 | 44 | //叶子节点并且值相等就结束 45 | if (!root->left && !root->right && root->val == sum) { 46 | vec.push_back(root->val); 47 | res.push_back(vec); 48 | return; 49 | } 50 | 51 | //非叶子节点都要添加进来 52 | vec.push_back(root->val); 53 | if (root->left) { 54 | help(root->left, sum-root->val, vec, res); 55 | } 56 | if (root->right) { 57 | help(root->right, sum-root->val, vec, res); 58 | } 59 | 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /Tree/llb/144. Binary Tree Preorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | 4 | Given a binary tree, return the preorder traversal of its nodes' values. 5 | 6 | For example: 7 | Given binary tree [1,null,2,3], 8 | 1 9 | \ 10 | 2 11 | / 12 | 3 13 | return [1,2,3]. 14 | */ 15 | 16 | 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | //前序遍历:根->左->右 30 | 31 | //思路一:递归 32 | // vector preorderTraversal(TreeNode* root) { 33 | // vector resVec; 34 | // preorder(root, resVec); 35 | // return resVec; 36 | // } 37 | 38 | // void preorder(TreeNode* root, vector &vec) { 39 | // if (root == NULL) { 40 | // return; 41 | // } 42 | 43 | // vec.push_back(root->val); 44 | // preorder(root->left, vec); 45 | // preorder(root->right, vec); 46 | // } 47 | 48 | //思路二:利用栈。 49 | //1.把根节点压入到栈中。 50 | //2.循环检测栈是否为空,若不为空,则取出栈顶元素,保存值。 51 | //3.判断该值的右子树是否为空,若存在则push到栈中。再判断其左子树是否为空,若存在则push到栈中。 52 | vector preorderTraversal(TreeNode* root) { 53 | if (root == NULL) { 54 | return {}; 55 | } 56 | 57 | vector resVec; 58 | stack s; 59 | s.push(root); 60 | while (!s.empty()) { 61 | TreeNode* pTemp = s.top(); 62 | s.pop(); 63 | resVec.push_back(pTemp->val); 64 | if (pTemp->right) 65 | s.push(pTemp->right); 66 | if (pTemp->left) 67 | s.push(pTemp->left); 68 | } 69 | 70 | return resVec; 71 | } 72 | 73 | 74 | }; 75 | -------------------------------------------------------------------------------- /Tree/llb/145. Binary Tree Postorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /*\ 2 | 问题描述: 3 | Given a binary tree, return the postorder traversal of its nodes' values. 4 | 5 | For example: 6 | Given binary tree [1,null,2,3], 7 | 8 | 1 9 | \ 10 | 2 11 | / 12 | 3 13 | 14 | 15 | return [3,2,1]. 16 | */ 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | 30 | //思路一:递归 31 | // vector postorderTraversal(TreeNode* root) { 32 | // vector vec; 33 | // postorder(root, vec); 34 | // return vec; 35 | // } 36 | 37 | // void postorder(TreeNode* root, vector &vec) { 38 | // if (root == NULL) { 39 | // return; 40 | // } 41 | 42 | // postorder(root->left, vec); 43 | // postorder(root->right, vec); 44 | // vec.push_back(root->val); 45 | // } 46 | 47 | 48 | //思路二:利用栈的思想 49 | //先序遍历是:根->左->右,而后序遍历是:左->右->根. 50 | //所以可以修改一下先序遍历为:根->右->左,然后给值倒叙出来即可 51 | vector postorderTraversal(TreeNode* root) { 52 | if (!root) { 53 | return {}; 54 | } 55 | 56 | vector resVec; 57 | stack s1, s2; 58 | s1.push(root); 59 | while(!s1.empty()) { 60 | TreeNode* pTemp = s1.top(); 61 | s1.pop(); 62 | s2.push(pTemp); //将节点依次放入s2栈中,之后再倒序即可 63 | if (pTemp->left) 64 | s1.push(pTemp->left); 65 | if (pTemp->right) 66 | s1.push(pTemp->right); 67 | } 68 | 69 | while (!s2.empty()) { 70 | resVec.push_back(s2.top()->val); 71 | s2.pop(); 72 | } 73 | 74 | return resVec; 75 | } 76 | 77 | 78 | }; 79 | -------------------------------------------------------------------------------- /Tree/llb/226. Invert Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 问题描述: 3 | Invert a binary tree. 4 | 4 5 | / \ 6 | 2 7 7 | / \ / \ 8 | 1 3 6 9 9 | to 10 | 4 11 | / \ 12 | 7 2 13 | / \ / \ 14 | 9 6 3 1 15 | Trivia: 16 | This problem was inspired by this original tweet by Max Howell: 17 | Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off. 18 | */ 19 | 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * struct TreeNode { 24 | * int val; 25 | * TreeNode *left; 26 | * TreeNode *right; 27 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | 33 | //思路一:利用广度优先搜索(层序遍历),判断然后交换每层,逐步进行 34 | /* 35 | TreeNode* invertTree(TreeNode* root) { 36 | if (root == NULL) 37 | return NULL; 38 | 39 | queue q; 40 | q.push(root); 41 | while(!q.empty()) { 42 | TreeNode* node = q.front(); 43 | q.pop(); 44 | 45 | //左右孩子存在的话,加入到队列中(也可以先转换,顺序不影响) 46 | if (node->left) 47 | q.push(node->left); 48 | if (node->right) 49 | q.push(node->right); 50 | 51 | //转换 52 | TreeNode* pTemp = node->left; 53 | node->left = node->right; 54 | node->right = pTemp; 55 | } 56 | 57 | return root; 58 | } 59 | */ 60 | 61 | //思路二:递归构造 62 | TreeNode* invertTree(TreeNode* root) { 63 | if (root == NULL) 64 | return NULL; 65 | 66 | //注意:交换和循环递归左右子树顺序无所谓,仔细想想就是 67 | TreeNode* pTemp = root->left; 68 | root->left = root->right; 69 | root->right = pTemp; 70 | 71 | invertTree(root->left); 72 | invertTree(root->right); 73 | 74 | return root; 75 | } 76 | }; 77 | -------------------------------------------------------------------------------- /Tree/llb/235. Lowest Common Ancestor of a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 3 | 4 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 5 | 6 | _______6______ 7 | / \ 8 | ___2__ ___8__ 9 | / \ / \ 10 | 0 _4 7 9 11 | / \ 12 | 3 5 13 | For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. 14 | 15 | 找到二叉平衡树的父节点 16 | */ 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | * }; 26 | */ 27 | class Solution { 28 | public: 29 | 30 | //思路一:利用递归二分法,利用父节点大于左孩子,而小于右孩子的特性 31 | /* 32 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 33 | if (root->val > p->val && root->val > q->val) 34 | return lowestCommonAncestor(root->left, p, q); 35 | if (root->val < p->val && root->val < q->val) 36 | return lowestCommonAncestor(root->right, p, q); 37 | 38 | return root; 39 | } 40 | */ 41 | 42 | //思路二:迭代循环,知道找到为止 43 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 44 | TreeNode* node = root; 45 | while (true) { 46 | if (node->val > p->val && node->val > q->val) 47 | node = node->left; 48 | else if (node->val < p->val && node->val < q->val) 49 | node = node->right; 50 | else 51 | return node; 52 | } 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /TwoPointers/15_3Sum.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | 4 | """ 5 | 题目链接: https://leetcode.com/problems/3sum/description. 6 | 题目描述: 7 | 8 | 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 9 | in the array which gives the sum of zero. 10 | 11 | Note: The solution set must not contain duplicate triplets. 12 | 13 | For example, given array S = [-1, 0, 1, 2, -1, -4], 14 | 15 | A solution set is: 16 | [ 17 | [-1, 0, 1], 18 | [-1, -1, 2] 19 | ] 20 | 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def threeSum(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: List[List[int]] 29 | """ 30 | if not nums or len(nums) < 3: 31 | return [] 32 | 33 | nums.sort() 34 | return self.three(nums, 0) 35 | 36 | def three(self, nums, target): 37 | ans = [] 38 | for i in range(len(nums) - 2): 39 | if i > 0 and nums[i] == nums[i - 1]: 40 | continue 41 | left, right = i + 1, len(nums) - 1 42 | ct = target - nums[i] 43 | while left < right: 44 | cs = nums[left] + nums[right] 45 | if cs == ct: 46 | ans.append([nums[i], nums[left], nums[right]]) 47 | left += 1 48 | right -= 1 49 | while left < right and nums[left] == nums[left - 1]: 50 | left += 1 51 | while left < right and nums[right] == nums[right + 1]: 52 | right -= 1 53 | elif cs < ct: 54 | left += 1 55 | else: 56 | right -= 1 57 | 58 | return ans 59 | --------------------------------------------------------------------------------