├── .gitignore ├── Array ├── 118_PascalTriangle.py ├── 119_PascalTriangleII.py ├── 164_MaximumGap.py ├── 189_RotateArray.py ├── 228_SummaryRanges.py ├── 26_RemoveDuplicatesFromSortedArray.py ├── 27_RemoveElement.cpp ├── 27_RemoveElement.py ├── 283_MoveZeroes.cpp ├── 283_MoveZeroes.py ├── 289_GameOfLife.py ├── 31_NextPermutation.cpp ├── 31_NextPermutation.py ├── 41_FirstMissingPositive.py ├── 54_SpiralMatrix.py ├── 56_MergeIntervals.py ├── 57_InsertInterval.py ├── 59_SpiralMatrixII.py └── 73_SetMatrixZeroes.py ├── Backtracking ├── 131_PalindromePartitioning.py ├── 216_CombinationSumIII.py ├── 22_GenerateParentheses.py ├── 39_CombinationSum.cpp ├── 39_CombinationSum.py ├── 40_CombinationSumII.cpp ├── 40_CombinationSumII.py ├── 46_Permutations.cpp ├── 46_Permutations.py ├── 47_PermutationsII.cpp ├── 47_PermutationsII.py ├── 51_NQueens.cpp ├── 51_NQueens.py ├── 52_NQueensII.cpp ├── 52_NQueensII.py ├── 79_WordSearch.py ├── 90_SubsetsII.py ├── 93_RestoreIPAddresses.py └── README.md ├── BinarySearch ├── 153_FindMinimumInRotatedSortedArray.cpp ├── 153_FindMinimumInRotatedSortedArray.py ├── 154_FindMinimumInRotatedSortedArrayII.cpp ├── 154_FindMinimumInRotatedSortedArrayII.py ├── 162_FindPeakElement.py ├── 222_CountCompleteTreeNodes.py ├── 230_KthSmallestElementInBST.py ├── 275_H-IndexII.py ├── 278_FirstBadVersion.py ├── 33_SearchInRotatedSortedArray.cpp ├── 33_SearchInRotatedSortedArray.py ├── 34_SearchForRange.cpp ├── 34_SearchForRange.py ├── 35_SearchInsertPosition.cpp ├── 35_SearchInsertPosition.py ├── 367_ValidPerfectSquare.cpp ├── 367_ValidPerfectSquare.py ├── 378_KthSmallestElementInSortedMatrix.py ├── 4_MedianOfTwoSortedArrays.cpp ├── 4_MedianOfTwoSortedArrays.py ├── 69_Sqrt_x.cpp ├── 69_Sqrt_x.py ├── 74_Search2DMatrix.cpp ├── 74_Search2DMatrix.py ├── 81_SearchInRotatedSortedArrayII.py └── README.md ├── BitManipulation ├── 136_SingleNumber.cpp ├── 136_SingleNumber.py ├── 137_SingleNumberII.cpp ├── 137_SingleNumberII.py ├── 169_MajorityElement.cpp ├── 169_MajorityElement.py ├── 190_ReverseBits.py ├── 191_NumberOf1Bits.py ├── 201_BitwiseANDofNumbersRange.py ├── 231_PowerOfTwo.py ├── 260_SingleNumberIII.cpp ├── 260_SingleNumberIII.py ├── 268_MissingNumber.py ├── 29_DivideTwoIntegers.cpp ├── 29_DivideTwoIntegers.py ├── 318_MaximumProductOfWordLengths.py ├── 338_CountingBits.cpp ├── 338_CountingBits.py ├── 342_PowerOfFour.cpp ├── 342_PowerOfFour.py ├── 371_SumOfTwoIntegers.cpp ├── 371_SumOfTwoIntegers.py ├── 78_Subsets.py └── README.md ├── BreadthFirstSearch ├── 102_BinaryTreeLevelOrderTraversal.cpp ├── 102_BinaryTreeLevelOrderTraversal.py ├── 103_BinaryTreeZigzagLevelOrderTraversal.cpp ├── 103_BinaryTreeZigzagLevelOrderTraversal.py ├── 104_MaximumDepthOfBinaryTree.py ├── 107_BinaryTreeLevelOrderTraversalII.py ├── 126_WordLadderII.py ├── 127_WordLadder.py ├── 130_SurroundedRegions.py ├── 199_BinaryTreeRightSideView.py ├── 310_MinimumHeightTrees.py ├── 322_CoinChange.py └── README.md ├── Combination ├── 140_WordBreakII.py ├── 146_LRUCache.py ├── 300_LongestIncreasingSubsequence.cpp ├── 300_LongestIncreasingSubsequence.py ├── 30_SubstringWithConcatenationOfAllWords.cpp ├── 30_SubstringWithConcatenationOfAllWords.py ├── 324_WiggleSortII.cpp ├── 324_WiggleSortII.py ├── 329_LongestIncreasingPathInMatrix.py ├── 355_DesignTwitter.cpp ├── 355_DesignTwitter.py ├── 37_SudokuSolver.cpp └── 37_SudokuSolver.py ├── DFA ├── 65_ValidNumber.cpp ├── 65_ValidNumber.py └── README.md ├── DepthFirstSearch ├── 126_WordLadderII.py ├── 129_SumRootToLeafNumbers.py ├── 140_WordBreakII.py ├── 200_NumberofIslands.py ├── 257_BinaryTreePaths.py ├── 282_ExpressionAddOperators.cpp ├── 282_ExpressionAddOperators.py ├── 301_RemoveInvalidParentheses.py ├── 306_AdditiveNumber.py ├── 98_ValidateBinarySearchTree.py └── README.md ├── DivideConquer ├── 215_KthLargestElementArray.cpp ├── 215_KthLargestElementArray.py ├── 240_Search2DMatrixII.cpp ├── 240_Search2DMatrixII.py ├── 241_DifferentWaysToAddParentheses.py └── README.md ├── DynamicProgramming ├── 10_RegularExpressionMatching.cpp ├── 10_RegularExpressionMatching.py ├── 115_DistinctSubsequences.cpp ├── 115_DistinctSubsequences.py ├── 120_Triangle.cpp ├── 120_Triangle.py ├── 121_BestTimeToBuyAndSellStock.cpp ├── 121_BestTimeToBuyAndSellStock.py ├── 123_BestTimeToBuyAndSellStockIII.cpp ├── 123_BestTimeToBuyAndSellStockIII.py ├── 132_PalindromePartitioningII.cpp ├── 132_PalindromePartitioningII.py ├── 135_Candy.py ├── 139_WordBreak.py ├── 152_MaximumProductSubarray.py ├── 174_DungeonGame.py ├── 188_BestTimeBuySellStockIV.cpp ├── 188_BestTimeBuySellStockIV.py ├── 198_HouseRobber.py ├── 213_HouseRobberII.py ├── 221_MaximalSquare.py ├── 264_UglyNumberII.cpp ├── 264_UglyNumberII.py ├── 279_PerfectSquares.py ├── 303_RangeSumQueryImmutable.py ├── 304_RangeSumQuery2DImmutable.py ├── 309_BestTimeBuySellStockWithCooldown.cpp ├── 309_BestTimeBuySellStockWithCooldown.py ├── 313_SuperUglyNumber.cpp ├── 313_SuperUglyNumber.py ├── 32_LongestValidParentheses.cpp ├── 32_LongestValidParentheses.py ├── 337_HouseRobberIII.cpp ├── 337_HouseRobberIII.py ├── 357_CountNumbersWithUniqueDigits.cpp ├── 357_CountNumbersWithUniqueDigits.py ├── 368_LargestDivisibleSubset.cpp ├── 368_LargestDivisibleSubset.py ├── 44_WildcardMatching.cpp ├── 44_WildcardMatching.py ├── 53_MaximumSubarray.cpp ├── 53_MaximumSubarray.py ├── 62_UniquePaths.cpp ├── 62_UniquePaths.py ├── 63_UniquePathsII.cpp ├── 63_UniquePathsII.py ├── 64_MinimumPathSum.cpp ├── 64_MinimumPathSum.py ├── 70_ClimbingStairs.py ├── 72_EditDistance.py ├── 87_ScrambleString.py ├── 91_DecodeWays.py ├── 97_InterleavingString.py └── README.md ├── Graph ├── 133_CloneGraph.py ├── 207_CourseSchedule.py ├── 210_CourseScheduleII.py └── README.md ├── Greedy ├── 122_BestTimeToBuyAndSellStockII.cpp ├── 122_BestTimeToBuyAndSellStockII.py ├── 134_GasStation.py ├── 316_RemoveDuplicateLetters.py ├── 330_PatchingArray.py ├── 45_JumpGameII.cpp ├── 45_JumpGameII.py ├── 55_JumpGame.cpp ├── 55_JumpGame.py └── README.md ├── HashTable ├── 01_TwoSum.cpp ├── 01_TwoSum.py ├── 03_LongestSubstringWithoutRepeatingCharacters.py ├── 128_LongestConsecutiveSequence.py ├── 146_LRUCache_pythonic.py ├── 149_MaxPointsOnLine.py ├── 187_RepeatedDNASequences.py ├── 205_IsomorphicStrings.py ├── 217_ContainsDuplicate.py ├── 219_ContainsDuplicateII.py ├── 242_ValidAnagram.py ├── 274_H-Index.py ├── 290_WordPattern.py ├── 299_BullsAndCows.py ├── 349_IntersectionOfTwoArrays.cpp ├── 349_IntersectionOfTwoArrays.py ├── 350_IntersectionOfTwoArraysII.cpp ├── 350_IntersectionOfTwoArraysII.py ├── 36_ValidSudoku.cpp ├── 36_ValidSudoku.py ├── 49_GroupAnagrams.cpp ├── 49_GroupAnagrams.py └── README.md ├── Heap ├── 23_MergeKSortedLists.py ├── 295_FindMedianFromDataStream.py ├── 347_TopKFrequentElements.cpp ├── 347_TopKFrequentElements.py └── README.md ├── Images ├── 223_rectangle_area.png ├── 65_StateConvert.png ├── 65_ValidNumber.png ├── Backtracking_1.png ├── Backtracking_2.png ├── Backtracking_3.png ├── Backtracking_4.png ├── Graph_1.png ├── Tree_1.jpg ├── Tree_2.jpg └── stack_demo.png ├── LinkedList ├── 02.AddTwoNumbers.py ├── 138_CopyListWithRandomPointer.py ├── 143_ReorderList.py ├── 147_InsertionSortList.py ├── 148_SortList.cpp ├── 148_SortList.py ├── 160_IntersectionOfTwoLinkedLists.cpp ├── 160_IntersectionOfTwoLinkedLists.py ├── 203_RemoveLinkedListElements.py ├── 206_ReverseLinkedList.cpp ├── 206_ReverseLinkedList.py ├── 21_MergeTwoSortedLists.cpp ├── 21_MergeTwoSortedLists.py ├── 234_PalindromeLinkedList.py ├── 237_DeleteNodeInLinkedList.py ├── 24_SwapNodesInPairs.py ├── 25_ReverseNodesIn-k-Group.py ├── 328_OddEvenLinkedList.py ├── 61_RotateList.cpp ├── 61_RotateList.py ├── 76_MinimumWindowSubstring.py ├── 82_RemoveDuplicatesFromSortedListII.cpp ├── 82_RemoveDuplicatesFromSortedListII.py ├── 83_RemoveDuplicatesFromSortedList.cpp ├── 83_RemoveDuplicatesFromSortedList.py ├── 86_PartitionList.py ├── 92_ReverseLinkedListII.py └── README.md ├── List.md ├── Math ├── 07_ReverseInteger.py ├── 09_PalindromeNumber.cpp ├── 09_PalindromeNumber.py ├── 12_IntegertoRoman.py ├── 13_RomantoInteger.py ├── 166_FractionToRecurringDecimal.py ├── 168_ExcelSheetColumnTitle.py ├── 171_ExcelSheetColumnNumber.py ├── 172_FactorialTrailingZeroes.py ├── 179_LargestNumber.py ├── 202_HappyNumber.py ├── 204_CountPrimes.py ├── 223_RectangleArea.cpp ├── 223_RectangleArea.py ├── 233_NumberOfDigitOne.cpp ├── 233_NumberOfDigitOne.py ├── 238_ProductOfArrayExceptSelf.py ├── 258_AddDigits.py ├── 263_UglyNumber.cpp ├── 263_UglyNumber.py ├── 273_IntegerToEnglishWords.py ├── 292_NimGame.py ├── 319_BulbSwitcher.py ├── 326_PowerOfThree.py ├── 335_SelfCrossing.py ├── 343_IntegerBreak.cpp ├── 343_IntegerBreak.py ├── 43_MultiplyStrings.cpp ├── 43_MultiplyStrings.py ├── 48_RotateImage.cpp ├── 48_RotateImage.py ├── 50_Pow.cpp ├── 50_Pow.py ├── 60_PermutationSequence.cpp ├── 60_PermutationSequence.py ├── 66_PlusOne.py └── README.md ├── Others ├── 220_ContainsDuplicateIII.py ├── 229_MajorityElementII.py ├── 239_SlidingWindowMaximum.py ├── 284_PeekingIterator.cpp ├── 284_PeekingIterator.py ├── 307_RangeSumQueryMutable.py ├── 329_LongestIncreasingPathInMatrix.py ├── 332_ReconstructItinerary.cpp ├── 332_ReconstructItinerary.py └── More.md ├── README.md ├── Recursion ├── 101_SymmetricTree.cpp ├── 101_SymmetricTree.py ├── 77_Combinations.py ├── 89_GrayCode.py └── README.md ├── Stack ├── 150_EvaluateReversePolishNotation.py ├── 155_MinStack.cpp ├── 155_MinStack.py ├── 20_ValidParentheses.py ├── 224_BasicCalculator.py ├── 225_ImplementStackusingQueues.cpp ├── 225_ImplementStackusingQueues.py ├── 227_BasicCalculatorII.py ├── 232_ImplementQueueUsingStacks.cpp ├── 232_ImplementQueueUsingStacks.py ├── 316_RemoveDuplicateLetters.py ├── 32_LongestValidParentheses.cpp ├── 32_LongestValidParentheses.py ├── 341_FlattenNestedListIterator.cpp ├── 341_FlattenNestedListIterator.py ├── 71_SimplifyPath.py ├── 84_LargestRectangleInHistogram.py ├── 85_MaximalRectangle.py ├── 94_BinaryTreeInorderTraversal.py └── README.md ├── String ├── 05_LongestPalindromicSubstring.cpp ├── 05_LongestPalindromicSubstring.py ├── 06_ZigZagConversion.py ├── 08_StringtoInteger.cpp ├── 08_StringtoInteger.py ├── 14_LongestCommonPrefix.py ├── 151_ReverseWordsInString.py ├── 165_CompareVersionNumbers.py ├── 17_LetterCombinationsPN.py ├── 28_ImplementstrStr.cpp ├── 28_ImplementstrStr.py ├── 344_ReverseString.cpp ├── 344_ReverseString.py ├── 38_CountAndSay.cpp ├── 38_CountAndSay.py ├── 58_LengthOfLastWord.cpp ├── 58_LengthOfLastWord.py ├── 67_AddBinary.cpp ├── 67_AddBinary.py ├── 68_TextJustification.cpp ├── 68_TextJustification.py └── README.md ├── ToBeOptimized ├── 125_ValidPalindrome.py ├── 127_WordLadder.py ├── 131_PalindromePartitioning.py ├── 132_PalindromePartitioningII.py ├── 132_PalindromePartitioningII_Optimized.py ├── 140_WordBreakII.py ├── 18_4Sum.py ├── 279_PerfectSquares.py ├── 322_CoinChange.py └── 324_WiggleSortII.py ├── Tree ├── 100_SameTree.py ├── 105_ConstructBinaryTreePreorderInorder.py ├── 106_ConstructBinaryTreeInorderPostorder.py ├── 108_ConvertSortedArrayToBinarySearchTree.py ├── 109_ConvertSortedListToBinarySearchTree.py ├── 110_BalancedBinaryTree.cpp ├── 110_BalancedBinaryTree.py ├── 111_MinimumDepthofBinaryTree.py ├── 112_PathSum.cpp ├── 112_PathSum.py ├── 113_PathSumII.cpp ├── 113_PathSumII.py ├── 114_FlattenBinaryTreeToLinkedList.py ├── 116_PopulatingNextRightPointersInEachNode.py ├── 117_PopulatingNextRightPointersInEachNodeII.py ├── 124_BinaryTreeMaximumPathSum.py ├── 144_BinaryTreePreorderTraversal.py ├── 145_BinaryTreePostorderTraversal.py ├── 173_BinarySearchTreeIterator.py ├── 208_ImplementTrie.py ├── 211_AddandSearchWord.py ├── 226_InvertBinaryTree.py ├── 235_LowestCommonAncestorOfBinarySearchTree.cpp ├── 235_LowestCommonAncestorOfBinarySearchTree.py ├── 236_LowestCommonAncestorOfBinaryTree.cpp ├── 236_LowestCommonAncestorOfBinaryTree.py ├── 297_SerializeAndDeserializeBinaryTree.cpp ├── 297_SerializeAndDeserializeBinaryTree.py ├── 331_VerifyPreorderSerializationOfBinaryTree.py ├── 94_BinaryTreeInorderTraversal.cpp ├── 94_BinaryTreeInorderTraversal.py ├── 95_UniqueBinarySearchTreesII.py ├── 96_UniqueBinarySearchTrees.py ├── 99_RecoverBinarySearchTree.py ├── Demo.py ├── README.md ├── test_tree.cpp ├── tree.cpp └── tree.h └── TwoPointers ├── 11_ContainerWithMostWater.py ├── 125_ValidPalindrome.py ├── 141_LinkedListCycle.cpp ├── 141_LinkedListCycle.py ├── 142_LinkedListCycleII.cpp ├── 142_LinkedListCycleII.py ├── 15_3Sum.py ├── 16_3SumClosest.py ├── 18_4Sum.py ├── 19_RemoveNthNodeFromEndOfList.cpp ├── 19_RemoveNthNodeFromEndOfList.py ├── 209_MinimumSizeSubarraySum.py ├── 283_MoveZeroes.py ├── 287_FindTheDuplicateNumber.py ├── 345_ReverseVowelsOfString.cpp ├── 345_ReverseVowelsOfString.py ├── 42_TrappingRainWater.cpp ├── 42_TrappingRainWater.py ├── 75_SortColors.cpp ├── 75_SortColors.py ├── 80_RemoveDuplicatesArrayII.py ├── 88_MergeSortedArray.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | working 2 | -------------------------------------------------------------------------------- /Array/118_PascalTriangle.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def generate(self, numRows): 7 | """ 8 | :type numRows: int 9 | :rtype: List[List[int]] 10 | """ 11 | if not numRows: 12 | return [] 13 | triangle = [[0 for j in range(i+1)] for i in range(numRows)] 14 | triangle[0] = [1] 15 | 16 | for i in range(1, numRows): 17 | one_row = [] 18 | for j in range(i+1): 19 | num = 0 20 | if j < i: 21 | num = triangle[i-1][j] 22 | if i > j-1 >= 0: 23 | num += triangle[i-1][j-1] 24 | one_row.append(num) 25 | 26 | triangle[i] = one_row 27 | 28 | return triangle 29 | 30 | """ 31 | 0 32 | 10 33 | """ 34 | -------------------------------------------------------------------------------- /Array/119_PascalTriangleII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def getRow(self, rowIndex): 7 | """ 8 | :type rowIndex: int 9 | :rtype: List[int] 10 | """ 11 | rowIndex += 1 12 | row_nums = [0 for i in range(rowIndex)] 13 | row_nums[0] = 1 14 | # Use the post part of pre row to update the current row. 15 | for i in range(1, rowIndex): 16 | symmetry_count = (i+1)/2 # The symmetry element's numbers 17 | for j in range(symmetry_count): 18 | num = row_nums[i-1-j] 19 | if i > j-1 >= 0: 20 | num += row_nums[i-j] 21 | row_nums[j] = num 22 | # Get the mid num in odd rows 23 | if (i+1) % 2 != 0: 24 | row_nums[symmetry_count] = 2 * row_nums[i/2] 25 | symmetry_count += 1 26 | # Update the post (symmetry) part of current row 27 | for k in range(symmetry_count, i+1): 28 | row_nums[k] = row_nums[i-k] 29 | return row_nums 30 | 31 | """ 32 | 0 33 | 3 34 | 8 35 | """ 36 | -------------------------------------------------------------------------------- /Array/164_MaximumGap.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | """ 7 | Radix sort, you can see the explanation follow the links. 8 | https://www.cs.usfca.edu/~galles/visualization/RadixSort.html 9 | And here is a java solution in leetcode's discuss: 10 | https://leetcode.com/discuss/53636/radix-sort-solution-in-java-with-explanation 11 | """ 12 | 13 | def maximumGap(self, nums): 14 | if not nums: 15 | return 0 16 | 17 | max_num = max(nums) 18 | bucket = [[] for i in range(10)] 19 | exp = 1 20 | while max_num / exp > 0: 21 | for num in nums: 22 | bucket[(num / exp) % 10].append(num) 23 | nums = [] 24 | for each in bucket: 25 | nums.extend(each) 26 | bucket = [[] for i in range(10)] 27 | exp *= 10 28 | 29 | max_gap = 0 30 | for i in range(1, len(nums)): 31 | max_gap = max(max_gap, nums[i] - nums[i - 1]) 32 | return max_gap 33 | 34 | """ 35 | [] 36 | [1] 37 | [9,12,4,8,6,16,23] 38 | [2,99999999] 39 | """ 40 | -------------------------------------------------------------------------------- /Array/228_SummaryRanges.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def summaryRanges(self, nums): 8 | nums.append("#") # Guard 9 | range_str = [] 10 | start, end = nums[0], nums[0] 11 | for i in xrange(1, len(nums)): 12 | if nums[i] == nums[i-1] + 1: 13 | end += 1 14 | else: 15 | if start == end: 16 | range_str.append(str(start)) 17 | else: 18 | range_str.append(str(start) + "->" + str(end)) 19 | start = end = nums[i] 20 | return range_str 21 | 22 | """ 23 | [] 24 | [-1] 25 | [0,1,2,3,5,8,9,11] 26 | """ 27 | -------------------------------------------------------------------------------- /Array/26_RemoveDuplicatesFromSortedArray.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def removeDuplicates(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | if not nums: 12 | return 0 13 | 14 | removed_end = 0 15 | for i in range(1, len(nums)): 16 | if nums[i] != nums[removed_end]: 17 | removed_end += 1 18 | nums[removed_end] = nums[i] 19 | 20 | return removed_end + 1 21 | 22 | """ 23 | [] 24 | [1,1,2,2,3] 25 | [1,3,5,8,9,9,9] 26 | """ 27 | -------------------------------------------------------------------------------- /Array/27_RemoveElement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-06 21:03:01 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int removeElement(vector& nums, int val) { 9 | int val_start = 0; 10 | for(auto &n : nums){ 11 | if(n!=val){ 12 | nums[val_start++] = n; 13 | } 14 | } 15 | return val_start; 16 | } 17 | }; 18 | 19 | /* 20 | [] 21 | 0 22 | [2,2,2,3,3,3,5,5,5] 23 | 4 24 | [1,2,3,4,5,1,2,3,4,5] 25 | 3 26 | */ 27 | -------------------------------------------------------------------------------- /Array/27_RemoveElement.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def removeElement(self, nums, val): 7 | removed_end = 0 8 | for num in nums: 9 | if num != val: 10 | nums[removed_end] = num 11 | removed_end += 1 12 | 13 | return removed_end 14 | 15 | """ 16 | [] 17 | 0 18 | [2,2,2,3,3,3,5,5,5] 19 | 4 20 | [1,2,3,4,5,1,2,3,4,5] 21 | 3 22 | """ 23 | -------------------------------------------------------------------------------- /Array/283_MoveZeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-28 10:57:41 4 | */ 5 | 6 | class Solution { 7 | public: 8 | void moveZeroes(vector& nums) { 9 | // Every time put the non-zero number to the right position. 10 | int non_zero = 0, index = 0; 11 | for(; index& nums) { 10 | if(nums.empty()) return; 11 | int i; 12 | for(i=nums.size()-1; i>=1; i--){ 13 | if(nums[i] > nums[i-1]) break; 14 | } 15 | reverse(nums.begin()+i, nums.end()); 16 | if(i==0) return; 17 | auto iter = upper_bound(nums.begin()+i, nums.end(), nums[i-1]); 18 | swap(nums[i-1], *iter); 19 | } 20 | }; 21 | 22 | /* 23 | [] 24 | [1] 25 | [1,2,3] 26 | [3,2,1] 27 | [1,1,2,2,4,5,5] 28 | */ 29 | -------------------------------------------------------------------------------- /Array/31_NextPermutation.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def nextPermutation(self, nums): 7 | length = len(nums) 8 | index = length - 1 9 | 10 | """ 11 | Scan from the end of nums and get nums[index], 12 | find one pair which nums[mark] > nums[mark - 1], 13 | then swap the smallest number in nums[mark:] and nums[mark - 1]. 14 | Finally sort nums[mark:] and we will slove the problem. 15 | """ 16 | while index >= 1: 17 | if nums[index] > nums[index - 1]: 18 | for i in range(length - 1, index - 1, -1): 19 | if nums[i] > nums[index - 1]: 20 | nums[i], nums[index - 1] = nums[index - 1], nums[i] 21 | nums[index:] = sorted(nums[index:]) 22 | return 23 | else: 24 | index -= 1 25 | 26 | # Nums is in descending order, just reverse it. 27 | nums.reverse() 28 | 29 | """ 30 | [] 31 | [1] 32 | [1,2,3] 33 | [3,2,1] 34 | [1,1,2,2,4,5,5] 35 | """ 36 | -------------------------------------------------------------------------------- /Array/41_FirstMissingPositive.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def firstMissingPositive(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | # Put all i+1 in nums[i] 12 | nums_len = len(nums) 13 | for i in range(nums_len): 14 | # Swap nums[i] to the appropriate position until current 15 | # nums[i] can't be push to the list, which is <0 or >nums_len 16 | # By the way, pay attention to situation as [1,1]. 17 | while nums[i] != i + 1 and 0 < nums[i] <= nums_len: 18 | index = nums[i] - 1 19 | if nums[index] == nums[i]: 20 | break 21 | nums[i], nums[index] = nums[index], nums[i] 22 | # nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i] 23 | 24 | for i in range(nums_len): 25 | if nums[i] != i + 1: 26 | return i + 1 27 | 28 | return nums_len + 1 29 | 30 | """ 31 | [] 32 | [1,2,0] 33 | [3,4,-1,1] 34 | [3,4,-1,1,2,2,0,12,3] 35 | """ 36 | -------------------------------------------------------------------------------- /Array/56_MergeIntervals.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Definition for an interval. 4 | # class Interval(object): 5 | # def __init__(self, s=0, e=0): 6 | # self.start = s 7 | # self.end = e 8 | 9 | 10 | class Solution(object): 11 | def merge(self, intervals): 12 | """ 13 | :type intervals: List[Interval] 14 | :rtype: List[Interval] 15 | """ 16 | merged_list = [] 17 | length = len(intervals) 18 | intervals.sort(key=lambda interval: interval.start) 19 | i = 0 20 | 21 | # Scan every interval and merge the overlapping intervals. 22 | while i < length: 23 | j = i + 1 24 | while j < length and intervals[j].start <= intervals[i].end: 25 | intervals[i].start = min(intervals[i].start, 26 | intervals[j].start) 27 | intervals[i].end = max(intervals[i].end, 28 | intervals[j].end) 29 | j += 1 30 | 31 | merged_list.append(intervals[i]) 32 | i = j 33 | 34 | return merged_list 35 | 36 | """ 37 | [] 38 | [[1,4],[4,5]] 39 | [[1,3],[2,6],[8,10],[15,18]] 40 | [[12,13],[1,3],[5,8],[2,6],[6,7]] 41 | """ 42 | -------------------------------------------------------------------------------- /Backtracking/216_CombinationSumIII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def combinationSum3(self, k, n): 8 | self.combination = [] 9 | self._combination_sum(k, n, []) 10 | return self.combination 11 | 12 | def _combination_sum(self, k, n, nums): 13 | if not k: 14 | if sum(nums) == n: 15 | # self.combination.append(nums) 16 | # Warning: nums[:] get a new list. 17 | # If not, we will get self.combination = [[], [], ...] finally. 18 | self.combination.append(nums[:]) 19 | else: 20 | return 21 | 22 | # Get the new num from start 23 | start = 1 24 | if nums: 25 | start = nums[-1] + 1 26 | for i in range(start, 10): 27 | cur_sum = sum(nums) + i 28 | if cur_sum <= n: 29 | nums.append(i) 30 | self._combination_sum(k - 1, n, nums) 31 | del nums[-1] # Backtracking 32 | else: 33 | break 34 | 35 | """ 36 | 0 37 | 3 38 | 3 39 | 7 40 | 9 41 | 45 42 | """ 43 | -------------------------------------------------------------------------------- /Backtracking/46_Permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-19 15:29:06 4 | */ 5 | 6 | class Solution { 7 | public: 8 | vector> permute(vector& nums) { 9 | vector> ans; 10 | dfs(nums, 0, ans); 11 | return ans; 12 | } 13 | 14 | void dfs(vector &num, int begin, vector> &ans){ 15 | if(begin == num.size()){ 16 | ans.push_back(num); 17 | return; 18 | } 19 | for(int i=begin; i& nums) { 9 | int left = 0; 10 | int right = nums.size()-1; 11 | 12 | /* 13 | Make sure right is always in the right rotated part. 14 | Left can be either in the left part or the minimum part. 15 | So, when left and right is the same finally, we find the minimum. 16 | */ 17 | while(left& nums) { 14 | int left=0; 15 | int right=nums.size()-1; 16 | while(left nums[mid]){ 24 | right = mid; 25 | } 26 | // Can't make sure whether left is in the left part or not. 27 | // Just move to right for 1 step. 28 | else{ 29 | left += 1; 30 | } 31 | } 32 | return nums[left]; 33 | } 34 | }; 35 | 36 | /* 37 | [1] 38 | [7,8,9,9,9,10,2,2,2,3,4,4,5] 39 | */ 40 | -------------------------------------------------------------------------------- /BinarySearch/154_FindMinimumInRotatedSortedArrayII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def findMin(self, nums): 7 | assert(nums) 8 | left = 0 9 | right = len(nums) - 1 10 | # Make sure right is always in the right rotated part. 11 | # Left can be either in the left part or the minimum part. 12 | # So, when left and right is the same finally, we find the minimum. 13 | while left < right: 14 | # When there is no rotate, just return self.nums[start] 15 | if nums[left] < nums[right]: 16 | return nums[left] 17 | 18 | mid = (left + right) / 2 19 | # mid is in the left part, so move the left point to mid. 20 | if nums[left] < nums[mid]: 21 | left = mid + 1 22 | elif nums[left] > nums[mid]: 23 | right = mid 24 | # Can't make sure whether left is in the left part or not. 25 | # Just move to right for 1 step. 26 | else: 27 | left += 1 28 | return nums[left] 29 | 30 | """ 31 | [1] 32 | [7,8,9,9,9,10,2,2,2,3,4,4,5] 33 | """ 34 | -------------------------------------------------------------------------------- /BinarySearch/162_FindPeakElement.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | """ 7 | Binary search 8 | Three possible situations(here target is just one of the peeks): 9 | 1. left, left+1, ..., mid-1, mid, mid+1, ..target.., right 10 | 2. left, left+1, ..target.., mid-1, mid, mid+1, ..., right 11 | 3. left, left+1, ..., mid-1, mid(target), mid+1, ..., right 12 | """ 13 | def findPeakElement(self, nums): 14 | if not nums: 15 | return 0 16 | right = len(nums) - 1 17 | left = 0 18 | 19 | while left < right: 20 | mid = (left + right) / 2 21 | if nums[mid] < nums[mid+1]: 22 | left = mid + 1 23 | else: 24 | right = mid 25 | 26 | return left 27 | 28 | """ 29 | if __name__ == '__main__': 30 | sol = Solution() 31 | print sol.findPeakElement([1]) 32 | print sol.findPeakElement([1, 2]) 33 | print sol.findPeakElement([1, 2, 3, 4]) 34 | print sol.findPeakElement([1, 2, 3, 2, 1, 4, 1, 2, 3]) 35 | """ 36 | -------------------------------------------------------------------------------- /BinarySearch/275_H-IndexII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # Binary Search, Yes!! 8 | def hIndex(self, citations): 9 | length = len(citations) 10 | left = 0 11 | right = length - 1 12 | while left <= right: 13 | # Disapproval / operator here(more slower), can use // or >> 1 14 | # mid = (left + right) / 2 15 | mid = (left + right) >> 1 16 | if citations[mid] == length - mid: 17 | return citations[mid] 18 | elif citations[mid] > length - mid: 19 | right = mid - 1 20 | else: 21 | left = mid + 1 22 | return length - (right + 1) 23 | 24 | 25 | """ 26 | [] 27 | [0] 28 | [23] 29 | [0,1] 30 | [1,1,1,1] 31 | [4,4,4,4] 32 | [0,1,4,5,6] 33 | """ 34 | -------------------------------------------------------------------------------- /BinarySearch/278_FirstBadVersion.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # The isBadVersion API is already defined for you. 5 | # @param version, an integer 6 | # @return a bool 7 | # def isBadVersion(version): 8 | 9 | 10 | class Solution(object): 11 | # Attention: the latest version of your product fails the quality check 12 | # That's saying, given n versions must have at least one bad version. 13 | def firstBadVersion(self, n): 14 | if n <= 0: 15 | return 0 16 | left, right = 1, n 17 | while left < right: 18 | mid = (left + right) / 2 19 | if isBadVersion(mid): 20 | right = mid 21 | else: 22 | left = mid + 1 23 | return right 24 | -------------------------------------------------------------------------------- /BinarySearch/33_SearchInRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def search(self, nums, target): 7 | nums_size = len(nums) 8 | start = 0 9 | end = nums_size - 1 10 | while start <= end: 11 | mid = (start + end) / 2 12 | num_mid = nums[mid] 13 | 14 | # Mid is in the left part of the rotated(if it's rotated) array. 15 | if num_mid >= nums[start]: 16 | if nums[start] <= target < num_mid: 17 | end = mid - 1 18 | elif num_mid == target: 19 | return mid 20 | else: 21 | start = mid + 1 22 | 23 | # The array must be rotated, and mid is in the right part 24 | else: 25 | if num_mid < target <= nums[end]: 26 | start = mid + 1 27 | elif target == num_mid: 28 | return mid 29 | else: 30 | end = mid - 1 31 | 32 | return -1 33 | 34 | """ 35 | [] 36 | 0 37 | [1] 38 | 1 39 | [8,11,13,1,3,4,5,7] 40 | 7 41 | [4,5,6,7,8,1,2,3] 42 | 8 43 | [5, 1, 3] 44 | 1 45 | """ 46 | -------------------------------------------------------------------------------- /BinarySearch/35_SearchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-05-24 22:01:50 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int searchInsert(vector& nums, int target) { 9 | int left=0, right=nums.size() - 1; 10 | while (left <= right){ 11 | int mid = left + (right-left) / 2; 12 | if(target == nums[mid]){ 13 | return mid; 14 | } 15 | 16 | else if(target > nums[mid]){ 17 | left = mid + 1; 18 | } 19 | 20 | else{ 21 | right = mid - 1; 22 | } 23 | } 24 | return left; 25 | } 26 | }; 27 | 28 | /* 29 | [1,3,5,6] 30 | 5 31 | [1,3,5,6] 32 | 2 33 | [1,3,5,6] 34 | 7 35 | [1,3,5,6] 36 | 0 37 | */ 38 | -------------------------------------------------------------------------------- /BinarySearch/35_SearchInsertPosition.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | # Pythonic way. 7 | def searchInsert(self, nums, target): 8 | return len([x for x in nums if x < target]) 9 | 10 | 11 | class Solution_2(object): 12 | def searchInsert(self, nums, target): 13 | left, right = 0, len(nums) - 1 14 | while left <= right: 15 | mid = (left + right) / 2 16 | if target == nums[mid]: 17 | return mid 18 | 19 | elif target > nums[mid]: 20 | left = mid + 1 21 | 22 | else: 23 | right = mid - 1 24 | 25 | return left 26 | 27 | """ 28 | [1,3,5,6] 29 | 5 30 | [1,3,5,6] 31 | 2 32 | [1,3,5,6] 33 | 7 34 | [1,3,5,6] 35 | 0 36 | """ 37 | -------------------------------------------------------------------------------- /BinarySearch/367_ValidPerfectSquare.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-07-04 11:44:22 5 | 6 | 7 | class Solution(object): 8 | # Binary Search 9 | def isPerfectSquare(self, num): 10 | low, high = 0, num 11 | while low <= high: 12 | mid = (low + high) / 2 13 | if mid ** 2 == num: 14 | return True 15 | elif mid ** 2 > num: 16 | high = mid - 1 17 | else: 18 | low = mid + 1 19 | return False 20 | 21 | 22 | class Solution_2(object): 23 | # Truth: A square number is 1+3+5+7+... Time Complexity O(sqrt(N)) 24 | def isPerfectSquare(self, num): 25 | i = 1 26 | while num > 0: 27 | num -= i 28 | i += 2 29 | return num == 0 30 | 31 | 32 | class Solution_3(object): 33 | # Newton Method. Time Complexity is close to constant. 34 | # According to: https://en.wikipedia.org/wiki/Newton%27s_method 35 | def isPerfectSquare(self, num): 36 | val = num 37 | while val ** 2 > num: 38 | val = (val + num / val) / 2 39 | return val * val == num 40 | 41 | """ 42 | 0 43 | 1 44 | 121 45 | 12321 46 | 2147483647 47 | """ 48 | -------------------------------------------------------------------------------- /BinarySearch/378_KthSmallestElementInSortedMatrix.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-08-29 10:15:24 5 | 6 | 7 | class Solution(object): 8 | """ Heap merge is helpfull. 9 | """ 10 | def kthSmallest(self, matrix, k): 11 | import heapq 12 | return list(heapq.merge(*matrix))[k - 1] 13 | 14 | 15 | class Solution(object): 16 | """ Binary Search can solve this too. 17 | """ 18 | def kthSmallest(self, matrix, k): 19 | 20 | 21 | """ 22 | [[1]] 23 | 1 24 | [[1,2,3], [4,5,6], [7,8,9]] 25 | 3 26 | [[ 1, 5, 9], [10, 11, 13], [12, 13, 15]] 27 | 8 28 | """ 29 | -------------------------------------------------------------------------------- /BinarySearch/69_Sqrt_x.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-01 20:42:32 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int mySqrt(int x) { 9 | if(x < 2){ 10 | return x; 11 | } 12 | int low = 0, high = x; 13 | while(low <= high){ 14 | int mid = low + (high - low) / 2; 15 | // mid * mid will overflow when mid > sqrt(INT_MAX) 16 | if(x / mid >= mid && x / (mid+1) < (mid+1)){ 17 | return mid; 18 | } 19 | else if(x / mid < mid){ 20 | high = mid - 1; 21 | } 22 | else{ 23 | low = mid + 1; 24 | } 25 | } 26 | return -1; // Can'e be reached! 27 | } 28 | }; 29 | 30 | class Solution_2{ 31 | public: 32 | int mySqrt(int x) { 33 | // Newton iterative method 34 | long ans = x; 35 | while(ans * ans > x){ 36 | ans = (ans + x/ans) / 2; 37 | } 38 | return ans; 39 | } 40 | }; 41 | 42 | /* 43 | 0 44 | 1 45 | 15 46 | 90 47 | 1010 48 | */ 49 | -------------------------------------------------------------------------------- /BinarySearch/69_Sqrt_x.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | # Binary search. 7 | def mySqrt(self, x): 8 | low, high = 0, x 9 | while low <= high: 10 | mid = (low + high) / 2 11 | if mid ** 2 <= x < (mid + 1) ** 2: 12 | return mid 13 | elif mid ** 2 > x: 14 | high = mid - 1 15 | else: 16 | low = mid + 1 17 | 18 | 19 | class Solution_2(object): 20 | # Newton iterative method 21 | # According to: 22 | # http://www.matrix67.com/blog/archives/361 23 | def mySqrt(self, x): 24 | if not x: 25 | return x 26 | val = x 27 | sqrt_x = (val + x * 1.0 / val) / 2.0 28 | while val - sqrt_x > 0.001: 29 | val = sqrt_x 30 | sqrt_x = (val + x * 1.0 / val) / 2.0 31 | 32 | return int(sqrt_x) 33 | 34 | 35 | class Solution_3(object): 36 | # Shorter Newton method. 37 | def mySqrt(self, x): 38 | val = x 39 | while val * val > x: 40 | val = (val + x / val) / 2 41 | return val 42 | 43 | """ 44 | 0 45 | 1 46 | 15 47 | 90 48 | 1010 49 | """ 50 | -------------------------------------------------------------------------------- /BinarySearch/74_Search2DMatrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-13 11:17:48 4 | */ 5 | 6 | class Solution { 7 | public: 8 | // Don't treat it as a 2D matrix, just treat it as a sorted list 9 | bool searchMatrix(vector>& matrix, int target) { 10 | if(matrix.empty()){ 11 | return false; 12 | } 13 | int m_rows = matrix.size(), n_cols = matrix[0].size(); 14 | int left=0, right = m_rows*n_cols-1; 15 | while(left <= right){ 16 | int mid = left + (right-left) / 2; 17 | int num = matrix[mid/n_cols][mid%n_cols]; 18 | if(num < target){ 19 | left = mid + 1; 20 | } 21 | else if(num > target){ 22 | right = mid - 1; 23 | } 24 | else{ 25 | return true; 26 | } 27 | } 28 | return false; 29 | } 30 | }; 31 | 32 | /* 33 | [[]] 34 | 0 35 | [[1]] 36 | 0 37 | [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] 38 | 34 39 | [[1, 3, 5], [10, 11, 16], [23, 30, 34]] 40 | 46 41 | */ 42 | -------------------------------------------------------------------------------- /BinarySearch/74_Search2DMatrix.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | # Don't treat it as a 2D matrix, just treat it as a sorted list 7 | def searchMatrix(self, matrix, target): 8 | if not matrix: 9 | return False 10 | 11 | # Classic binary search: O(logmn) 12 | m_rows, n_cols = len(matrix), len(matrix[0]) 13 | left, right = 0, m_rows * n_cols - 1 14 | 15 | while left <= right: 16 | mid = (left+right) / 2 17 | num = matrix[mid / n_cols][mid % n_cols] 18 | if num > target: 19 | right = mid - 1 20 | elif num < target: 21 | left = mid + 1 22 | else: 23 | return True 24 | 25 | return False 26 | 27 | """ 28 | [[]] 29 | 0 30 | [[1]] 31 | 0 32 | [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] 33 | 34 34 | [[1, 3, 5], [10, 11, 16], [23, 30, 34]] 35 | 46 36 | """ 37 | -------------------------------------------------------------------------------- /BitManipulation/136_SingleNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-11 23:02:26 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int singleNumber(vector& nums) { 9 | int xor_n = 0; 10 | for(const auto &n: nums){ 11 | xor_n ^= n; 12 | } 13 | return xor_n; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /BitManipulation/136_SingleNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def singleNumber(self, nums): 7 | num = nums[0] 8 | for i in nums[1:]: 9 | num = num ^ i 10 | return num 11 | 12 | """ 13 | [1] 14 | [1,2,3,4,4,3,2] 15 | """ 16 | -------------------------------------------------------------------------------- /BitManipulation/169_MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuelangZF 3 | * @Date: 2016-03-06 17:30:53 4 | * @Last Modified by: xuelangZF 5 | * @Last Modified time: 2016-03-06 17:30:53 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int majorityElement(vector& nums) { 11 | int count = 0, num = 0, size = nums.size(); 12 | for(int i=0; i> i) & 1 19 | return count 20 | 21 | """ 22 | if __name__ == '__main__': 23 | sol = Solution() 24 | print sol.hammingWeight(11) 25 | print sol.hammingWeight_1(11) 26 | """ 27 | -------------------------------------------------------------------------------- /BitManipulation/231_PowerOfTwo.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Easy to understand. 7 | class Solution(object): 8 | def isPowerOfTwo(self, n): 9 | if n <= 0: 10 | return False 11 | while n: 12 | if n & 1 and n != 1: 13 | return False 14 | n >>= 1 15 | return True 16 | 17 | 18 | # Another solution: using n&(n-1) trick 19 | class Solution_2(object): 20 | def isPowerOfTwo(self, n): 21 | return n > 0 and not n & (n-1) 22 | 23 | """ 24 | -7 25 | 0 26 | 1 27 | 2 28 | 15 29 | 121 30 | """ 31 | -------------------------------------------------------------------------------- /BitManipulation/260_SingleNumberIII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-11 15:02:03 4 | */ 5 | 6 | class Solution { 7 | public: 8 | vector singleNumber(vector& nums) { 9 | vector ans(2,0); 10 | int xor_nums = 0; 11 | for(int &n : nums){ 12 | xor_nums ^= n; 13 | } 14 | xor_nums &= -xor_nums; 15 | for(int &n : nums){ 16 | /* 17 | * All the numbers can be partitioned into 18 | * two groups according to their bits at location i. 19 | * The first group consists of all numbers whose bits at i is 0. 20 | * The second group consists of all numbers whose bits at i is 1. 21 | * The two different number a and b is in the two different groups. 22 | */ 23 | if(n & xor_nums){ 24 | ans[0] ^= n; 25 | } 26 | else{ 27 | ans[1] ^= n; 28 | } 29 | } 30 | return ans; 31 | } 32 | }; 33 | 34 | /* 35 | [-1,0] 36 | [1, 2, 1, 3, 2, 5] 37 | [-1,-1,-2,-2,-3,-3,-3,-3,4,-5] 38 | */ 39 | -------------------------------------------------------------------------------- /BitManipulation/260_SingleNumberIII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # Clear explanation according to 8 | # https://leetcode.com/discuss/60408/sharing-explanation-of-the-solution 9 | def singleNumber(self, nums): 10 | xor_res = 0 11 | for num in nums: 12 | xor_res ^= num 13 | 14 | # Assume the two different numbers diff at ith bit(i is the rightmost). 15 | # Then we can get 0x000...1...000, 1 is the ith bit by the following. 16 | xor_res &= -xor_res 17 | num_a, num_b = 0, 0 18 | for num in nums: 19 | # All the numbers can be partitioned into 20 | # two groups according to their bits at location i. 21 | # The first group consists of all numbers whose bits at i is 0. 22 | # The second group consists of all numbers whose bits at i is 1. 23 | # The two different number a and b is in the two different groups. 24 | if num & xor_res == 0: 25 | num_a ^= num 26 | else: 27 | num_b ^= num 28 | return [num_a, num_b] 29 | 30 | """ 31 | [-1,0] 32 | [1, 2, 1, 3, 2, 5] 33 | [-1,-1,-2,-2,-3,-3,-3,-3,4,-5] 34 | """ 35 | -------------------------------------------------------------------------------- /BitManipulation/268_MissingNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # XOR all the num in nums and sequence from 0 to n, 8 | # All the num in nums occur twice, then the result is the missing one 9 | def missingNumber(self, nums): 10 | i = 0 11 | missing_num = 0 12 | for num in nums: 13 | missing_num ^= num 14 | missing_num ^= i 15 | i += 1 16 | missing_num ^= i 17 | return missing_num 18 | 19 | """ 20 | [0] 21 | [1] 22 | [1,2,3] 23 | [0,1,2,3,5,7,8,6] 24 | """ 25 | -------------------------------------------------------------------------------- /BitManipulation/29_DivideTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-06 22:39:41 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | // Refer to: 10 | // https://leetcode.com/discuss/38997/detailed-explained-8ms-c-solution 11 | int divide(int dividend, int divisor) { 12 | if(!divisor || (dividend==INT_MIN && divisor==-1)) 13 | return INT_MAX; 14 | 15 | bool positive = ((dividend < 0) == (divisor < 0)); 16 | long long dvd = labs(dividend); 17 | long long dvs = labs(divisor); 18 | int ans = 0; 19 | while(dvd >= dvs){ 20 | long long temp=dvs, multiple=1; 21 | while(dvd >= (temp<<1)){ 22 | temp <<= 1; 23 | multiple <<= 1; 24 | } 25 | ans += multiple; 26 | dvd -= temp; 27 | } 28 | 29 | return positive ? ans:-ans; 30 | } 31 | }; 32 | 33 | /* 34 | 0 35 | 1 36 | 12 37 | 3 38 | 125 39 | -4 40 | 1 41 | -1 42 | 2147483647 43 | 1 44 | */ 45 | -------------------------------------------------------------------------------- /BitManipulation/29_DivideTwoIntegers.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | # According to: 7 | # https://leetcode.com/discuss/38997/detailed-explained-8ms-c-solution 8 | # Key concept: 9 | # division simply requires us to find how many times we can subtract the 10 | # divisor from the the dividend without making the dividend negative. 11 | 12 | def divide(self, dividend, divisor): 13 | if divisor == 0: 14 | return -1 15 | 16 | # Make sure it's positive or negative 17 | positive = (dividend < 0) is (divisor < 0) 18 | dividend, divisor = abs(dividend), abs(divisor) 19 | answer = 0 20 | 21 | while dividend >= divisor: 22 | multiple, temp = 1, divisor 23 | while dividend >= (temp << 1): 24 | multiple <<= 1 25 | temp <<= 1 26 | dividend -= temp 27 | answer += multiple 28 | 29 | if not positive: 30 | answer = -answer 31 | 32 | if (answer > 2147483647) or (answer < -2147483648): 33 | return 2147483647 34 | return answer 35 | 36 | """ 37 | 0 38 | 1 39 | 12 40 | 3 41 | 125 42 | -4 43 | 1 44 | -1 45 | """ 46 | -------------------------------------------------------------------------------- /BitManipulation/318_MaximumProductOfWordLengths.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def maxProduct(self, words): 8 | max_product = 0 9 | length = len(words) 10 | bit_record = [0] * length 11 | # Use 1bit to represent each letter, and 12 | # use 32bit(Int variable, bitMap[i]) to represent the set of each word 13 | for i in xrange(length): 14 | for c in words[i]: 15 | bit_record[i] |= 1 << (ord(c) - ord("a")) 16 | 17 | for i in xrange(length): 18 | for j in xrange(i+1, length): 19 | # If the AND of two bitmap element equals to 0, 20 | # these two words do not have same letter. 21 | if not bit_record[i] & bit_record[j]: 22 | product = len(words[i]) * len(words[j]) 23 | if product > max_product: 24 | max_product = product 25 | return max_product 26 | 27 | """ 28 | [] 29 | ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] 30 | ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] 31 | ["a", "aa", "aaa", "aaaa"] 32 | """ 33 | -------------------------------------------------------------------------------- /BitManipulation/338_CountingBits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-05 17:22:31 4 | */ 5 | 6 | class Solution { 7 | public: 8 | /* 9 | f[i] = f[i / 2] + i % 2 10 | or 11 | f[i] = f[i&(i-1)] + 1, i&(i-1) drops the lowest set bit 12 | */ 13 | vector countBits(int num) { 14 | vector ans(num+1, 0); 15 | for(int i=1;i<=num;i++){ 16 | ans[i] = ans[i>>1] + (i&0x1); 17 | // ans[i] = ans[i&(i-1)] + 1; 18 | } 19 | return ans; 20 | } 21 | }; 22 | 23 | /* 24 | 0 25 | 1 26 | 12 27 | */ 28 | -------------------------------------------------------------------------------- /BitManipulation/338_CountingBits.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-04-05 17:18:25 5 | 6 | 7 | class Solution(object): 8 | def countBits(self, num): 9 | """ 10 | f[i] = f[i / 2] + i % 2 11 | or 12 | f[i] = f[i&(i-1)] + 1, i&(i-1) drops the lowest set bit 13 | """ 14 | ans = [0] * (num + 1) 15 | for i in xrange(1, num + 1): 16 | ans[i] = ans[i >> 1] + (i & 0x1) 17 | # ans[i] = ans[i & (i - 1)] + 1 18 | return ans 19 | 20 | """ 21 | 0 22 | 1 23 | 12 24 | """ 25 | -------------------------------------------------------------------------------- /BitManipulation/342_PowerOfFour.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-04 17:57:31 4 | */ 5 | 6 | class Solution { 7 | public: 8 | /* 9 | Easy to find that power of 4 numbers have those 3 common features. 10 | First, greater than 0. 11 | Second, only have one '1' bit in their binary notation. 12 | Third, the only '1' bit should be locate at the odd location. 13 | */ 14 | bool isPowerOfFour(int num) { 15 | // return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0; 16 | return num>0 && (num&(num-1))==0 && (num&0x55555555); 17 | } 18 | }; 19 | 20 | /* 21 | 1 22 | 16 23 | 256 24 | 1000 25 | */ 26 | -------------------------------------------------------------------------------- /BitManipulation/342_PowerOfFour.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-07-04 17:47:17 5 | 6 | 7 | class Solution(object): 8 | """ 9 | Easy to find that power of 4 numbers have those 3 common features. 10 | First, greater than 0. 11 | Second, only have one '1' bit in their binary notation. 12 | Third, the only '1' bit should be locate at the odd location. 13 | """ 14 | def isPowerOfFour(self, num): 15 | return bool(num > 0 and num & (num - 1) == 0 and num & 0x55555555) 16 | 17 | """ 18 | 1 19 | 16 20 | 256 21 | 1000 22 | """ 23 | -------------------------------------------------------------------------------- /BitManipulation/371_SumOfTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-02 17:09:34 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | /* 10 | Firstly, calculate the carry. 11 | then calculate sum of a and b without thinking the carry. 12 | Finally add sum(without carry) and carry. 13 | */ 14 | int getSum(int a, int b) { 15 | if(b==0){ 16 | return a; 17 | } 18 | return getSum(a^b, (a&b)<<1); 19 | } 20 | }; 21 | 22 | 23 | class Solution_2 { 24 | public: 25 | int getSum(int a, int b) { 26 | while(b != 0){ 27 | int carry_in = (a & b) << 1; 28 | int add_two = a ^ b; 29 | a = add_two; 30 | b = carry_in; 31 | } 32 | return a; 33 | } 34 | }; 35 | 36 | 37 | """ 38 | 0 39 | 1 40 | -3 41 | 5 42 | 12 43 | 10000098 44 | -8 45 | -12 46 | """ 47 | -------------------------------------------------------------------------------- /BitManipulation/371_SumOfTwoIntegers.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-07-02 17:09:49 5 | 6 | 7 | class Solution(object): 8 | """ 9 | Firstly, calculate the carry. 10 | then calculate sum of a and b without thinking the carry. 11 | Finally add sum(without carry) and carry. 12 | """ 13 | MAX_INT = 0x7FFFFFFF 14 | MIN_INT = 0x80000000 15 | MASK = 0x100000000 16 | 17 | def getSum(self, a, b): 18 | if b == 0: 19 | return a if a <= self.MAX_INT else (a % self.MIN_INT) - self.MIN_INT 20 | 21 | add_sum = (a ^ b) % self.MASK 22 | carry_in = ((a & b) << 1) % self.MASK 23 | return self.getSum(add_sum, carry_in) 24 | 25 | 26 | class Solution_2(object): 27 | def getSum(self, a, b): 28 | MAX_INT = 0x7FFFFFFF 29 | MIN_INT = 0x80000000 30 | MASK = 0x100000000 31 | while b != 0: 32 | a, b = (a ^ b) % MASK, ((a & b) << 1) % MASK 33 | 34 | return a if a <= MAX_INT else (a % MIN_INT) - MIN_INT 35 | 36 | """ 37 | 0 38 | 1 39 | -3 40 | 5 41 | 12 42 | 10000098 43 | -8 44 | -12 45 | """ 46 | -------------------------------------------------------------------------------- /BitManipulation/78_Subsets.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def subsets(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: List[List[int]] 10 | """ 11 | 12 | subsets = [] 13 | n = len(nums) 14 | nums.sort() 15 | # We know there are totally 2^n subsets, 16 | # becase every num may in or not in one subsets. 17 | # So we check the jth(0<=j> levelOrder(TreeNode* root) { 19 | if(root==NULL){ 20 | return {}; 21 | } 22 | vector> ans; 23 | deque levels{root}; 24 | while(!levels.empty()){ 25 | vector cur_level; 26 | int l_size = levels.size(); 27 | for(int i=0;ival); 31 | if(cur_node->left) levels.push_back(cur_node->left); 32 | if(cur_node->right) levels.push_back(cur_node->right); 33 | } 34 | ans.push_back(cur_level); 35 | } 36 | return ans; 37 | } 38 | }; 39 | 40 | 41 | /* 42 | [] 43 | [1] 44 | [1,2,3] 45 | [3,9,20,null,null,15,7] 46 | */ 47 | -------------------------------------------------------------------------------- /BreadthFirstSearch/102_BinaryTreeLevelOrderTraversal.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def levelOrder(self, root): 14 | if not root: 15 | return [] 16 | 17 | cur_level, ans = [root], [] 18 | 19 | # Breadth-first Search, Pythonic way. 20 | while cur_level: 21 | ans.append([node.val for node in cur_level]) 22 | cur_level = [kid for n in cur_level 23 | for kid in (n.left, n.right) if kid] 24 | 25 | return ans 26 | 27 | """ 28 | [] 29 | [1] 30 | [1,2,3] 31 | [3,9,20,null,null,15,7] 32 | """ 33 | -------------------------------------------------------------------------------- /BreadthFirstSearch/103_BinaryTreeZigzagLevelOrderTraversal.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def zigzagLevelOrder(self, root): 14 | if not root: 15 | return [] 16 | 17 | left2right = 1 18 | # 1. scan the level from left to right. -1 reverse. 19 | ans, stack, temp = [], [root], [] 20 | while stack: 21 | temp = [node.val for node in stack] 22 | stack = [child for node in stack 23 | for child in (node.left, node.right) if child] 24 | 25 | ans += [temp[::left2right]] # Pythonic way 26 | left2right *= -1 27 | 28 | return ans 29 | 30 | """ 31 | [] 32 | [1] 33 | [1,2,3] 34 | [0,1,2,3,4,5,6,null,null,7,null,8,9,null,10] 35 | """ 36 | -------------------------------------------------------------------------------- /BreadthFirstSearch/199_BinaryTreeRightSideView.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | # Breadth First Search 14 | def rightSideView(self, root): 15 | if not root: 16 | return [] 17 | cur_level = [root] 18 | next_level = [] 19 | result = [] 20 | while cur_level: 21 | for node in cur_level: 22 | if node.left: 23 | next_level.append(node.left) 24 | if node.right: 25 | next_level.append(node.right) 26 | result.append(cur_level[-1].val) 27 | cur_level = next_level 28 | next_level = [] 29 | return result 30 | 31 | """ 32 | [] 33 | [1,2,3] 34 | [1,2,3,null,4,null,5] 35 | """ 36 | -------------------------------------------------------------------------------- /BreadthFirstSearch/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 广度优先遍历 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Combination/300_LongestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-07 11:38:39 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | /* 10 | The key to the solution is: build a ladder for numbers: dp. 11 | dp[i]: the smallest num of all increasing subsequences with length i+1. 12 | When a new number x comes, compare it with the number in each level: 13 | 1. If x is larger than all levels, append it, increase the size by 1 14 | 2. If dp[i-1] < x <= dp[i], update dp[i] with x. 15 | 16 | According to: 17 | https://leetcode.com/discuss/67554/9-lines-c-code-with-o-nlogn-complexity 18 | */ 19 | int lengthOfLIS(vector& nums) { 20 | vector dp; 21 | for(auto &n : nums){ 22 | auto iter = lower_bound(dp.begin(), dp.end(), n); 23 | if(iter == dp.end()){ 24 | dp.push_back(n); 25 | } 26 | else{ 27 | *iter = n; 28 | } 29 | } 30 | return dp.size(); 31 | } 32 | }; 33 | 34 | 35 | /* 36 | [] 37 | [3] 38 | [1,1,1,1] 39 | [10,9,2,5,3,7,101,18] 40 | */ 41 | -------------------------------------------------------------------------------- /DFA/README.md: -------------------------------------------------------------------------------- 1 | # DFA确定有限状态机 2 | 3 | 解释: 4 | 5 | 6 | 具体题目: 7 | 8 | * 65. Valid Number 9 | 10 | 图解: 11 | 12 | ![][1] 13 | 14 | ![][2] 15 | 16 | 17 | [1]: http://xuelangzf-github.qiniudn.com/LeetCode65_ValidNumber.png 18 | [2]: http://xuelangzf-github.qiniudn.com/LeetCode65_State_change.png 19 | -------------------------------------------------------------------------------- /DepthFirstSearch/129_SumRootToLeafNumbers.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | """ 14 | Depth First Search 15 | """ 16 | def sumNumbers(self, root): 17 | node_stack = [] 18 | path_sum = 0 19 | # Keep the path number from root to the current node. 20 | cur_node_num = 0 21 | 22 | while root or node_stack: 23 | if root: 24 | cur_node_num = cur_node_num * 10 + root.val 25 | node_stack.append([root, cur_node_num]) 26 | root = root.left 27 | 28 | else: 29 | if node_stack: 30 | pop_record = node_stack.pop() 31 | root = pop_record[0].right 32 | cur_node_num = pop_record[1] 33 | # Meet a leaf node 34 | if not pop_record[0].left and not root: 35 | path_sum += cur_node_num 36 | 37 | else: 38 | break 39 | return path_sum 40 | 41 | """ 42 | [] 43 | [1,2,3] 44 | [1,null,2,3,null,null,4,5,6] 45 | """ 46 | -------------------------------------------------------------------------------- /DepthFirstSearch/257_BinaryTreePaths.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.left = None 11 | # self.right = None 12 | 13 | class Solution(object): 14 | def binaryTreePaths(self, root): 15 | if not root: 16 | return [] 17 | node_stack = [[root, str(root.val)]] 18 | path_str = [] 19 | while node_stack: 20 | node, path = node_stack.pop() 21 | if node.left: 22 | new_path = path + "->" + str(node.left.val) 23 | node_stack.append([node.left, new_path]) 24 | if node.right: 25 | new_path = path + "->" + str(node.right.val) 26 | node_stack.append([node.right, new_path]) 27 | if not node.left and not node.right: 28 | path_str.append(path) 29 | return path_str 30 | 31 | """ 32 | [] 33 | [1] 34 | [1,2,3,4,null,null,null,5] 35 | """ 36 | -------------------------------------------------------------------------------- /DepthFirstSearch/98_ValidateBinarySearchTree.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def isValidBST(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: bool 17 | """ 18 | # When do inorder traversal, the val growth bigger. 19 | node_stack = [] 20 | max_val = "init" 21 | while root or node_stack: 22 | if not root: 23 | if not node_stack: 24 | return True 25 | node = node_stack.pop() 26 | if max_val == "init" or node.val > max_val: 27 | max_val = node.val 28 | else: 29 | return False 30 | root = node.right 31 | else: 32 | node_stack.append(root) 33 | root = root.left 34 | return True 35 | 36 | """ 37 | [] 38 | [1] 39 | [1,null,2,3] 40 | [10,5,15,null,null,6,20] 41 | """ 42 | -------------------------------------------------------------------------------- /DepthFirstSearch/README.md: -------------------------------------------------------------------------------- 1 | 深度优先搜索 2 | 3 | 4 | WikiPedia 里对 DFS 的说明如下: 5 | 6 | > Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking. 7 | 8 | 9 | # 一般化实现 10 | 11 | 递归实现 12 | 13 | 14 | def DFS(G, v): 15 | visited[v] = True 16 | for cur_node in v.adjacentNodes(): 17 | if not visited[cur_node]: 18 | # Do something for the current node 19 | DFS(G, cur_node) 20 | 21 | 栈实现 22 | 23 | def DFS(G, v): 24 | nodes = stack() 25 | nodes.push(v) 26 | while not nodes.empty(): 27 | cur_node = nodes.pop() 28 | # Do something for the current node 29 | visited[cur_node] = True 30 | for w in cur_node.adjacentNodes(): 31 | if not visited[w]: 32 | nodes.push(w) 33 | 34 | [Clone Graph](https://leetcode.com/problems/clone-graph/) 是一个图的复制问题,可以用 DFS 来遍历图中所有的顶点。 35 | 36 | # 例子,更好的理解 37 | 38 | ## 282. Expression Add Operators 39 | 40 | # 更多阅读 41 | 42 | [Depth-first search](https://en.wikipedia.org/wiki/Depth-first_search) 43 | 44 | -------------------------------------------------------------------------------- /DivideConquer/215_KthLargestElementArray.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # Simple way: O(nlogn) 8 | def findKthLargest(self, nums, k): 9 | return sorted(nums)[-k] 10 | 11 | 12 | class Solution_2(object): 13 | # QuickSelect, according to: 14 | # http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html 15 | # Heap implement by c++ can be found in c++ version. 16 | def findKthLargest(self, nums, k): 17 | pivot = nums[0] 18 | nums1, nums2 = [], [] 19 | for num in nums: 20 | if num > pivot: 21 | nums1.append(num) 22 | elif num < pivot: 23 | nums2.append(num) 24 | if k <= len(nums1): 25 | return self.findKthLargest(nums1, k) 26 | elif k > len(nums) - len(nums2): 27 | return self.findKthLargest(nums2, k - (len(nums) - len(nums2))) 28 | else: 29 | return pivot 30 | 31 | """ 32 | [1] 33 | 1 34 | [3,2,1,5,6,4] 35 | 2 36 | [1,2,1,3,9] 37 | 2 38 | """ 39 | -------------------------------------------------------------------------------- /DivideConquer/240_Search2DMatrixII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-13 11:50:05 4 | */ 5 | 6 | class Solution { 7 | public: 8 | /* 9 | O(m+n) 10 | Check the top-right corner. 11 | If it's not the target, then remove the top row or rightmost column. 12 | */ 13 | bool searchMatrix(vector>& matrix, int target) { 14 | if(matrix.empty()){ 15 | return false; 16 | } 17 | int m_rows = matrix.size(), n_cols = matrix[0].size(); 18 | int top=0, right=n_cols-1; 19 | while(top=0){ 20 | if(matrix[top][right] > target){ 21 | right -= 1; 22 | } 23 | else if(matrix[top][right] < target){ 24 | top += 1; 25 | } 26 | else{ 27 | return true; 28 | } 29 | } 30 | return false; 31 | } 32 | }; 33 | 34 | /* 35 | [[]] 36 | 0 37 | [[-5]] 38 | -2 39 | [[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24]] 40 | 12 41 | */ 42 | -------------------------------------------------------------------------------- /DivideConquer/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | # 题目 8 | 9 | ### [240 Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) 10 | 11 | > 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列也是按照从上到下的顺序递增,判断该二维数组中是否存在给定的数字。如下例子: 12 | 13 | > [1, 4, 7, 11, 15], 14 | > [2, 5, 8, 12, 19], 15 | > [3, 6, 9, 16, 22], 16 | 17 | 首先选取数组中右上角的数字,如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,剔除这个数字所在的列;如果该数字小于要查找的数字,剔除这个数字所在的行。也就是说每次都在数组的查找范围内剔除一行或者一列。 18 | 19 | [具体实现](https://github.com/xuelangZF/LeetCode/blob/master/DivideConquer/240_Search2DMatrixII.py) 20 | 21 | 22 | -------------------------------------------------------------------------------- /DynamicProgramming/120_Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-10-09 14:22:17 4 | */ 5 | 6 | class Solution { 7 | public: 8 | /* 9 | dp[i][j] is the j-th position's minimum path sum in i-th row. 10 | Then we can find the recursive formula: 11 | dp[i][j] = min(dp[i-1][j-1] if j-1>=0, dp[i-1][j]) + triangle[i][j] 12 | */ 13 | int minimumTotal(vector>& triangle) { 14 | int rows = triangle.size(); 15 | if(rows==0 || triangle[0].size()==0){ 16 | return 0; 17 | } 18 | 19 | std::vector dp(rows, 0); 20 | for(auto lines : triangle){ 21 | for(int i=lines.size()-1; i!=-1; i--){ 22 | if(i-1>=0 && dp[i-1]=0, dp[i-1][j]) + triangle[i][j] 11 | """ 12 | 13 | if not triangle or not triangle[0]: 14 | return 0 15 | rows = len(triangle) 16 | dp = [0 for i in xrange(rows)] 17 | 18 | for lines in triangle: 19 | # Scan from tail to head to reduce space, otherwise we need a 20 | # rows*rows array. 21 | for j in xrange(len(lines) - 1, -1, -1): 22 | if (j - 1 >= 0 and dp[j - 1] < dp[j]) or j == len(lines) - 1: 23 | dp[j] = dp[j - 1] + lines[j] 24 | else: 25 | dp[j] += lines[j] 26 | 27 | return min(dp) 28 | 29 | 30 | """ 31 | [] 32 | [[-10]] 33 | [[2],[3,4],[6,5,7],[1,4,8,3]] 34 | [[2],[3,3],[1,5,0],[4,6,9,3]] 35 | """ 36 | -------------------------------------------------------------------------------- /DynamicProgramming/135_Candy.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def candy(self, ratings): 7 | candies = [0 for i in ratings] 8 | candies[0] = 1 9 | children_nums = len(ratings) 10 | 11 | # Scan from left to right 12 | for i in range(children_nums - 1): 13 | if ratings[i + 1] > ratings[i]: 14 | candies[i + 1] = candies[i] + 1 15 | else: 16 | candies[i + 1] = 1 17 | 18 | minimum_candies = 0 19 | # Scan from right to left 20 | for i in range(children_nums - 1, 0, -1): 21 | if ratings[i - 1] > ratings[i]: 22 | candies[i - 1] = max(candies[i] + 1, candies[i - 1]) 23 | else: 24 | candies[i - 1] = max(1, candies[i - 1]) 25 | minimum_candies += candies[i] 26 | 27 | return minimum_candies + candies[0] 28 | 29 | 30 | """ 31 | [0] 32 | [2,2,1] 33 | [3,4,8,6,7] 34 | [4,3,8,6,7] 35 | [1,2,4,4,3] 36 | [1,2,4,4,5] 37 | [4,4,4,4,4] 38 | """ 39 | -------------------------------------------------------------------------------- /DynamicProgramming/139_WordBreak.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def wordBreak(self, s, wordDict): 7 | """ 8 | :type s: str 9 | :type wordDict: Set[str] 10 | :rtype: bool 11 | """ 12 | if not s: 13 | return True 14 | if not wordDict: 15 | return False 16 | s_len = len(s) 17 | dp = [False for i in range(s_len+1)] 18 | dp[-1] = True 19 | for i in range(s_len-1, -1, -1): 20 | k = 0 21 | while k+i < s_len: 22 | cur_fisrt_word = s[i:i+k+1] 23 | if cur_fisrt_word in wordDict and dp[i+k+1]: 24 | dp[i] = True 25 | break 26 | else: 27 | k += 1 28 | return dp[0] 29 | 30 | """ 31 | "leetcode" 32 | ["leet","code"] 33 | "leetcodecode" 34 | ["leet","code"] 35 | """ 36 | -------------------------------------------------------------------------------- /DynamicProgramming/188_BestTimeBuySellStockIV.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-08-23 14:30:18 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int maxProfit(int k, vector& prices) { 9 | size_t days = prices.size(); 10 | if(k==0 || days<2){ 11 | return 0; 12 | } 13 | 14 | if(k>prices.size()/2){ 15 | return solve_quickly(prices); 16 | } 17 | 18 | vector> dp(k+1, vector(days, 0)); 19 | for(int i=1; i<= k; i++){ 20 | int max_buy = -prices[0]; 21 | for(int j=1; j &prices){ 30 | int max_profit = 0; 31 | for(int i=1; i 0 ? diff : 0; 34 | } 35 | return max_profit; 36 | } 37 | }; 38 | 39 | /* 40 | 1 41 | [8,5,3] 42 | 2 43 | [1,8,3,2,7,12,7,15,16,17] 44 | 4 45 | [1,8,3,2,7,12,7,15,16,17] 46 | */ 47 | -------------------------------------------------------------------------------- /DynamicProgramming/198_HouseRobber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | # Dynamic Programming 7 | def rob(self, nums): 8 | if not nums: 9 | return 0 10 | pre_rob = 0 11 | pre_not_rob = 0 12 | for num in nums: 13 | cur_rob = pre_not_rob + num 14 | cur_not_rob = max(pre_rob, pre_not_rob) 15 | pre_rob = cur_rob 16 | pre_not_rob = cur_not_rob 17 | return max(pre_rob, pre_not_rob) 18 | 19 | """ 20 | [] 21 | [1,2] 22 | [12, 1,1,12,1] 23 | """ 24 | -------------------------------------------------------------------------------- /DynamicProgramming/213_HouseRobberII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # Dynamic Programming 8 | def rob(self, nums): 9 | if not nums: 10 | return 0 11 | # We can break the circle according to whether rob house 0 or not. 12 | return max(self.rob_line(nums[1:]), # Not rob first house 13 | self.rob_line(nums[2:-1]) + nums[0]) # Rob first house 14 | 15 | def rob_line(self, nums): 16 | if not nums: 17 | return 0 18 | pre_rob = nums[0] 19 | pre_not_rob = 0 20 | for num in nums[1:]: 21 | cur_rob = pre_not_rob + num 22 | cur_not_rob = max(pre_rob, pre_not_rob) 23 | pre_rob = cur_rob 24 | pre_not_rob = cur_not_rob 25 | return max(pre_rob, pre_not_rob) 26 | 27 | """ 28 | [] 29 | [1,2] 30 | [12, 1,1,12,1] 31 | """ 32 | -------------------------------------------------------------------------------- /DynamicProgramming/264_UglyNumberII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-15 22:44:13 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int nthUglyNumber(int n) { 10 | if(n<=0){ 11 | return -1; 12 | } 13 | vector uglys(n, 1); 14 | int p_2=0, p_3=0, p_5=0; 15 | for(int i=1; i& primes) { 12 | vector index(primes.size(), 0), ugly_numbers(n, INT_MAX); 13 | ugly_numbers[0] = 1; 14 | for(int i=1; i dp(s.size(),0); 24 | for(int i=1; i < s.length(); i++){ 25 | if(s[i] == ')' && i-dp[i-1]-1>=0 && s[i-dp[i-1]-1] == '('){ 26 | dp[i] = dp[i-1] + 2 + dp[i-dp[i-1]-2]; 27 | curMax = max(dp[i],curMax); 28 | } 29 | } 30 | return curMax; 31 | } 32 | }; 33 | 34 | /* 35 | "" 36 | ")" 37 | "()" 38 | "))" 39 | "(((()()()))(" 40 | "(((()()()))())" 41 | */ 42 | -------------------------------------------------------------------------------- /DynamicProgramming/32_LongestValidParentheses.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def longestValidParentheses(self, s): 7 | """ 8 | According to: 9 | https://leetcode.com/discuss/8092/my-dp-o-n-solution-without-using-stack 10 | 11 | dp[i]: the longest length of valid parentheses which ends at i. Then: 12 | 13 | 1. s[i] is '(', dp[i] = 0 14 | 2. s[i] is ')' 15 | a. s[i-dp[i-1]-1] == '(': dp = dp[i-1] + 2 + dp[i-dp[i-1]-2] 16 | b. dp[i] = 0 17 | 18 | Just think about what does s[i-dp[i-1]-1] == '(' mean. 19 | """ 20 | if not s: 21 | return 0 22 | 23 | dp = [0] * len(s) 24 | max_len = 0 25 | for i in xrange(1, len(s)): 26 | if s[i] == ")" and i - 1 - dp[i - 1] >= 0 and s[i - 1 - dp[i - 1]] == "(": 27 | dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] - 2] 28 | max_len = max(max_len, dp[i]) 29 | 30 | return max_len 31 | 32 | """ 33 | "" 34 | ")" 35 | "()" 36 | "))" 37 | "(((()()()))(" 38 | "(((()()()))())" 39 | """ 40 | -------------------------------------------------------------------------------- /DynamicProgramming/337_HouseRobberIII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-02 16:21:11 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | int rob(TreeNode* root) { 18 | map cache; 19 | return rob_dp(root, cache); 20 | } 21 | 22 | int rob_dp(TreeNode* root, map &cache){ 23 | if(root==NULL){ 24 | return 0; 25 | } 26 | if(cache.find(root)!=cache.end()){ 27 | return cache[root]; 28 | } 29 | int money = root->val; 30 | if(root->left!=NULL){ 31 | money += rob_dp(root->left->left, cache) + rob_dp(root->left->right, cache); 32 | } 33 | if(root->right!=NULL){ 34 | money += rob_dp(root->right->left, cache) + rob_dp(root->right->right, cache); 35 | } 36 | cache[root] = max(money, rob_dp(root->left, cache) + rob_dp(root->right, cache)); 37 | return cache[root]; 38 | } 39 | }; 40 | 41 | /* 42 | [] 43 | [3,4,5,1,3,null,1] 44 | [3,2,3,null,3,null,1] 45 | */ 46 | -------------------------------------------------------------------------------- /DynamicProgramming/357_CountNumbersWithUniqueDigits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-08 10:45:15 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | int countNumbersWithUniqueDigits(int n) { 10 | if(n==0){ 11 | return 1; 12 | } 13 | if(n==1){ 14 | return 10; 15 | } 16 | if(n==2){ 17 | return 91; 18 | } 19 | vector dp(n+1, 0); 20 | dp[1] = 10; 21 | dp[2] = 81; 22 | int result = 91; 23 | for(int i=3; i& nums) { 10 | int nums_len = nums.size(); 11 | int pre_sum = nums[0]; 12 | int max_sum = nums[0]; 13 | 14 | for(int i=1;i>& obstacleGrid) { 9 | int rows = obstacleGrid.size(); 10 | if(rows==0){ 11 | return 0; 12 | } 13 | int cols = obstacleGrid[0].size(); 14 | vector> dp(rows+1, vector(cols+1, 0)); 15 | 16 | dp[0][1] = 1; 17 | for(int i=1; i>& grid) { 9 | if(grid.size()==0){ 10 | return 0; 11 | } 12 | int rows = grid.size(); 13 | int cols = grid[0].size(); 14 | 15 | vector> dp(rows, vector(cols, 0)); 16 | for(int i=0; i0){ 20 | dp[i][j] += dp[i][j-1]; 21 | } 22 | else if(j==0 && i>0){ 23 | dp[i][j] += dp[i-1][j]; 24 | } 25 | else if(j > 0 && i>0){ 26 | dp[i][j] += min(dp[i-1][j], dp[i][j-1]); 27 | } 28 | } 29 | } 30 | return dp[rows-1][cols-1]; 31 | } 32 | }; 33 | 34 | /* 35 | [] 36 | [[0]] 37 | [[1,2,4,3,2,1,5],[3,4,1,2,3,5,4],[3,2,4,5,1,2,5]] 38 | */ 39 | -------------------------------------------------------------------------------- /DynamicProgramming/64_MinimumPathSum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def minPathSum(self, grid): 7 | if not grid: 8 | return 0 9 | 10 | m_row = len(grid) 11 | n_col = len(grid[0]) 12 | 13 | # dp[i][j]: the min sum along path from top left to [i,j]. 14 | dp = [[0 for i in range(n_col)] for j in range(m_row)] 15 | 16 | for row in range(m_row): 17 | for col in range(n_col): 18 | dp[row][col] = grid[row][col] 19 | if row == 0 and col > 0: 20 | dp[row][col] += dp[row][col - 1] 21 | elif row > 0 and col == 0: 22 | dp[row][col] += dp[row - 1][col] 23 | elif row > 0 and col > 0: 24 | dp[row][col] += min(dp[row - 1][col], dp[row][col - 1]) 25 | else: 26 | pass 27 | 28 | return dp[m_row - 1][n_col - 1] 29 | 30 | 31 | """ 32 | [] 33 | [[0]] 34 | [[1,2,4,3,2,1,5],[3,4,1,2,3,5,4],[3,2,4,5,1,2,5]] 35 | """ 36 | -------------------------------------------------------------------------------- /DynamicProgramming/70_ClimbingStairs.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def climbStairs(self, n): 7 | """ 8 | :type n: int 9 | :rtype: int 10 | """ 11 | if not n: 12 | return 1 13 | 14 | dp = [0 for i in range(n)] 15 | dp[0] = 1 16 | if n > 1: 17 | dp[1] = 2 18 | for i in range(2, n): 19 | dp[i] = dp[i-1] + dp[i-2] 20 | 21 | return dp[n-1] 22 | -------------------------------------------------------------------------------- /DynamicProgramming/72_EditDistance.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def minDistance(self, word1, word2): 7 | """ 8 | :type word1: str 9 | :type word2: str 10 | :rtype: int 11 | """ 12 | len_w1 = len(word1) 13 | len_w2 = len(word2) 14 | 15 | # dp[i][j]: minimum number of steps convert word1[0,i) to word2[0,j) 16 | dp = [[0 for j in range(len_w2+1)] for i in range(len_w1+1)] 17 | 18 | # initial the dp array 19 | dp[0][0] = 0 20 | for j in range(1, len_w2+1): 21 | dp[0][j] = j 22 | for i in range(1, len_w1+1): 23 | dp[i][0] = i 24 | 25 | for i in range(1, len_w1+1): 26 | for j in range(1, len_w2+1): 27 | if word1[i-1] == word2[j-1]: 28 | dp[i][j] = dp[i-1][j-1] 29 | else: 30 | dp[i][j] = min( 31 | dp[i-1][j-1] + 1, 32 | dp[i-1][j] + 1, 33 | dp[i][j-1] + 1,) 34 | 35 | return dp[len_w1][len_w2] 36 | -------------------------------------------------------------------------------- /DynamicProgramming/91_DecodeWays.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | 7 | def numDecodings(self, s): 8 | """ 9 | :type s: str 10 | :rtype: int 11 | """ 12 | if not s or s[0] == "0": 13 | return 0 14 | 15 | len_s = len(s) 16 | # dp[i]: total number of ways to decode s[0:i) 17 | dp = [1 for i in range(len_s + 1)] 18 | for i in range(1, len_s): 19 | pre_num = ord(s[i - 1]) - ord('0') 20 | cur_num = ord(s[i]) - ord('0') 21 | num = pre_num * 10 + cur_num 22 | 23 | if cur_num == 0: 24 | if num > 26 or num == 0: 25 | return 0 26 | else: 27 | dp[i+1] = dp[i-1] 28 | 29 | else: 30 | if num <= 26 and pre_num != 0: 31 | dp[i + 1] = dp[i] + dp[i - 1] 32 | else: 33 | dp[i + 1] = dp[i] 34 | 35 | return dp[len_s] 36 | 37 | """ 38 | "" 39 | "123" 40 | "1238" 41 | "172731349111222" 42 | "0" 43 | "10203" 44 | """ 45 | -------------------------------------------------------------------------------- /Graph/133_CloneGraph.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a undirected graph node 6 | # class UndirectedGraphNode(object): 7 | # def __init__(self, x): 8 | # self.label = x 9 | # self.neighbors = [] 10 | 11 | class Solution(object): 12 | def cloneGraph(self, node): 13 | if not node: 14 | return None 15 | 16 | copyed_node_pair = {} 17 | copy_head = UndirectedGraphNode(node.label) 18 | copy_head.neighbors = [] 19 | copyed_node_pair[node] = copy_head 20 | 21 | nodes_stack = [] 22 | nodes_stack.append(node) 23 | while nodes_stack: 24 | one_node = nodes_stack.pop() 25 | 26 | for neighbor in one_node.neighbors: 27 | if neighbor not in copyed_node_pair: 28 | copy_node = UndirectedGraphNode(neighbor.label) 29 | copy_node.neighbors = [] 30 | copyed_node_pair[neighbor] = copy_node 31 | nodes_stack.append(neighbor) 32 | 33 | copyed_node_pair[one_node].neighbors.append( 34 | copyed_node_pair[neighbor]) 35 | 36 | return copy_head 37 | 38 | """ 39 | {0,0,0} 40 | {0,1,2#1,2#2,2} 41 | """ 42 | -------------------------------------------------------------------------------- /Graph/README.md: -------------------------------------------------------------------------------- 1 | 图(Graph)是由顶点的有穷非空集合和顶点之间边的集合组成,通常表示为:G(V,E),其中,G表示一个图,V是图G中顶点的集合,E是图G中边的集合。 2 | 3 | 简单的概念: 4 | 5 | * `无向边`: 若顶点vi到vj之间的边没有方向,则称这条边为无向边(Edge),用无序偶对(vi,vj)来表示。 6 | * `无向图`: 如果图中任意两个顶点之间的边都是无向边,则称该图为无向图(Undirected graphs)。 7 | * `有向边`:若从顶点vi到vj的边有方向,则称这条边为有向边,也称为弧(Arc)。用有序偶来表示,vi称为弧尾(Tail),vj称为弧头(Head)。 8 | * `有向图`: 如果图中任意两个顶点之间的边都是有向边,则称该图为有向图(Directed graphs)。 9 | 10 | 对于下面的无向图G1来说,G1=(V1,{E1}),其中顶点集合V1={A,B,C,D};边集合E1={(A,B),(B,C),(C,D),(D,A),(A,C)}。对于下有向图G2来说,G2=(V2,{E2}),其中顶点集合V2={A,B,C,D};弧集合E2={, , (B,C), }。 11 | 12 | ![][1] 13 | 14 | 15 | 16 | # 更多阅读 17 | 18 | [数据结构之图](https://www.zybuluo.com/guoxs/note/249812) 19 | 20 | [1]: ../Images/Graph_1.png 21 | 22 | -------------------------------------------------------------------------------- /Greedy/122_BestTimeToBuyAndSellStockII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-08-22 20:03:11 4 | */ 5 | 6 | class Solution { 7 | public: 8 | /* 9 | As long as there is a price gap, we gain a profit. 10 | */ 11 | int maxProfit(vector& prices) { 12 | int max_profit = 0; 13 | for(int i=1; i 0 ? diff : 0); 16 | } 17 | return max_profit; 18 | } 19 | }; 20 | 21 | /* 22 | [] 23 | [3,4,5,6,2,4] 24 | [6,5,4,3,2,1] 25 | [1,2,3,4,3,2,1,9,11,2,20] 26 | */ 27 | -------------------------------------------------------------------------------- /Greedy/122_BestTimeToBuyAndSellStockII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | """ As long as there is a price gap, we gain a profit. 7 | """ 8 | def maxProfit(self, prices): 9 | max_profit = 0 10 | for i in range(1, len(prices)): 11 | diff = prices[i] - prices[i - 1] 12 | if diff > 0: 13 | max_profit += diff 14 | return max_profit 15 | 16 | """ 17 | [] 18 | [3,4,5,6,2,4] 19 | [6,5,4,3,2,1] 20 | [1,2,3,4,3,2,1,9,11,2,20] 21 | """ 22 | -------------------------------------------------------------------------------- /Greedy/45_JumpGameII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-26 09:32:27 4 | */ 5 | 6 | class Solution { 7 | public: 8 | /* 9 | When you can reach position i, find the next longest distance you can reach. 10 | 11 | Once we can reach position i, we can find the next longest distance by iterate all 12 | the position before position i. 13 | 14 | Of course, you can think it as a BFS problem. 15 | Where nodes in level i are all the nodes that can be reached in i-1th jump. 16 | For more explnation, goto: 17 | https://discuss.leetcode.com/topic/3191/o-n-bfs-solution 18 | */ 19 | int jump(vector& nums) { 20 | if(nums.size() == 1) return 0; 21 | int step = 1, longest = nums[0]; 22 | int index = 1; 23 | while(longest < nums.size()-1){ 24 | int max_instance = 0; 25 | while(index <= longest){ 26 | if(index + nums[index] > max_instance){ 27 | max_instance = index + nums[index]; 28 | } 29 | index += 1; 30 | } 31 | step += 1; 32 | longest = max_instance; 33 | } 34 | return step; 35 | } 36 | }; 37 | 38 | /* 39 | [0] 40 | [2,5,0,3] 41 | [2,3,1,1,4] 42 | [3,1,8,1,1,1,1,1,5] 43 | */ 44 | -------------------------------------------------------------------------------- /Greedy/45_JumpGameII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def jump(self, nums): 7 | """ When you can reach position i, find the next longest distance you can reach. 8 | 9 | Once we can reach position i, we can find the next longest distance by iterate all 10 | the position before position i. 11 | 12 | Of course, you can think it as a BFS problem. 13 | Where nodes in level i are all the nodes that can be reached in i-1th jump. 14 | For more explnation, goto: 15 | https://discuss.leetcode.com/topic/3191/o-n-bfs-solution 16 | """ 17 | if len(nums) == 1: 18 | return 0 19 | 20 | last = nums[0] 21 | step = 1 22 | index = 1 23 | while last < len(nums) - 1: 24 | max_distance = 0 25 | while index <= last: 26 | if nums[index] + index > max_distance: 27 | max_distance = nums[index] + index 28 | index += 1 29 | 30 | last = max_distance 31 | step += 1 32 | 33 | return step 34 | 35 | """ 36 | [0] 37 | [2,5,0,3] 38 | [2,3,1,1,4] 39 | [3,1,8,1,1,1,1,1,5] 40 | """ 41 | -------------------------------------------------------------------------------- /Greedy/55_JumpGame.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-06-27 13:06:01 4 | */ 5 | 6 | class Solution { 7 | public: 8 | bool canJump(vector& nums) { 9 | /* 10 | The main idea is to see if current element can be 11 | reached by previous max jump. 12 | If not, return false. If true, renew the max jump. 13 | */ 14 | int length = nums.size(); 15 | int max_distance = nums[0]; 16 | 17 | for(int i=0; i= length-1){ 19 | return true; 20 | } 21 | if(max_distance >= i){ 22 | max_distance = max(max_distance, i+nums[i]); 23 | } 24 | else{ 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | }; 31 | 32 | /* 33 | [0] 34 | [2,3,1,1,4] 35 | [3,2,1,0,4] 36 | [1,3,5,0,0,0,0,0] 37 | */ 38 | -------------------------------------------------------------------------------- /Greedy/55_JumpGame.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-06-27 12:58:19 5 | 6 | 7 | class Solution(object): 8 | def canJump(self, nums): 9 | """ 10 | The main idea is to see if current element can be 11 | reached by previous max jump. 12 | If not, return false. If true, renew the max jump. 13 | """ 14 | length = len(nums) 15 | index, max_distance = 0, nums[0] 16 | 17 | while index < length: 18 | # Prune here. 19 | if max_distance >= length - 1: 20 | return True 21 | 22 | if max_distance >= index: 23 | max_distance = max(max_distance, index + nums[index]) 24 | else: 25 | # Current position cannot be reached. 26 | return False 27 | index += 1 28 | 29 | return True 30 | 31 | """ 32 | [0] 33 | [2,3,1,1,4] 34 | [3,2,1,0,4] 35 | [1,3,5,0,0,0,0,0] 36 | """ 37 | -------------------------------------------------------------------------------- /Greedy/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Greedy/README.md -------------------------------------------------------------------------------- /HashTable/01_TwoSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-14 10:43:27 4 | */ 5 | 6 | 7 | class Solution { 8 | public: 9 | vector twoSum(vector& nums, int target) { 10 | map hash; 11 | for(int i=0;i max_length: 27 | max_length = end - start + 1 28 | char_dict[char] = index 29 | 30 | return max_length 31 | 32 | """ 33 | "" 34 | "bbbbb" 35 | "abcabcbb" 36 | """ 37 | -------------------------------------------------------------------------------- /HashTable/128_LongestConsecutiveSequence.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def longestConsecutive(self, nums): 7 | """ 8 | Build a hash to find whether a num in nums or not in O(1) time. 9 | """ 10 | nums_dict = {num: False for num in nums} 11 | max_length = 0 12 | for num in nums: 13 | if nums_dict[num]: 14 | continue 15 | 16 | # Find the post consecutive number 17 | next_num = num + 1 18 | while next_num in nums_dict: 19 | nums_dict[next_num] = True 20 | next_num += 1 21 | 22 | # Find the pre consecutive number 23 | pre_num = num - 1 24 | while pre_num in nums_dict: 25 | nums_dict[pre_num] = True 26 | pre_num -= 1 27 | 28 | max_length = max(next_num-pre_num-1, max_length) 29 | 30 | return max_length 31 | 32 | """ 33 | [] 34 | [0] 35 | [100, 4, 200, 1, 3, 2] 36 | [2147483646,-2147483647,0,2,2147483644,-2147483645,2147483645] 37 | """ 38 | -------------------------------------------------------------------------------- /HashTable/146_LRUCache_pythonic.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import collections 4 | 5 | 6 | class LRUCache: 7 | def __init__(self, capacity): 8 | self.capacity = capacity 9 | # An OrderedDict is a dictionary subclass 10 | # that remembers the order in which its contents are added. 11 | self.cache = collections.OrderedDict() 12 | 13 | def get(self, key): 14 | if key not in self.cache: 15 | return -1 16 | value = self.cache.pop(key) 17 | self.cache[key] = value 18 | return value 19 | 20 | def set(self, key, value): 21 | if key in self.cache: 22 | self.cache.pop(key) 23 | elif len(self.cache) == self.capacity: 24 | self.cache.popitem(last=False) 25 | else: 26 | pass 27 | self.cache[key] = value 28 | 29 | """ 30 | if __name__ == '__main__': 31 | ca = LRUCache(2) 32 | ca.set(2, 1) 33 | print "AA", ca.get(2) 34 | ca.set(2, 2) 35 | print "BB", ca.get(2) 36 | ca.set(3, 3) 37 | print "CC", ca.get(3) 38 | # what if: print "CC", ca.get(2) 39 | ca.set(4, 1) 40 | print "CC", ca.get(2) 41 | """ 42 | -------------------------------------------------------------------------------- /HashTable/187_RepeatedDNASequences.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def findRepeatedDnaSequences(self, s): 7 | str_hash = {} 8 | sequence = [] 9 | len_s = len(s) 10 | for i in range(len_s-9): 11 | cur_str = s[i:i+10] 12 | str_hash[cur_str] = str_hash.get(cur_str, 0) + 1 13 | if str_hash[cur_str] == 2: 14 | sequence.append(cur_str) 15 | return sequence 16 | 17 | 18 | """ 19 | "AAA" 20 | "AAAAAAAAAA" 21 | "AAAAAAAAAAA" 22 | "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 23 | """ 24 | -------------------------------------------------------------------------------- /HashTable/217_ContainsDuplicate.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def containsDuplicate(self, nums): 8 | hash_dict = {} 9 | for num in nums: 10 | if num in hash_dict: 11 | return True 12 | hash_dict[num] = 1 13 | return False 14 | 15 | """ 16 | [] 17 | [1,2,3,3] 18 | [1,2,3,4,1] 19 | """ 20 | -------------------------------------------------------------------------------- /HashTable/219_ContainsDuplicateII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def containsNearbyDuplicate(self, nums, k): 8 | hash_dict = {} 9 | if not nums: 10 | return False 11 | len_nums = len(nums) 12 | for i in range(len_nums): 13 | num = nums[i] 14 | if num in hash_dict and i - hash_dict[num] <= k: 15 | return True 16 | hash_dict[num] = i 17 | return False 18 | 19 | """ 20 | [] 21 | 3 22 | [1,2,3,3] 23 | 1 24 | [1,2,3,4,1] 25 | 3 26 | """ 27 | -------------------------------------------------------------------------------- /HashTable/242_ValidAnagram.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def isAnagram(self, s, t): 8 | char_hash = {} 9 | for c in s: 10 | char_hash[c] = char_hash.get(c, 0) + 1 11 | 12 | for c in t: 13 | if c not in char_hash: 14 | return False 15 | char_hash[c] -= 1 16 | if char_hash[c] < 0: 17 | return False 18 | return not sum(char_hash.values()) 19 | 20 | """ 21 | "" 22 | "" 23 | "acd" 24 | "ac" 25 | "anagram" 26 | "nagaram" 27 | "rat" 28 | "car" 29 | """ 30 | -------------------------------------------------------------------------------- /HashTable/274_H-Index.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # An easy approach which sorts the array first. 8 | def hIndex(self, citations): 9 | if not citations: 10 | return 0 11 | citations.sort() 12 | length = len(citations) 13 | for i in range(length, 0, -1): 14 | if citations[length-i] >= i: 15 | return i 16 | return 0 17 | 18 | 19 | class Solution_2(object): 20 | # A faster approach use extra space. 21 | def hIndex(self, citations): 22 | length = len(citations) 23 | count = [0] * (length + 1) 24 | for i in citations: 25 | if i >= length: 26 | count[length] += 1 27 | else: 28 | count[i] += 1 29 | occur = 0 30 | # Dynamic programming here to 31 | # Sum the occuring times of citations bigger than one given value 32 | for i in range(length, 0, -1): 33 | occur += count[i] 34 | if occur >= i: 35 | return i 36 | return 0 37 | 38 | """ 39 | [] 40 | [0] 41 | [23] 42 | [4,4,4,4] 43 | [4, 0, 6, 1, 5] 44 | """ 45 | -------------------------------------------------------------------------------- /HashTable/290_WordPattern.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def wordPattern(self, pattern, str): 8 | words = str.split(" ") 9 | if len(pattern) != len(words): 10 | return False 11 | 12 | char_word = {} 13 | for i, char in enumerate(pattern): 14 | if char in char_word and char_word[char] != words[i]: 15 | return False 16 | if char not in char_word: 17 | char_word[char] = words[i] 18 | 19 | word_char = {} 20 | for j, word in enumerate(words): 21 | if word in word_char and word_char[word] != pattern[j]: 22 | return False 23 | if word not in word_char: 24 | word_char[word] = pattern[j] 25 | return True 26 | 27 | """ 28 | "" 29 | "" 30 | "a" 31 | "are" 32 | "abba" 33 | "dog cat cat dog" 34 | "abb" 35 | "dog cat cat" 36 | "aba" 37 | "dog dog dog" 38 | """ 39 | -------------------------------------------------------------------------------- /HashTable/299_BullsAndCows.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def getHint(self, secret, guess): 8 | secret = list(secret) 9 | guess = list(guess) 10 | 11 | bulls, cows = 0, 0 12 | hash_secret = {} 13 | hash_guess = {} 14 | for i in range(len(secret)): 15 | sec, gue = secret[i], guess[i] 16 | if sec == gue: 17 | bulls += 1 18 | else: 19 | hash_guess[gue] = hash_guess.get(gue, 0) + 1 20 | hash_secret[sec] = hash_secret.get(sec, 0) + 1 21 | for digit in hash_secret: 22 | if digit in hash_guess: 23 | cows += min(hash_guess[digit], hash_secret[digit]) 24 | return "".join([str(bulls), "A", str(cows), "B"]) 25 | 26 | 27 | """ 28 | "" 29 | "" 30 | "1807" 31 | "7810" 32 | "1123" 33 | "1111" 34 | "1123" 35 | "0111" 36 | """ 37 | -------------------------------------------------------------------------------- /HashTable/350_IntersectionOfTwoArraysII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-07-02 10:47:23 5 | 6 | 7 | class Solution(object): 8 | def intersect(self, nums1, nums2): 9 | nums1_dict = {} 10 | for n in nums1: 11 | nums1_dict[n] = nums1_dict.get(n, 0) + 1 12 | ans = [] 13 | for n in nums2: 14 | if nums1_dict.get(n, 0) > 0: 15 | ans.append(n) 16 | nums1_dict[n] = nums1_dict.get(n, 0) - 1 17 | return ans 18 | 19 | 20 | class Solution_2(object): 21 | def intersect(self, nums1, nums2): 22 | nums1.sort() 23 | nums2.sort() 24 | i, j = 0, 0 25 | ans = [] 26 | while i < len(nums1) and j < len(nums2): 27 | if nums1[i] == nums2[j]: 28 | ans.append(nums1[i]) 29 | i += 1 30 | j += 1 31 | elif nums1[i] < nums2[j]: 32 | i += 1 33 | else: 34 | j += 1 35 | return ans 36 | 37 | """ 38 | [] 39 | [] 40 | [1,2,2,2,3] 41 | [3,2,2,2,3] 42 | [1, 2, 2, 1] 43 | [2, 2] 44 | """ 45 | -------------------------------------------------------------------------------- /HashTable/36_ValidSudoku.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-07-17 10:15:37 4 | */ 5 | 6 | class Solution 7 | { 8 | public: 9 | /* Hash Table 10 | Use three 9*9 array to keep the used numbers in row, col, panel. 11 | According to: 12 | https://discuss.leetcode.com/topic/8241/my-short-solution-by-c-o-n2 13 | */ 14 | bool isValidSudoku(vector > &board) 15 | { 16 | int row[9][9] = {0}, col[9][9] = {0}, panel[9][9] = {0}; 17 | 18 | for(int i = 0; i < board.size(); ++i) 19 | for(int j = 0; j < board[i].size(); ++j) 20 | if(board[i][j] != '.') 21 | { 22 | int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3; 23 | if(row[i][num] || col[j][num] || panel[k][num]) 24 | return false; 25 | row[i][num] = col[j][num] = panel[k][num] = 1; 26 | } 27 | 28 | return true; 29 | } 30 | }; 31 | 32 | /* 33 | ["..4...63.",".........","5......9.","...56....","4.3.....1","...7.....","...5.....",".........","........."] 34 | [".87654321","2........","3........","4........","5........","6........","7........","8........","9........"] 35 | */ 36 | -------------------------------------------------------------------------------- /HashTable/49_GroupAnagrams.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-06-26 19:18:40 5 | 6 | 7 | class Solution(object): 8 | def groupAnagrams(self, strs): 9 | """Hash tables: use sorted(word) as key. 10 | 11 | Note that list is unhashable type, so we need to change sorted 12 | str to tuple, which is hashable type. 13 | """ 14 | d = {} 15 | for w in sorted(strs): 16 | key = tuple(sorted(w)) 17 | d[key] = d.get(key, []) + [w] 18 | return d.values() 19 | 20 | """ 21 | [""] 22 | ["aaa", "aaa", "aa", "bb"] 23 | ["a", "b", "c", "d"] 24 | """ 25 | -------------------------------------------------------------------------------- /Heap/347_TopKFrequentElements.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-07-09 09:41:55 5 | 6 | 7 | class Solution(object): 8 | def topKFrequent(self, nums, k): 9 | """ Given a non-empty array of integers, return the k most frequent elements. 10 | 11 | heapq.nlargest(n, iterable[, key]) 12 | Return a list with the n largest elements from the dataset defined by iterable. 13 | """ 14 | num_count = collections.Counter(nums) 15 | return heapq.nlargest(k, num_count, key=lambda x: num_count[x]) 16 | 17 | 18 | class Solution_2(object): 19 | def topKFrequent(self, nums, k): 20 | ''' Use Counter to extract the top k frequent elements 21 | 22 | most_common(k) return a list of tuples, 23 | where the first item of the tuple is the element, 24 | and the second item of the tuple is the count 25 | Thus, the built-in zip function could be used to extract 26 | the first item from the tuples 27 | ''' 28 | return zip(*collections.Counter(nums).most_common(k))[0] 29 | 30 | """ 31 | [1,1,1,2,2,3] 32 | 2 33 | [1,1,2,3,3,3,4,4,4,4,1,1,1] 34 | 3 35 | """ 36 | -------------------------------------------------------------------------------- /Heap/README.md: -------------------------------------------------------------------------------- 1 | 堆(Heap)是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵树的数组对象。在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短小,但具有重要性的作业,同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。 2 | 3 | 简单地说堆就是一种有序队列,普通的队列是先入先出,而二叉堆是:最小(最大)先出。 4 | 5 | # 更多内容 6 | 7 | [数据结构系列——堆](http://vickyqi.com/2015/11/19/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%B3%BB%E5%88%97%E2%80%94%E2%80%94%E5%A0%86/) 8 | 9 | -------------------------------------------------------------------------------- /Images/223_rectangle_area.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/223_rectangle_area.png -------------------------------------------------------------------------------- /Images/65_StateConvert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/65_StateConvert.png -------------------------------------------------------------------------------- /Images/65_ValidNumber.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/65_ValidNumber.png -------------------------------------------------------------------------------- /Images/Backtracking_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/Backtracking_1.png -------------------------------------------------------------------------------- /Images/Backtracking_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/Backtracking_2.png -------------------------------------------------------------------------------- /Images/Backtracking_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/Backtracking_3.png -------------------------------------------------------------------------------- /Images/Backtracking_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/Backtracking_4.png -------------------------------------------------------------------------------- /Images/Graph_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/Graph_1.png -------------------------------------------------------------------------------- /Images/Tree_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/Tree_1.jpg -------------------------------------------------------------------------------- /Images/Tree_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/Tree_2.jpg -------------------------------------------------------------------------------- /Images/stack_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/Images/stack_demo.png -------------------------------------------------------------------------------- /LinkedList/147_InsertionSortList.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for singly-linked list. 6 | # class ListNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | class Solution(object): 12 | def insertionSortList(self, head): 13 | if not head or not head.next: 14 | return head 15 | 16 | dummy = ListNode(0) 17 | start = dummy 18 | while head: 19 | cur_node = head 20 | head = head.next 21 | # Don't need to scan from head of the sorted list every time. 22 | if start.val > cur_node.val: 23 | start = dummy 24 | # Find the insert position. 25 | while start.next and start.next.val < cur_node.val: 26 | start = start.next 27 | # Insert the current node. 28 | cur_node.next = start.next 29 | start.next = cur_node 30 | 31 | return dummy.next 32 | """ 33 | [] 34 | [1] 35 | [1,2] 36 | [5,1,2] 37 | [5,1,2,3] 38 | """ 39 | -------------------------------------------------------------------------------- /LinkedList/160_IntersectionOfTwoLinkedLists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-20 11:28:51 4 | */ 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode(int x) : val(x), next(NULL) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | // Refer to: 17 | // https://leetcode.com/discuss/17278/accepted-shortest-explaining-algorithm-comments-improvements 18 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 19 | ListNode *p1 = headA; 20 | ListNode *p2 = headB; 21 | while(p1!=p2){ 22 | p1 = (p1==NULL ? headB : p1->next); 23 | p2 = (p2==NULL ? headA : p2->next); 24 | } 25 | return p1; 26 | } 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /LinkedList/160_IntersectionOfTwoLinkedLists.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for singly-linked list. 6 | # class ListNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | 12 | class Solution(object): 13 | def getIntersectionNode(self, headA, headB): 14 | # Refer to: 15 | # https://leetcode.com/discuss/17278/accepted-shortest-explaining-algorithm-comments-improvements 16 | p1, p2 = headA, headB 17 | while(p1 != p2): 18 | p1 = headB if not p1 else p1.next 19 | p2 = headA if not p2 else p2.next 20 | return p1 21 | -------------------------------------------------------------------------------- /LinkedList/203_RemoveLinkedListElements.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for singly-linked list. 6 | # class ListNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | class Solution(object): 12 | def removeElements(self, head, val): 13 | pre_node = dummy = ListNode(0) 14 | while head: 15 | if head.val == val: 16 | pre_node.next = None 17 | else: 18 | pre_node.next = head 19 | pre_node = head 20 | head = head.next 21 | return dummy.next 22 | 23 | """ 24 | [] 25 | 1 26 | [1,1,1] 27 | 1 28 | [1,2,3] 29 | 2 30 | [1,2] 31 | 2 32 | """ 33 | -------------------------------------------------------------------------------- /LinkedList/206_ReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-17 17:26:46 4 | */ 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode(int x) : val(x), next(NULL) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | // Recursively reverse 17 | ListNode* reverseList(ListNode* head) { 18 | if(head==NULL || head->next == NULL){ 19 | return head; 20 | } 21 | ListNode *reversed_head = reverseList(head->next); 22 | head->next->next = head; 23 | head->next = NULL; 24 | return reversed_head; 25 | } 26 | }; 27 | 28 | class Solution_2 { 29 | public: 30 | // Itratively reverse 31 | ListNode* reverseList(ListNode* head) { 32 | ListNode *new_head = NULL; 33 | while(head!=NULL){ 34 | ListNode *next_node = head->next; 35 | head->next = new_head; 36 | new_head = head; 37 | head = next_node; 38 | } 39 | return new_head; 40 | } 41 | }; 42 | 43 | /* 44 | [] 45 | [1] 46 | [1,2] 47 | [1,2,3,4,5] 48 | */ 49 | -------------------------------------------------------------------------------- /LinkedList/206_ReverseLinkedList.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.next = None 11 | 12 | class Solution(object): 13 | # recursively reverse 14 | def reverseList(self, head): 15 | if not head or not head.next: 16 | return head 17 | reverse_head = self.reverseList(head.next) 18 | head.next.next = head 19 | head.next = None 20 | return reverse_head 21 | 22 | # iteratively reverse 23 | def reverseList_2(self, head): 24 | reverse_head = None 25 | while head: 26 | next_node = head.next 27 | head.next = reverse_head 28 | reverse_head = head 29 | head = next_node 30 | return reverse_head 31 | 32 | """ 33 | [] 34 | [1] 35 | [1,2] 36 | [1,2,3,4,5] 37 | """ 38 | -------------------------------------------------------------------------------- /LinkedList/234_PalindromeLinkedList.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.next = None 11 | 12 | class Solution(object): 13 | def isPalindrome(self, head): 14 | slow, fast, new_head = head, head, None 15 | # Reverse the first half while finding the middle. 16 | while fast and fast.next: 17 | fast = fast.next.next 18 | # Reverse the slow nodes, Pythonic way 19 | new_head, new_head.next, slow = slow, new_head, slow.next 20 | """ More general way 21 | next_node = slow.next 22 | slow.next = new_head 23 | new_head = slow 24 | slow = next_node 25 | """ 26 | # Midle node is slow or slow.next according to the len of list. 27 | if fast: 28 | slow = slow.next 29 | 30 | # Compare the reversed(pre_half) and post half 31 | while new_head and new_head.val == slow.val: 32 | new_head, slow = new_head.next, slow.next 33 | 34 | return not new_head 35 | 36 | """ 37 | [] 38 | [1] 39 | [1,2,2,1] 40 | [1,2,3,2,1] 41 | [1,2,3,4] 42 | """ 43 | -------------------------------------------------------------------------------- /LinkedList/237_DeleteNodeInLinkedList.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.next = None 11 | 12 | class Solution(object): 13 | def deleteNode(self, node): 14 | if not node: 15 | return None 16 | while node.next: 17 | node.val = node.next.val 18 | if node.next.next: 19 | node = node.next 20 | else: 21 | node.next = None 22 | break 23 | -------------------------------------------------------------------------------- /LinkedList/328_OddEvenLinkedList.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Definition for singly-linked list. 7 | # class ListNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.next = None 11 | 12 | class Solution(object): 13 | def oddEvenList(self, head): 14 | if not head or not head.next: 15 | return head 16 | 17 | odd = ListNode(0) 18 | even = ListNode(0) 19 | pre_head = odd 20 | pre_mid = even 21 | odd_even_dict = {0: even, 1: odd} 22 | count = 0 23 | while head: 24 | count += 1 25 | odd_even_dict[count & 1].next = head 26 | odd_even_dict[count & 1] = head 27 | head = head.next 28 | 29 | odd_even_dict[0].next = None 30 | odd_even_dict[1].next = pre_mid.next 31 | return pre_head.next 32 | 33 | """ 34 | [] 35 | [1] 36 | [1,2] 37 | [1,2,3] 38 | [1,2,3,4,5,6,7,8] 39 | """ 40 | -------------------------------------------------------------------------------- /LinkedList/83_RemoveDuplicatesFromSortedList.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-04-29 16:18:37 5 | 6 | 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | 14 | # Recursively 15 | class Solution_2(object): 16 | def deleteDuplicates(self, head): 17 | if not head or not head.next: 18 | return head 19 | head.next = self.deleteDuplicates(head.next) 20 | return head.next if head.val == head.next.val else head 21 | 22 | 23 | # Iteratively 24 | class Solution(object): 25 | def deleteDuplicates(self, head): 26 | cur = head 27 | while cur: 28 | # Skip all the duplicated nodes of cur. 29 | while cur.next and cur.val == cur.next.val: 30 | cur.next = cur.next.next 31 | # No duplicated nodes, move cur to next node 32 | cur = cur.next 33 | 34 | return head 35 | 36 | """ 37 | [] 38 | [1] 39 | [3,3,3,3,3] 40 | [1,1,1,2,3,4,4,4,4,5] 41 | """ 42 | -------------------------------------------------------------------------------- /LinkedList/README.md: -------------------------------------------------------------------------------- 1 | # 链表概述 2 | 3 | 我们知道用数组存放数据时,必须事先定义数组的长度(即元素个数)。当事先难以确定有多少个元素时,则必须把数组定义的足够大,以保证成功。无疑,这会造成内存浪费。因此可以考虑设计一种物理存储单元上非连续、非顺序的存储结构,来避免数组带来的问题,链表正是这样的一种数据结构。 4 | 5 | 链表由一系列`结点`(链表中每一个元素称为结点)组成,每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。 6 | 7 | 8 | 结点可以在运行时动态生成。 9 | 10 | 数据元素的逻辑顺序则是通过链表中的指针链接次序实现的。 11 | 12 | 13 | 使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。 14 | 15 | # 链表特点 16 | 17 | `头指针` 指链表中第一个结点(即第一个数据元素)的存储位置。 18 | 19 | 有时为了简化链表的操作,在链表的第一个结点之前附设一个结点,称之为头结点。头结点的数据域可以不存储任何信息,也可以存储如线性表长度等类的附加信息,头结点的指针域存储指向第一个结点的指针(即第一个元素结点的存储位置)。 20 | 21 | 22 | 最后一个数据元素没有直接后继,所以线性链表中最后一个结点的指针域为“空”(NULL)。 23 | 24 | 25 | # 链表操作 26 | 27 | ## 单链表排序 28 | 29 | 30 | 31 | # 题目 32 | 33 | ### 206 [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) 34 | 35 | > 定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头节点。 36 | 37 | 可以用递归或者迭代实现,关键在于要注意结点为 NULL 的情况。 38 | 39 | [具体代码](https://github.com/xuelangZF/LeetCode/blob/master/LinkedList/206_ReverseLinkedList.py) 40 | 41 | # 更多阅读 42 | 43 | [Wikipedia: Linked_list](https://en.wikipedia.org/wiki/Linked_list) 44 | 45 | 46 | -------------------------------------------------------------------------------- /Math/07_ReverseInteger.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def reverse(self, x): 7 | """ 8 | :type x: int 9 | :rtype: int 10 | """ 11 | negative = 1 12 | if x < 0: 13 | negative = -1 14 | x = x * -1 15 | 16 | result = 0 17 | while x / 10 != 0: 18 | result = (result + x % 10) * 10 19 | x = x / 10 20 | result += x % 10 21 | 22 | if abs(result) > 2 ** 31 - 1: 23 | return 0 24 | return result * negative 25 | -------------------------------------------------------------------------------- /Math/09_PalindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-05-04 22:03:09 4 | */ 5 | 6 | class Solution { 7 | public: 8 | bool isPalindrome(int x) { 9 | if(x<0|| (x!=0 &&x%10==0)) return false; 10 | int sum=0; 11 | while(x>sum) 12 | { 13 | sum = sum*10+x%10; 14 | x = x/10; 15 | } 16 | return (x==sum)||(x==sum/10); 17 | } 18 | }; 19 | 20 | /* 21 | 9 22 | 10 23 | -2147483648 24 | 32023 25 | 320023 26 | 98765432123456789 27 | */ 28 | -------------------------------------------------------------------------------- /Math/09_PalindromeNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def isPalindrome(self, x): 7 | if x < 0: 8 | return False 9 | reversed_x = 0 10 | original_x = x 11 | while x > 0: 12 | reversed_x = reversed_x * 10 + x % 10 13 | x /= 10 14 | return reversed_x == original_x 15 | 16 | 17 | # Pythonic way. 18 | class Solution_2(object): 19 | def isPalindrome(self, x): 20 | return x >= 0 and str(x) == str(x)[::-1] 21 | 22 | 23 | """ 24 | 9 25 | 10 26 | -2147483648 27 | 32023 28 | 320023 29 | 98765432123456789 30 | """ 31 | -------------------------------------------------------------------------------- /Math/13_RomantoInteger.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def romanToInt(self, s): 7 | """ 8 | :type s: str 9 | :rtype: int 10 | """ 11 | symbols_integer = {"I": 1, "V": 5, "X": 10, "L": 50, 12 | "C": 100, "D": 500, "M": 1000, 13 | "IV": 4, "IX": 9, "XL": 40, "XC": 90, 14 | "CD": 400, "CM": 900 15 | } 16 | length = len(s) 17 | integer = 0 18 | isPass = False 19 | for i in range(length): 20 | # Subtractive notation use this symbol 21 | if isPass: 22 | isPass = False 23 | continue 24 | # Just add the integer 25 | if s[i] in symbols_integer and s[i:i + 2] not in symbols_integer: 26 | integer = integer + symbols_integer[s[i]] 27 | isPass = False 28 | continue 29 | 30 | # Subtractive notation is used as follows. 31 | if s[i:i + 2] in symbols_integer: 32 | integer = integer + symbols_integer[s[i:i + 2]] 33 | isPass = True 34 | 35 | return integer 36 | 37 | """ 38 | "DCXXI" 39 | "CDCM" 40 | """ 41 | -------------------------------------------------------------------------------- /Math/168_ExcelSheetColumnTitle.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def convertToTitle(self, n): 7 | title = [] 8 | while n: 9 | if n % 26 == 0: 10 | title.insert(0, "Z") 11 | n -= 26 12 | else: 13 | title.insert(0, chr(n % 26 + 64)) 14 | n = n / 26 15 | 16 | return "".join(title) 17 | 18 | """ 19 | 0 20 | 1 21 | 52 22 | 130 23 | 99999999 24 | """ 25 | -------------------------------------------------------------------------------- /Math/171_ExcelSheetColumnNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def titleToNumber(self, s): 7 | base = 1 8 | s_list = list(s)[::-1] 9 | column = 0 10 | for char in s_list: 11 | column += (ord(char)-64) * base 12 | base *= 26 13 | 14 | return column 15 | 16 | """ 17 | "" 18 | "A" 19 | "ZZ" 20 | "AAACCCDDD" 21 | """ 22 | -------------------------------------------------------------------------------- /Math/172_FactorialTrailingZeroes.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def trailingZeroes(self, n): 7 | if n < 5: 8 | return 0 9 | 10 | sums = 0 11 | i = 1 12 | # Every five numbers will produce a trailing 0 13 | # when meet 25, 125, 625, ..., it will get addtional 0. 14 | while n / (5*i) >= 1: 15 | sums += n / (5*i) 16 | i *= 5 17 | return sums 18 | 19 | """ 20 | 0 21 | 5 22 | 7 23 | 10 24 | 25 25 | """ 26 | -------------------------------------------------------------------------------- /Math/179_LargestNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | def comp(a, b): 6 | return int(a + b > b + a) * 2 - 1 7 | 8 | 9 | class Solution(object): 10 | def largestNumber(self, nums): 11 | nums = map(str, nums) 12 | nums.sort(cmp=comp, reverse=True) 13 | return str(int("".join(nums))) 14 | 15 | """ 16 | [1] 17 | [1,2,3,21] 18 | [1,2,3,23] 19 | """ 20 | -------------------------------------------------------------------------------- /Math/202_HappyNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def isHappy(self, n): 7 | square_sum = 0 8 | sum_record = {} 9 | while n: 10 | square_sum += (n % 10) ** 2 11 | n = n / 10 12 | 13 | if not n: 14 | if square_sum == 1: 15 | return True 16 | if square_sum in sum_record: 17 | return False 18 | else: 19 | n = square_sum 20 | square_sum = 0 21 | sum_record[n] = 1 22 | 23 | """ 24 | 1 25 | 19 26 | 20 27 | """ 28 | -------------------------------------------------------------------------------- /Math/204_CountPrimes.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def countPrimes(self, n): 7 | if n <= 2: 8 | return 0 9 | count = 1 10 | # nums = [1 for i in range(n)] 11 | # Faster as follows 12 | nums = [1] * n 13 | 14 | for num in range(3, n, 2): 15 | if nums[num] == 1: 16 | count += 1 17 | k = num 18 | while num * k < n: 19 | nums[num*k] = 0 20 | k += 1 21 | else: 22 | pass 23 | return count 24 | 25 | # Pythonic way, beats 98% submissions. 26 | def countPrimes_2(self, n): 27 | if n <= 2: 28 | return 0 29 | nums = [True] * n 30 | nums[:2] = [False] * 2 31 | nums[2:n:2] = [False] * ((n-1)/2) 32 | for i in range(3, int(n ** 0.5) + 1, 2): 33 | if nums[i]: 34 | nums[i*i:n:i] = [False] * ((n-i*i-1)/i+1) 35 | 36 | return sum(nums)+1 37 | 38 | """ 39 | 0 40 | 120 41 | 9999 42 | """ 43 | -------------------------------------------------------------------------------- /Math/223_RectangleArea.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-12 09:17:10 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 9 | int left = max(A, E); 10 | int bottom = max(B, F); 11 | int right = min(C, G); 12 | int top = min(D, H); 13 | int size = (D-B) * (C-A) + (H-F) * (G-E); 14 | if(left < right && bottom < top){ 15 | size -= (top-bottom) * (right-left); 16 | } 17 | return size; 18 | } 19 | }; 20 | 21 | /* 22 | -2 23 | -2 24 | 2 25 | 2 26 | -2 27 | -2 28 | 2 29 | 2 30 | 0 31 | 0 32 | 0 33 | 0 34 | -1 35 | -1 36 | 1 37 | 1 38 | */ 39 | -------------------------------------------------------------------------------- /Math/223_RectangleArea.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def computeArea(self, A, B, C, D, E, F, G, H): 8 | size_1 = (C-A) * (D-B) 9 | size_2 = (G-E) * (H-F) 10 | left = max(A, E) 11 | bottom = max(B, F) 12 | right = min(C, G) 13 | top = min(D, H) 14 | 15 | # There is an area coverd by both the two rectangle 16 | if left < right and bottom < top: 17 | return size_1 + size_2 - (top-bottom) * (right-left) 18 | else: 19 | return size_1 + size_2 20 | 21 | """ 22 | -2 23 | -2 24 | 2 25 | 2 26 | -2 27 | -2 28 | 2 29 | 2 30 | 0 31 | 0 32 | 0 33 | 0 34 | -1 35 | -1 36 | 1 37 | 1 38 | """ 39 | -------------------------------------------------------------------------------- /Math/233_NumberOfDigitOne.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-28 13:58:30 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int countDigitOne(int n) 9 | { 10 | if(n<=0) return 0; 11 | long long count = 1; 12 | while(n){ 13 | if(n<10){ 14 | break; 15 | } 16 | int digit = n % 10; 17 | n /= 10; 18 | count += n; 19 | if(digit == 0) count -= 1; 20 | count += countDigitOne(n-1) * 10; 21 | 22 | // 最后一行中数组1出现的次数 23 | while(n){ 24 | if(n%10==1) count += digit+1; 25 | n /= 10; 26 | } 27 | } 28 | return count; 29 | } 30 | }; 31 | 32 | /* 33 | -1 34 | 6 35 | 12 36 | 234545 37 | */ 38 | -------------------------------------------------------------------------------- /Math/233_NumberOfDigitOne.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # Recursive solution 8 | def countDigitOne(self, n): 9 | if n <= 0: 10 | return 0 11 | elif n < 10: 12 | return 1 13 | else: 14 | units = n % 10 15 | tens = n / 10 16 | count = self.countDigitOne(tens - 1) * 10 + tens 17 | n /= 10 18 | while n: 19 | if n % 10 == 1: 20 | count = count + 1 + units 21 | n = n / 10 22 | 23 | if units >= 1: 24 | count += 1 25 | return count 26 | 27 | """ 28 | -1 29 | 6 30 | 12 31 | 234545 32 | """ 33 | -------------------------------------------------------------------------------- /Math/238_ProductOfArrayExceptSelf.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def productExceptSelf(self, nums): 8 | nums_len = len(nums) 9 | products = [1] * nums_len 10 | # Product of left part before the current position 11 | for i in range(1, nums_len): 12 | products[i] = products[i-1] * nums[i-1] 13 | 14 | # Mul the product of right part after the current position 15 | right_procudt = 1 16 | for j in range(nums_len-1, -1, -1): 17 | products[j] *= right_procudt 18 | right_procudt *= nums[j] 19 | 20 | return products 21 | 22 | """ 23 | [0,0] 24 | [1,2,3,4,5] 25 | [1,2,3,4,0] 26 | """ 27 | -------------------------------------------------------------------------------- /Math/258_AddDigits.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # According to Wiki: Digital root 8 | # https://en.wikipedia.org/wiki/Digital_root 9 | def addDigits(self, num): 10 | if not num: 11 | return 0 12 | return (1+(num-1) % 9) 13 | -------------------------------------------------------------------------------- /Math/263_UglyNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-15 22:23:06 4 | */ 5 | 6 | class Solution { 7 | public: 8 | bool isUgly(int num) { 9 | int prime[] = {2,3,5}; 10 | for(auto &n : prime){ 11 | while(num!=0 && num%n==0) num/=n; 12 | } 13 | return num==1; 14 | } 15 | }; 16 | 17 | /* 18 | -2147483648 19 | 1 20 | 0 21 | 14 22 | 8 23 | */ 24 | -------------------------------------------------------------------------------- /Math/263_UglyNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def isUgly(self, num): 8 | for p in [2, 3, 5]: 9 | while num and num % p == 0: 10 | num /= p 11 | return num == 1 12 | 13 | """ 14 | -2147483648 15 | 1 16 | 0 17 | 14 18 | 8 19 | """ 20 | -------------------------------------------------------------------------------- /Math/292_NimGame.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # Just get the conclusion from the following second way. 8 | def canWinNim(self, n): 9 | if n % 4: 10 | return True 11 | else: 12 | return False 13 | 14 | 15 | class Solution_2(object): 16 | # Easy to understand, need more memory. 17 | # Can be optimized by using static variable. 18 | def canWinNim(self, n): 19 | dp = [True] * (n+1) 20 | if n > 3: 21 | dp[4] = False 22 | for i in range(5, n+1): 23 | if dp[i-1] and dp[i-2] and dp[i-3]: 24 | dp[i] = False 25 | return dp[n] 26 | 27 | """ 28 | 1 29 | 8 30 | 12 31 | 245 32 | 12345 33 | """ 34 | -------------------------------------------------------------------------------- /Math/319_BulbSwitcher.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def bulbSwitch(self, n): 8 | """ 9 | A bulb ends up on iff it is switched an odd number of times. 10 | Call them bulb 1 to bulb n. 11 | Bulb i is switched in round d if and only if d divides i. 12 | So bulb i ends up on if and only if it has an odd number of divisors. 13 | """ 14 | return int(n ** 0.5) 15 | """ 16 | count = 0 17 | for i in xrange(1, n+1): 18 | if i * i < (n+1): 19 | count += 1 20 | else: 21 | break 22 | return count 23 | """ 24 | """ 25 | 0 26 | 1 27 | 2 28 | 3 29 | 4 30 | 12 31 | 1908 32 | """ 33 | -------------------------------------------------------------------------------- /Math/326_PowerOfThree.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def isPowerOfThree(self, n): 8 | # 3 ** 19 = 1162261467 9 | return n > 0 and not (1162261467 % n) 10 | 11 | """ 12 | -1 13 | 0 14 | 1 15 | 27 16 | 72 17 | """ 18 | -------------------------------------------------------------------------------- /Math/43_MultiplyStrings.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def multiply(self, num1, num2): 7 | """ Simulation the manual way we do multiplication. 8 | 9 | Start from right to left, perform multiplication on every pair of digits. 10 | And add them together. 11 | 12 | There is a good graph explanation. Refer to: 13 | https://discuss.leetcode.com/topic/30508/easiest-java-solution-with-graph-explanation 14 | """ 15 | m, n = len(num1), len(num2) 16 | pos = [0] * (m + n) 17 | for i in range(m - 1, -1, -1): 18 | for j in range(n - 1, -1, -1): 19 | multi = int(num1[i]) * int(num2[j]) 20 | pos_sum = pos[i + j + 1] + multi 21 | 22 | # Update pos[i+j], pos[i+j+1] 23 | pos[i + j] += pos_sum / 10 24 | pos[i + j + 1] = pos_sum % 10 25 | 26 | first_not_0 = 0 27 | while first_not_0 < m + n and pos[first_not_0] == 0: 28 | first_not_0 += 1 29 | 30 | return "".join(map(str, pos[first_not_0:] or [0])) 31 | 32 | """ 33 | "0" 34 | "1" 35 | "123" 36 | "123" 37 | "12121212121212125" 38 | "121232323499999252" 39 | """ 40 | -------------------------------------------------------------------------------- /Math/48_RotateImage.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-06-12 23:22:13 4 | */ 5 | 6 | class Solution { 7 | public: 8 | /* 9 | * Rotate the image by 90 degrees (clockwise). 10 | 11 | * After rotate, the element in A[i][j] moves to A[j][n-1-i]. So we can 12 | * Firstly reverse up to down : A[i][j] --> A[n-1-i][j] 13 | * Then then swap the symmetry: A[n-1-i][j] --> A[j][n-1-i] 14 | 15 | * 1 2 3 7 8 9 7 4 1 16 | * 4 5 6 => 4 5 6 => 8 5 2 17 | * 7 8 9 1 2 3 9 6 3 18 | */ 19 | void rotate(vector>& matrix) { 20 | reverse(matrix.begin(), matrix.end()); 21 | for(int i=0; i 0: 15 | result = self.myPow(x * x, abs_half) 16 | if n & 1 == 1: 17 | result *= x 18 | return result 19 | 20 | else: 21 | result = 1 / self.myPow(x * x, abs_half) 22 | if abs(n) & 1 == 1: 23 | result *= 1 / x 24 | return result 25 | 26 | """ 27 | 8.88023 28 | 3 29 | 2 30 | 1 31 | 2.2 32 | -100 33 | """ 34 | -------------------------------------------------------------------------------- /Math/60_PermutationSequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-06-28 15:13:27 4 | */ 5 | 6 | class Solution { 7 | public: 8 | string getPermutation(int n, int k) { 9 | vector factorial(n, 1); 10 | for(int i=1; i remain_array = {"1", "2", "3", 14 | "4", "5", "6", "7", "8", "9"}; 15 | string ans = ""; 16 | k -= 1; 17 | int pos = n; 18 | while(pos){ 19 | int cur_pos = k / factorial[pos-1]; 20 | string c = remain_array[cur_pos]; 21 | remain_array.erase(remain_array.begin() + cur_pos); 22 | ans += c; 23 | k %= factorial[pos-1]; 24 | pos -= 1; 25 | } 26 | return ans; 27 | } 28 | }; 29 | 30 | /* 31 | 9 32 | 23 33 | 9 34 | 24 35 | 9 36 | 25 37 | */ 38 | -------------------------------------------------------------------------------- /Math/66_PlusOne.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def plusOne(self, digits): 7 | """ 8 | :type digits: List[int] 9 | :rtype: List[int] 10 | """ 11 | if not digits: 12 | return [1] 13 | 14 | carry_in = (digits[-1] + 1)/10 15 | digits[-1] = (digits[-1] + 1) % 10 16 | 17 | index = len(digits) - 2 18 | # Every position is the sum of post position and carry_in mod 10 19 | while index >= 0: 20 | if digits[index] + carry_in == 10: 21 | digits[index] = 0 22 | carry_in = 1 23 | index -= 1 24 | else: 25 | digits[index] += carry_in 26 | carry_in = 0 27 | break 28 | 29 | # Add the pre carry in number. 30 | if carry_in and index == -1: 31 | digits.insert(0, 1) 32 | 33 | return digits 34 | 35 | """ 36 | [0] 37 | [1,2,3,4,5,6] 38 | [9,9,9,9,9,9] 39 | """ 40 | -------------------------------------------------------------------------------- /Math/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # 题目 5 | 6 | ### [223 Rectangle Area](https://leetcode.com/problems/rectangle-area/) 7 | 8 | > 计算平面坐标系中两个矩形覆盖的面积。注意两个矩形有可能相交,相交部分面积只能算一次,其中给出了每个矩形的左下角和右上角的坐标。 9 | 10 | 下图为矩形的可能情况: 11 | 12 | ![][1] 13 | 14 | 解决问题关键在于假设矩形相交,然后找出重合的小矩形的左下角坐标和右上角坐标,判断这两个坐标是否能够构成矩形。 15 | 16 | // 假设两个矩形相交,重合矩形的坐标如下 17 | int left = max(A, E); 18 | int bottom = max(B, F); 19 | int right = min(C, G); 20 | int top = min(D, H); 21 | 22 | 矩形相交的条件为 `left < right && bottom < top`。 23 | 24 | 25 | 26 | 27 | 28 | 29 | [1]: ../Images/223_rectangle_area.png 30 | 31 | -------------------------------------------------------------------------------- /Others/229_MajorityElementII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # According to: 5 | # https://leetcode.com/discuss/43248/boyer-moore-majority-vote-algorithm-and-my-elaboration 6 | 7 | 8 | class Solution(object): 9 | def majorityElement(self, nums): 10 | if not nums: 11 | return [] 12 | candidate_1, candidate_2 = 0, 1 13 | count_1, count_2 = 0, 0 14 | for num in nums: 15 | if num == candidate_1: 16 | count_1 += 1 17 | elif num == candidate_2: 18 | count_2 += 1 19 | elif not count_1: 20 | candidate_1, count_1 = num, 1 21 | elif not count_2: 22 | candidate_2, count_2 = num, 1 23 | else: 24 | count_1 -= 1 25 | count_2 -= 1 26 | result = [] 27 | for num in [candidate_1, candidate_2]: 28 | if nums.count(num) > len(nums) / 3: 29 | result.append(num) 30 | return result 31 | """ 32 | [] 33 | [0,0,0] 34 | [1,2,2,3,3,1,1,1] 35 | [2,2,2,3,3,4,3,2] 36 | [1,1,2] 37 | [3,0,3,4] 38 | """ 39 | -------------------------------------------------------------------------------- /Others/332_ReconstructItinerary.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def findItinerary(self, tickets): 8 | """ Eulerian path. Hierholzer Algorithm, greedy DFS with backtracking. 9 | 10 | Refer to: Short Ruby / Python / Java / C++ 11 | https://discuss.leetcode.com/topic/36370/short-ruby-python-java-c 12 | """ 13 | import collections 14 | targets = collections.defaultdict(list) 15 | for a, b in sorted(tickets, reverse=True): 16 | targets[a] += b, 17 | route = [] 18 | 19 | def visit(airport): 20 | while targets[airport]: 21 | visit(targets[airport].pop()) 22 | route.append(airport) 23 | visit('JFK') 24 | 25 | return route[::-1] 26 | 27 | """ 28 | [["JFK", "MUC"], ["JFK", "SJC"], ["SJC", "JFK"], ["MUC", "ATL"]] 29 | [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] 30 | [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] 31 | [["JFK", "MUC"], ["MUC", "SJC"], ["SJC", "ATL"], ["MUC", "LHR"], ["LHR", "SJC"]] 32 | """ 33 | -------------------------------------------------------------------------------- /Others/More.md: -------------------------------------------------------------------------------- 1 | # Binary Indexed Trees 2 | 3 | 4 | 相关题目: [s307. Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) 5 | 6 | 参考: 7 | [夜深人静写算法(三) - 树状数组](http://www.cppblog.com/menjitianya/archive/2015/11/02/212171.html) 8 | 9 | 10 | -------------------------------------------------------------------------------- /Recursion/101_SymmetricTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-29 13:51:57 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | bool isSymmetric(TreeNode* root) { 18 | return helper(root, root); 19 | } 20 | 21 | bool helper(TreeNode* lNode, TreeNode* rNode){ 22 | if(lNode == NULL || rNode == NULL){ 23 | return lNode == rNode; 24 | } 25 | if(lNode->val != rNode->val){ 26 | return false; 27 | } 28 | return helper(lNode->left, rNode->right) && helper(lNode->right, rNode->left); 29 | } 30 | }; 31 | 32 | /* 33 | [] 34 | [1] 35 | [1,2,3] 36 | [1,2,2,3,4,4,3] 37 | [1,2,2,null,3,null,3] 38 | */ 39 | -------------------------------------------------------------------------------- /Recursion/101_SymmetricTree.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def isSymmetric(self, root): 14 | return self.helper(root, root) 15 | 16 | # If two nodes are symmetric 17 | def helper(self, lNode, rNode): 18 | if not lNode or not rNode: 19 | return lNode == rNode 20 | if lNode.val != rNode.val: 21 | return False 22 | return (self.helper(lNode.left, rNode.right) and 23 | self.helper(lNode.right, rNode.left)) 24 | 25 | """ 26 | [] 27 | [1] 28 | [1,2,3] 29 | [1,2,2,3,4,4,3] 30 | [1,2,2,null,3,null,3] 31 | """ 32 | -------------------------------------------------------------------------------- /Recursion/77_Combinations.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def combine(self, n, k): 7 | """ 8 | :type n: int 9 | :type k: int 10 | :rtype: List[List[int]] 11 | """ 12 | if k > n or not n: 13 | return [] 14 | 15 | combine_list = self.combine_k(1, n, k) 16 | return combine_list 17 | 18 | def combine_k(self, start, n, k): 19 | combine_k = [] 20 | # k == 1, just return the list[start, end] 21 | if k == 1: 22 | for i in range(start, n+1): 23 | combine_k.append([i]) 24 | return combine_k 25 | 26 | # k > 1, return every i combines all the k-1 th combine in [i+1, n] 27 | for i in range(start, n+2-k): 28 | combine_k_1 = self.combine_k(i+1, n, k-1) 29 | for combine_1 in combine_k_1: 30 | combine = [i] 31 | combine.extend(combine_1) 32 | combine_k.append(combine) 33 | 34 | return combine_k 35 | 36 | """ 37 | 5 38 | 2 39 | 2 40 | 3 41 | 6 42 | 6 43 | """ 44 | -------------------------------------------------------------------------------- /Recursion/89_GrayCode.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def grayCode(self, n): 7 | """ 8 | :type n: int 9 | :rtype: List[int] 10 | """ 11 | if not n: 12 | return [0] 13 | 14 | if n == 1: 15 | return [0, 1] 16 | 17 | # Consume n's sequence is: 0..0, 0..1, ..., 1..0 18 | # When comes to n+1, it's sequence is simple as followers: 19 | # 0{0..0, 0..1, ..., 1..0}, 1{1..0, ..., 0..1, 0..0} 20 | # Then second part of past line is just a reverse of n's sequence. 21 | high_digit = 2 ** (n-1) 22 | gray_code_list = self.grayCode(n-1) 23 | for num in gray_code_list[::-1]: 24 | gray_code_list.append(high_digit + num) 25 | 26 | return gray_code_list 27 | 28 | """ 29 | 0 30 | 2 31 | 3 32 | 4 33 | """ 34 | -------------------------------------------------------------------------------- /Recursion/README.md: -------------------------------------------------------------------------------- 1 | > To Iterate is Human, to Recurse, Divine. 2 | 3 | 人理解迭代,神理解递归。下面我们来体验一下做神的感觉! 4 | 5 | # 递归的思想 6 | 7 | 一般来讲,能用递归来解决的问题必须满足两个条件: 8 | 9 | 1. 可以通过递归调用来缩小问题规模,且新问题与原问题有着相同的形式。 10 | 2. 存在一种简单情境,可以使递归在简单情境下退出。 11 | 12 | 可以这样理解,递归就是有去(递去)有回(归来)。 13 | 14 | # 递归思考诀窍 15 | 16 | 分析递归问题的关键点: 17 | 18 | 1. 设计递归体的目标,即递归到底求的是什么。 19 | 2. 划分问题,对子问题调用递归函数求出结果,然后利用这个结果求原问题的解(即如何利用递归的结果) 20 | 3. 考虑清楚递归退出的边界条件。(即何时退出递归过程) 21 | 22 | 23 | 参考 24 | [人脑理解递归](http://zisong.me/post/suan-fa/ren-nao-li-jie-di-gui) 25 | [漫谈递归:递归的思想](http://www.nowamagic.net/librarys/veda/detail/2314) 26 | 27 | 28 | -------------------------------------------------------------------------------- /Stack/150_EvaluateReversePolishNotation.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def evalRPN(self, tokens): 7 | value_stack = [] 8 | for token in tokens: 9 | if token in "+-*/": 10 | operand_2 = value_stack.pop() 11 | operand_1 = value_stack.pop() 12 | negative = 1 13 | if operand_1 * operand_2 < 0: 14 | negative = -1 15 | 16 | if token == "+": 17 | result = operand_1 + operand_2 18 | elif token == "-": 19 | result = operand_1 - operand_2 20 | elif token == "*": 21 | result = operand_1 * operand_2 22 | else: 23 | # Leetcode think 12/-7 = -1, 12/-13 = 0 24 | result = abs(operand_1) / abs(operand_2) * negative 25 | 26 | value_stack.append(result) 27 | else: 28 | value_stack.append(int(token)) 29 | return value_stack[-1] 30 | 31 | """ 32 | ["18"] 33 | ["12", "-7", "/"] 34 | ["2", "1", "+", "3", "*"] 35 | ["4", "13", "5", "/", "+"] 36 | """ 37 | -------------------------------------------------------------------------------- /Stack/155_MinStack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-15 16:10:01 4 | */ 5 | 6 | 7 | class MinStack { 8 | public: 9 | void push(int x) { 10 | data.push(x); 11 | if(min_n.empty() || x <= getMin()){ 12 | min_n.push(x); 13 | } 14 | } 15 | 16 | void pop() { 17 | if(top() == getMin()){ 18 | min_n.pop(); 19 | } 20 | data.pop(); 21 | } 22 | 23 | int top() { 24 | return data.top(); 25 | } 26 | 27 | int getMin() { 28 | return min_n.top(); 29 | } 30 | private: 31 | stack data; 32 | stack min_n; 33 | }; 34 | -------------------------------------------------------------------------------- /Stack/155_MinStack.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class MinStack(object): 6 | # According to: 7 | # https://leetcode.com/discuss/45373/c-using-two-stacks-quite-short-and-easy-to-understand 8 | def __init__(self): 9 | self.stack_d = [] 10 | self.stack_m = [] 11 | 12 | def push(self, x): 13 | self.stack_d.append(x) 14 | if not self.stack_m or x <= self.getMin(): 15 | self.stack_m.append(x) 16 | 17 | def pop(self): 18 | if self.top() == self.getMin(): 19 | self.stack_m.pop() 20 | self.stack_d.pop() 21 | 22 | def top(self): 23 | return self.stack_d[-1] 24 | 25 | def getMin(self): 26 | return self.stack_m[-1] 27 | 28 | ''' 29 | if __name__ == '__main__': 30 | one_stack = MinStack() 31 | one_stack.push(3) 32 | one_stack.push(4) 33 | one_stack.push(2) 34 | one_stack.push(1) 35 | 36 | print one_stack.getMin() 37 | one_stack.pop() 38 | print one_stack.getMin() 39 | one_stack.pop() 40 | print one_stack.getMin() 41 | one_stack.push(0) 42 | print one_stack.getMin() 43 | ''' 44 | -------------------------------------------------------------------------------- /Stack/20_ValidParentheses.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def isValid(self, s): 7 | """ 8 | :type s: str 9 | :rtype: bool 10 | """ 11 | parenthes_stack = [] 12 | match_rule = {")": "(", "]": "[", "}": "{"} 13 | for symble in s: 14 | if symble == "(" or symble == "[" or symble == "{": 15 | parenthes_stack.append(symble) 16 | 17 | else: 18 | # Check if stack top matches the current ), ] or }. 19 | if (parenthes_stack and 20 | parenthes_stack[-1] == match_rule[symble]): 21 | parenthes_stack.pop() 22 | else: 23 | return False 24 | # Have some symbles that is not matched. 25 | if parenthes_stack: 26 | return False 27 | 28 | return True 29 | 30 | """ 31 | "" 32 | "[" 33 | "()()()()[]" 34 | "()((()){})" 35 | """ 36 | -------------------------------------------------------------------------------- /Stack/225_ImplementStackusingQueues.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-24 13:24:37 4 | */ 5 | 6 | class Stack { 7 | public: 8 | // Push element x onto stack. 9 | // then rotating the queue until the new element is at the front 10 | void push(int x) { 11 | q.push(x); 12 | for(int i=0;i q{}; 34 | }; 35 | -------------------------------------------------------------------------------- /Stack/225_ImplementStackusingQueues.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | from collections import deque 5 | 6 | 7 | class Stack(object): 8 | def __init__(self): 9 | self._queue = deque() 10 | 11 | def push(self, x): 12 | # Pushing to back and 13 | # then rotating the queue until the new element is at the front 14 | q = self._queue 15 | q.append(x) 16 | for i in xrange(len(q) - 1): 17 | q.append(q.popleft()) 18 | 19 | def pop(self): 20 | self._queue.popleft() 21 | 22 | def top(self): 23 | return self._queue[0] 24 | 25 | def empty(self): 26 | return not len(self._queue) 27 | 28 | """Test 29 | if __name__ == '__main__': 30 | s = Stack() 31 | s.push(1) 32 | s.push(2) 33 | print s.top() 34 | s.pop() 35 | print s.empty() 36 | print s.top() 37 | s.pop() 38 | print s.empty() 39 | """ 40 | -------------------------------------------------------------------------------- /Stack/232_ImplementQueueUsingStacks.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-24 12:16:45 4 | */ 5 | 6 | class Queue { 7 | public: 8 | // Push element x to the back of queue. 9 | void push(int x) { 10 | in_stack.push(x); 11 | } 12 | 13 | // Removes the element from in front of queue. 14 | void pop(void) { 15 | move(); 16 | out_stack.pop(); 17 | } 18 | 19 | // Get the front element. 20 | int peek(void) { 21 | move(); 22 | return out_stack.top(); 23 | } 24 | 25 | // Return whether the queue is empty. 26 | bool empty(void) { 27 | return in_stack.empty() && out_stack.empty(); 28 | } 29 | 30 | private: 31 | void move(){ 32 | if(out_stack.empty()){ 33 | while(!in_stack.empty()){ 34 | out_stack.push(in_stack.top()); 35 | in_stack.pop(); 36 | } 37 | } 38 | } 39 | stack in_stack; 40 | stack out_stack; 41 | }; 42 | -------------------------------------------------------------------------------- /Stack/232_ImplementQueueUsingStacks.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Queue(object): 7 | """ 8 | Use python list as the underlying data structure for stack. 9 | Add a "move()" method to simplify code: it moves all elements 10 | of the "inStack" to the "outStack" when the "outStack" is empty. 11 | """ 12 | def __init__(self): 13 | self.in_stack, self.out_stack = [], [] 14 | 15 | def push(self, x): 16 | self.in_stack.append(x) 17 | 18 | def pop(self): 19 | self.move() 20 | self.out_stack.pop() 21 | 22 | def peek(self): 23 | self.move() 24 | return self.out_stack[-1] 25 | 26 | def empty(self): 27 | return (not self.in_stack) and (not self.out_stack) 28 | 29 | def move(self): 30 | if not self.out_stack: 31 | while self.in_stack: 32 | self.out_stack.append(self.in_stack.pop()) 33 | 34 | ''' 35 | if __name__ == '__main__': 36 | q = Queue() 37 | q.push(2) 38 | q.push(3) 39 | q.push(4) 40 | print q.peek() 41 | q.pop() 42 | print q.peek() 43 | q.pop() 44 | q.pop() 45 | print q.empty() 46 | ''' 47 | -------------------------------------------------------------------------------- /Stack/32_LongestValidParentheses.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def longestValidParentheses(self, s): 7 | """ 8 | According to: 9 | https://leetcode.com/discuss/7609/my-o-n-solution-using-a-stack 10 | 11 | If current character is '(', push its index to the stack. 12 | If current character is ')': 13 | 1. top of stack is '(', just find a matching pair so pop from the stack. 14 | 2. Otherwise, we push the index of ')' to the stack. 15 | 16 | Finally the stack will only contain the indices of characters which cannot be matched. 17 | Then the substring between adjacent indices should be valid parentheses. 18 | """ 19 | stack, longest = [0], 0 20 | for i in xrange(1, len(s)): 21 | if s[i] == '(': 22 | stack.append(i) 23 | else: 24 | if stack and s[stack[-1]] == '(': 25 | stack.pop() 26 | valid_len = (i - stack[-1]) if stack else i + 1 27 | longest = max(longest, valid_len) 28 | else: 29 | stack.append(i) 30 | return longest 31 | 32 | """ 33 | "" 34 | ")" 35 | "()" 36 | "))" 37 | "(((()()()))(" 38 | "(((()()()))())" 39 | """ 40 | -------------------------------------------------------------------------------- /Stack/94_BinaryTreeInorderTraversal.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | 12 | class Solution(object): 13 | def inorderTraversal(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: List[int] 17 | """ 18 | if not root: 19 | return [] 20 | 21 | tree_stack = [] 22 | inorder_tra = [] 23 | while root or tree_stack: 24 | # Go along the left child 25 | if root: 26 | tree_stack.append(root) 27 | root = root.left 28 | # Meet a left, go back to the parent node 29 | else: 30 | if not tree_stack: 31 | root = None 32 | continue 33 | node = tree_stack.pop() 34 | inorder_tra.append(node.val) 35 | root = node.right 36 | 37 | return inorder_tra 38 | 39 | """ 40 | [] 41 | [1] 42 | [1,2,3,null,null,4,null,null,5] 43 | """ 44 | -------------------------------------------------------------------------------- /Stack/README.md: -------------------------------------------------------------------------------- 1 | 栈是一种最基本、最常用的数据结构,一个词来总结栈的特点就是`后进先出`。我们可以将栈看作是一个数据仓库,向栈内增加数据的操作叫入栈(push)操作,从栈内取出数据的操作叫出栈(pop)操作。不过不像一般的仓库一样,可以随意取出任何位置的物品,从一个栈取出的数据必须是最后一次增加的数据。换句话就是说,最后一个进入栈的数据,会被第一个取出来。 2 | 3 | 一个简单的入栈、出栈过程如下图: 4 | 5 | ![][1] 6 | 7 | 生活中有很多场景包含有后进先出的思想,比如刷盘子这个过程,我们将已经洗好的盘子叠在一起,每次洗好一个盘子就将堆在顶部,而我们需要用一个盘子时也是从最上面取走。 8 | 9 | # 栈的起源 10 | 11 | 那么计算机学科中,是怎么出现栈这个数据结构呢。 12 | 13 | # 栈的实现 14 | 15 | 16 | # 典型应用场景 17 | 18 | 1. 函数调用 19 | 20 | 2. 表达式计算 21 | 22 | 3. 表达式转换 23 | 24 | * 中缀转前缀 25 | * 中缀转后缀 26 | * 前缀转中缀 27 | * 后缀转中缀 28 | 29 | 4. 模拟递归 30 | 31 | # 题目 32 | 33 | ### [155. Min Stack](https://leetcode.com/problems/min-stack/) 34 | 35 | > 设计一个栈数据结构,支持 push, pop, top, getMin 操作,且时间复杂度均为 O(1)。 36 | 37 | 用一个栈来实现正常的站操作,同时用一个`辅助栈`来保存每次的最小元素。push 数据时,如果当前数据小于等于最小元素,则同时push到数据栈和辅助栈,保证辅助栈顶部是最小元素。pop 时,如果数据栈顶部等于辅助栈顶,则同时pop,否则只用 pop 数据栈。 38 | 39 | 当然,用一个栈也是可以的,栈里面内容为当前数据和当前最小值之间的距离,具体可以参考 40 | [Share my Java solution with ONLY ONE stack](https://leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack)。 41 | 42 | [具体实现](https://github.com/xuelangZF/LeetCode/blob/master/Stack/155_MinStack.py) 43 | 44 | 45 | [1]: ../Images/stack_demo.png 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /String/05_LongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-04 21:41:17 4 | */ 5 | 6 | class Solution { 7 | public: 8 | string longestPalindrome(string s) { 9 | if(s=="") return ""; 10 | else if(s.size() == 1) return s; 11 | int s_len = s.size(); 12 | int max_begin=0, max_end=0; 13 | int pos = 0; 14 | while(pos < s_len){ 15 | // No need to check the remainming, pruning here 16 | if(max_end-max_begin >= (s_len-pos) * 2 - 1){ 17 | break; 18 | } 19 | int left = pos, right = pos+1; 20 | while(right < s_len && s[right] == s[right-1]){ 21 | right ++; 22 | } 23 | pos = right; 24 | while(left-1>=0 && right max_end - max_begin){ 29 | max_begin = left; 30 | max_end = right; 31 | } 32 | } 33 | return s.substr(max_begin, max_end-max_begin); 34 | } 35 | }; 36 | 37 | /* 38 | "" 39 | "a" 40 | "aa" 41 | "dcc" 42 | "aaaa" 43 | "cccd" 44 | "ccccdc" 45 | "abcdefead" 46 | */ 47 | -------------------------------------------------------------------------------- /String/06_ZigZagConversion.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convert(self, s, numRows): 3 | """ 4 | :type s: str 5 | :type numRows: int 6 | :rtype: str 7 | """ 8 | if not s: 9 | return "" 10 | if numRows == 1: 11 | return s 12 | 13 | len_s = len(s) 14 | zigzag_list = [] 15 | magic_number = 2 * numRows - 2 16 | 17 | for row in range(numRows): 18 | index = row 19 | while index < len_s: 20 | zigzag_list.append(s[index]) 21 | if row != 0 and row != numRows - 1: 22 | next_num = magic_number + index - 2 * row 23 | if next_num < len_s: 24 | zigzag_list.append(s[next_num]) 25 | index += magic_number 26 | 27 | return "".join(zigzag_list) 28 | 29 | """ 30 | "" 31 | 1 32 | "ABC" 33 | 1 34 | "PAYPALISHIRING" 35 | 5 36 | """ 37 | -------------------------------------------------------------------------------- /String/08_StringtoInteger.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-08-21 09:10:58 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int myAtoi(string str){ 9 | /* 10 | We need to handle four cases: 11 | 12 | 1. discards all leading whitespaces 13 | 2. sign of the number 14 | 3. overflow 15 | 4. invalid input 16 | */ 17 | const int len = str.size(); 18 | 19 | int i=0; 20 | // Skip starting whitespace as many as possible. 21 | while (str[i]==' ' && i '9'){ 34 | break; 35 | } 36 | if(num > INT_MAX/10 || (num == INT_MAX / 10 && (str[i]-'0') > INT_MAX % 10)){ 37 | return sign == -1 ? INT_MIN : INT_MAX; 38 | } 39 | num = num * 10 + str[i] - '0'; 40 | } 41 | 42 | return num * sign; 43 | } 44 | }; 45 | 46 | /* 47 | "" 48 | " 12a" 49 | " a12" 50 | " +12" 51 | " +-12" 52 | "2147483648" 53 | "-2147483648" 54 | */ 55 | -------------------------------------------------------------------------------- /String/08_StringtoInteger.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | MAX_INT = 2**31 - 1 7 | MIN_INT = - 2**31 8 | 9 | def myAtoi(self, strs): 10 | """ We need to handle four cases: 11 | 12 | 1. discards all leading whitespaces 13 | 2. sign of the number 14 | 3. overflow 15 | 4. invalid input 16 | """ 17 | strs = strs.strip() 18 | if not strs: 19 | return 0 20 | 21 | sign, i = 1, 0 22 | if strs[i] == '+': 23 | i += 1 24 | elif strs[i] == '-': 25 | i += 1 26 | sign = -1 27 | 28 | num = 0 29 | while i < len(strs): 30 | if strs[i] < '0' or strs[i] > '9': 31 | break 32 | if num > self.MAX_INT or (num * 10 + int(strs[i]) > self.MAX_INT): 33 | return self.MAX_INT if sign == 1 else self.MIN_INT 34 | else: 35 | num = num * 10 + int(strs[i]) 36 | i += 1 37 | 38 | return num * sign 39 | 40 | """ 41 | "" 42 | " 12a" 43 | " a12" 44 | " +12" 45 | " +-12" 46 | "2147483648" 47 | "-2147483648" 48 | """ 49 | -------------------------------------------------------------------------------- /String/14_LongestCommonPrefix.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def longestCommonPrefix(self, strs): 7 | """ 8 | :type strs: List[str] 9 | :rtype: str 10 | """ 11 | if not strs: 12 | return "" 13 | common_prefix = strs[0] 14 | for string in strs: 15 | min_len = min(len(string), len(common_prefix)) 16 | mark = 0 # Record the longest commen prefix index right now. 17 | for i in range(min_len): 18 | mark = i 19 | if string[i] == common_prefix[i]: 20 | i += 1 21 | mark = i 22 | else: 23 | if i == 0: 24 | return "" 25 | break 26 | common_prefix = common_prefix[:mark] 27 | 28 | return common_prefix 29 | 30 | """ 31 | [] 32 | ["abcd", "abc", "ab","acdef"] 33 | ["abc", "abcd", "d"] 34 | """ 35 | -------------------------------------------------------------------------------- /String/151_ReverseWordsInString.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def reverseWords(self, s): 7 | return " ".join(s.split()[::-1]) 8 | 9 | """ 10 | if __name__ == "__main__": 11 | sol = Solution() 12 | print sol.reverseWords("AAA BBB ") 13 | print sol.reverseWords(" BBB CC ") 14 | """ 15 | -------------------------------------------------------------------------------- /String/165_CompareVersionNumbers.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def compareVersion(self, version1, version2): 7 | ver_list_1 = version1.split(".") 8 | ver_list_2 = version2.split(".") 9 | 10 | len_1 = len(ver_list_1) 11 | len_2 = len(ver_list_2) 12 | for i in range(len_1): 13 | ver_list_1[i] = int(ver_list_1[i]) 14 | for i in range(len_2): 15 | ver_list_2[i] = int(ver_list_2[i]) 16 | 17 | len_max = max(len_1, len_2) 18 | for i in range(len_1, len_max): 19 | ver_list_1.append(0) 20 | for i in range(len_2, len_max): 21 | ver_list_2.append(0) 22 | 23 | for i in range(len_max): 24 | if ver_list_1[i] < ver_list_2[i]: 25 | return -1 26 | elif ver_list_1[i] > ver_list_2[i]: 27 | return 1 28 | else: 29 | pass 30 | return 0 31 | 32 | """ 33 | "01" 34 | "1" 35 | "1.0" 36 | "1" 37 | "1.2.3.4" 38 | "1.2.3.4.5" 39 | "1.12.13" 40 | "1.13" 41 | """ 42 | -------------------------------------------------------------------------------- /String/28_ImplementstrStr.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-06 21:22:30 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int strStr(string haystack, string needle) { 9 | if(needle=="") return 0; 10 | int str_len = haystack.size(); 11 | int pat_len = needle.size(); 12 | for(int i=0;i= 0 && s[tail] == ' ') tail--; 12 | while (tail >= 0 && s[tail] != ' ') { 13 | len++; 14 | tail--; 15 | } 16 | return len; 17 | } 18 | }; 19 | 20 | /* 21 | "" 22 | "are" 23 | "we are teams" 24 | "we are teams " 25 | */ 26 | -------------------------------------------------------------------------------- /String/58_LengthOfLastWord.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def lengthOfLastWord(self, s): 7 | s = s.strip() 8 | length = 0 9 | while length < len(s) and s[-(length + 1)] != " ": 10 | length += 1 11 | 12 | return length 13 | 14 | 15 | class Solution_2(object): 16 | def lengthOfLastWord(self, s): 17 | return len(s.strip().split(' ')[-1]) 18 | 19 | """ 20 | "" 21 | "are" 22 | "we are teams" 23 | "we are teams " 24 | """ 25 | -------------------------------------------------------------------------------- /String/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/selfboot/LeetCode/473c0c5451651140d75cbd143309c51cd8fe1cf1/String/README.md -------------------------------------------------------------------------------- /ToBeOptimized/125_ValidPalindrome.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def isPalindrome(self, s): 7 | """ 8 | :type s: str 9 | :rtype: bool 10 | """ 11 | alpha_num_str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 12 | s = s.upper() 13 | s_l = len(s) 14 | pre = 0 15 | post = s_l - 1 16 | while pre < post and pre < s_l and post >= 0: 17 | # Remember the situation ",,..". 18 | # Make sure pre and post don't 19 | while pre < s_l and s[pre] not in alpha_num_str: 20 | pre += 1 21 | while post >= 0 and s[post] not in alpha_num_str: 22 | post -= 1 23 | if pre >= post: 24 | break 25 | if s[pre] != s[post]: 26 | return False 27 | pre += 1 28 | post -= 1 29 | 30 | return True 31 | 32 | """ 33 | "" 34 | "1a2" 35 | ",,,,...." 36 | "A man, a plan, a canal: Panama" 37 | "race a car" 38 | """ 39 | -------------------------------------------------------------------------------- /ToBeOptimized/18_4Sum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def fourSum(self, nums, target): 7 | """ 8 | :type nums: List[int] 9 | :type target: int 10 | :rtype: List[List[int]] 11 | """ 12 | nums.sort() 13 | length = len(nums) 14 | 15 | # Get all the two sums and their two addend's index. 16 | two_sums_dict = {} 17 | for i in range(length): 18 | for j in range(i+1, length): 19 | two_sums = nums[i] + nums[j] 20 | if two_sums not in two_sums_dict: 21 | two_sums_dict[two_sums] = [] 22 | two_sums_dict[two_sums].append([i, j]) 23 | 24 | sums_list = two_sums_dict.keys 25 | sums_list.sort() 26 | solution = [] 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | """ 35 | [] 36 | 0 37 | [1, 0, -1, 0, -2, 2] 38 | 0 39 | [1,1,1,1,0,0,0,0,-1,-1,-1,-1] 40 | 0 41 | """ 42 | -------------------------------------------------------------------------------- /ToBeOptimized/279_PerfectSquares.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Dynamic Programming with static variable 7 | class Solution(object): 8 | # Since dp is a static vector, we have already calculated the result 9 | # during previous function calls and we can just return the result now. 10 | _dp = [0] 11 | 12 | def numSquares(self, n): 13 | dp = self._dp 14 | while len(dp) <= n: 15 | i = len(dp) 16 | min_count = 2 ** 31 - 1 17 | for j in range(1, int(i**0.5) + 1): 18 | min_count = min(min_count, dp[i-j*j]+1) 19 | dp.append(min_count) 20 | return dp[n] 21 | 22 | 23 | # Dynamic Programming 24 | # Easy to undersrtand but unfortually "Time Limit Exceeded" 25 | class Solution_2(object): 26 | def numSquares(self, n): 27 | dp = [0] * (n+1) 28 | for i in range(1, n+1): 29 | min_count = 2 ** 31 - 1 30 | for j in range(1, int(i**0.5) + 1): 31 | min_count = min(min_count, dp[i-j*j]+1) 32 | dp[i] = min_count 33 | return dp[n] 34 | 35 | """ 36 | 1 37 | 12 38 | 13 39 | 156 40 | """ 41 | -------------------------------------------------------------------------------- /ToBeOptimized/324_WiggleSortII.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def wiggleSort(self, nums): 8 | """ 9 | Clear solutionm, explanation and proof can be found here: 10 | https://leetcode.com/discuss/76965/3-lines-python-with-explanation-proof 11 | """ 12 | nums.sort() 13 | half = (len(nums[::2])) - 1 14 | # Consider [4,5,5,6] 15 | # half = (len(nums)+1) // 2 16 | # nums[::2], nums[1::2] = nums[:half], nums[half:] 17 | nums[::2], nums[1::2] = nums[half::-1], nums[:half:-1] 18 | 19 | 20 | class Solution_2(object): 21 | def wiggleSort(self, nums): 22 | """ 23 | O(n)-time O(1)-space solution, no sort here. 24 | According to: 25 | https://leetcode.com/discuss/77133/o-n-o-1-after-median-virtual-indexing 26 | """ 27 | 28 | 29 | """ 30 | [4, 5, 5, 6] 31 | [1, 5, 1, 1, 6, 4] 32 | [1, 3, 2, 2, 3, 1] 33 | """ 34 | -------------------------------------------------------------------------------- /Tree/100_SameTree.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def isSameTree(self, p, q): 14 | """ 15 | :type p: TreeNode 16 | :type q: TreeNode 17 | :rtype: bool 18 | """ 19 | if not p and not q: 20 | return True 21 | if (not p and q) or (p and not q): 22 | return False 23 | 24 | if p.val != q.val: 25 | return False 26 | if not self.isSameTree(p.left, q.left): 27 | return False 28 | if not self.isSameTree(p.right, q.right): 29 | return False 30 | 31 | return True 32 | 33 | """ 34 | [] 35 | [1] 36 | [1,2,3] 37 | [1,2,3] 38 | [2,null,3,4,5] 39 | [2,null,3,5,4] 40 | """ 41 | -------------------------------------------------------------------------------- /Tree/110_BalancedBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuelangZF 3 | * @Date: 2016-03-06 17:16:31 4 | * @Last Modified by: xuelangZF 5 | * @Last Modified time: 2016-03-06 17:16:31 6 | */ 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | bool isBalancedSolution(TreeNode* root, int &height){ 20 | if(!root){ 21 | return true; 22 | } 23 | int left = 0; 24 | int right = 0; 25 | if (isBalancedSolution(root->left, left) && isBalancedSolution(root->right, right)){ 26 | int diff = left - right; 27 | if (diff < -1 or diff > 1){ 28 | return false; 29 | } 30 | height = (left > right ? left: right) + 1; 31 | return true; 32 | } 33 | return false; 34 | } 35 | bool isBalanced(TreeNode* pRoot) { 36 | int height = 0; 37 | return isBalancedSolution(pRoot, height); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Tree/111_MinimumDepthofBinaryTree.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def minDepth(self, root): 14 | """ 15 | :type root: TreeNode 16 | :rtype: int 17 | """ 18 | if not root: 19 | return 0 20 | 21 | if root.left and root.right: 22 | return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) 23 | if not root.left: 24 | return 1 + self.minDepth(root.right) 25 | if not root.right: 26 | return 1 + self.minDepth(root.left) 27 | else: 28 | return 1 29 | 30 | """ 31 | [] 32 | [1] 33 | [1,2,null,3] 34 | [1,2,3,4,null,6,7,5,8] 35 | [1,2,2,3,null,null,3,4,null,null,4] 36 | """ 37 | -------------------------------------------------------------------------------- /Tree/112_PathSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-19 09:57:21 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | bool hasPathSum(TreeNode* root, int sum) { 18 | if(root == NULL){ 19 | return false; 20 | } 21 | if(root->left==NULL && root->right == NULL){ 22 | return root->val == sum; 23 | } 24 | if(root->left && hasPathSum(root->left, sum-root->val)){ 25 | return true; 26 | } 27 | if(root->right && hasPathSum(root->right, sum-root->val)){ 28 | return true; 29 | } 30 | } 31 | }; 32 | 33 | /* 34 | [] 35 | 0 36 | [1,2,3,4,null,6,7,5,8] 37 | 15 38 | [1,2,2,3,null,null,3,4,null,null,4] 39 | 9 40 | */ 41 | -------------------------------------------------------------------------------- /Tree/112_PathSum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | def hasPathSum(self, root, sum): 14 | if not root: 15 | return False 16 | 17 | root_val = root.val 18 | if root.left and self.hasPathSum(root.left, sum-root_val): 19 | return True 20 | if root.right and self.hasPathSum(root.right, sum-root_val): 21 | return True 22 | if not root.left and not root.right and sum == root.val: 23 | return True 24 | return False 25 | 26 | """ 27 | [] 28 | 0 29 | [1,2,3,4,null,6,7,5,8] 30 | 15 31 | [1,2,2,3,null,null,3,4,null,null,4] 32 | 9 33 | """ 34 | -------------------------------------------------------------------------------- /Tree/113_PathSumII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-19 10:25:40 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | vector> pathSum(TreeNode* root, int sum) { 18 | vector> pathList; 19 | vector path; 20 | findPath(root, sum, path, pathList); 21 | return pathList; 22 | } 23 | 24 | void findPath(TreeNode* root, int sum, vector path, vector> &pathList){ 25 | if(root==NULL) return; 26 | path.push_back(root->val); 27 | if(root->left == NULL && root->right==NULL && root->val==sum){ 28 | pathList.push_back(path); 29 | } 30 | findPath(root->left, sum-root->val, path, pathList); 31 | findPath(root->right, sum-root->val, path, pathList); 32 | path.pop_back(); 33 | } 34 | }; 35 | 36 | /* 37 | [] 38 | 0 39 | [1,2,3,4,null,6,7,5,8] 40 | 15 41 | [1,2,2,3,3,3,3] 42 | 6 43 | */ 44 | -------------------------------------------------------------------------------- /Tree/144_BinaryTreePreorderTraversal.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | # Preorder Traversal 14 | def preorderTraversal(self, root): 15 | if not root: 16 | return [] 17 | result = [] 18 | node_stack = [] 19 | while root or node_stack: 20 | if root: 21 | node_stack.append(root) 22 | result.append(root.val) 23 | root = root.left 24 | else: 25 | node = node_stack.pop() 26 | root = node.right 27 | return result 28 | 29 | """ 30 | [] 31 | [1, null, 2, 3] 32 | [1, null, 2, 3, null, 4, 5] 33 | """ 34 | -------------------------------------------------------------------------------- /Tree/145_BinaryTreePostorderTraversal.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.left = None 10 | # self.right = None 11 | 12 | class Solution(object): 13 | # Postorder Traversal 14 | def postorderTraversal(self, root): 15 | if not root: 16 | return [] 17 | result = [] 18 | node_stack = [] 19 | while root or node_stack: 20 | if root: 21 | node_stack.append(root) 22 | result.append(root.val) 23 | root = root.right 24 | else: 25 | node = node_stack.pop() 26 | root = node.left 27 | return result[::-1] 28 | 29 | """ 30 | [] 31 | [1, null, 2, 3] 32 | [1, null, 2, 3, null, 4, 5] 33 | """ 34 | -------------------------------------------------------------------------------- /Tree/173_BinarySearchTreeIterator.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Definition for a binary tree node 4 | # class TreeNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.left = None 8 | # self.right = None 9 | 10 | 11 | class BSTIterator(object): 12 | def __init__(self, root): 13 | self.root = root 14 | self.node_stack = [] 15 | self.cur_node = root 16 | 17 | def hasNext(self): 18 | if self.cur_node or self.node_stack: 19 | return True 20 | else: 21 | return False 22 | 23 | def next(self): 24 | # inorder traversal 25 | while self.cur_node: 26 | self.node_stack.append(self.cur_node) 27 | self.cur_node = self.cur_node.left 28 | 29 | top = self.node_stack.pop() 30 | self.cur_node = top.right 31 | return top.val 32 | 33 | # Your BSTIterator will be called like this: 34 | # i, v = BSTIterator(root), [] 35 | # while i.hasNext(): v.append(i.next()) 36 | 37 | """ 38 | [] 39 | [1] 40 | [10,8,16,2,9,15,17] 41 | """ 42 | -------------------------------------------------------------------------------- /Tree/226_InvertBinaryTree.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.left = None 11 | # self.right = None 12 | 13 | class Solution(object): 14 | def invertTree(self, root): 15 | if not root: 16 | return None 17 | root.left, root.right = root.right, root.left 18 | self.invertTree(root.left) 19 | self.invertTree(root.right) 20 | return root 21 | 22 | """ 23 | [] 24 | [1,2,3,4,5,6] 25 | """ 26 | -------------------------------------------------------------------------------- /Tree/235_LowestCommonAncestorOfBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-09-20 19:37:23 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | // Easy to understand 18 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 19 | int min = p->val < q->val ? p->val : q->val; 20 | int max = p->val < q->val ? q->val : p->val; 21 | while(root){ 22 | if(root->val < min){ 23 | root = root->right; 24 | } 25 | else if(root->val > max){ 26 | root = root->left; 27 | } 28 | else{ 29 | return root; 30 | } 31 | } 32 | return nullptr; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Tree/94_BinaryTreeInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-19 11:32:27 4 | */ 5 | 6 | /** 7 | * Definition for a binary tree node. 8 | * struct TreeNode { 9 | * int val; 10 | * TreeNode *left; 11 | * TreeNode *right; 12 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | // iteratively implement 18 | vector inorderTraversal(TreeNode* root) { 19 | vector node_stack; 20 | vector inorder_val; 21 | while(root!=NULL || !node_stack.empty()){ 22 | if(root!=NULL){ 23 | node_stack.push_back(root); 24 | root = root->left; 25 | } 26 | else{ 27 | TreeNode *node = node_stack.back(); 28 | inorder_val.push_back(node->val); 29 | node_stack.pop_back(); 30 | root = node->right; 31 | } 32 | } 33 | return inorder_val; 34 | } 35 | }; 36 | 37 | /* 38 | [] 39 | [1] 40 | [1,2,3,null,null,4,null,null,5] 41 | */ 42 | -------------------------------------------------------------------------------- /Tree/96_UniqueBinarySearchTrees.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def numTrees(self, n): 7 | if not n: 8 | return 1 9 | dp = [0 for i in range(n + 1)] 10 | dp[0] = dp[1] = 1 11 | for i in range(2, n + 1): 12 | dp[i] += dp[i - 1] * 2 13 | # Get the symmetric left and right childs 14 | for j in range(1, (i - 2) / 2 + 1): 15 | dp[i] += dp[j] * dp[i - 1 - j] * 2 16 | 17 | # Get the mid one whitout symmetry. 18 | if (i - 2) % 2 != 0: 19 | mid_once = (i - 1) / 2 20 | dp[i] += dp[mid_once] * dp[i - 1 - mid_once] 21 | 22 | return dp[n] 23 | 24 | """ 25 | 0 26 | 1 27 | 3 28 | 15 29 | """ 30 | -------------------------------------------------------------------------------- /Tree/Demo.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-08-21 09:49:20 5 | 6 | 7 | def inorderTraversal(self, root): 8 | tree_stack = [] 9 | inorder_tra = [] 10 | while root or tree_stack: 11 | # Go along the left child 12 | if root: 13 | tree_stack.append(root) 14 | root = root.left 15 | # Meet a left, go back to the parent node 16 | else: 17 | node = tree_stack.pop() 18 | inorder_tra.append(node.val) 19 | root = node.right 20 | 21 | return inorder_tra 22 | -------------------------------------------------------------------------------- /Tree/test_tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-09-07 08:42:12 4 | */ 5 | #include 6 | #include "tree.h" 7 | #include 8 | using namespace std; 9 | 10 | int main() { 11 | Tree demo; 12 | /* 13 | 1 14 | / \ 15 | 2 3 16 | \ / \ 17 | 4 5 6 18 | / \ 19 | 7 8 20 | */ 21 | demo.deserialize("1 2 3 null 4 5 6 7 8"); 22 | cout << demo.serialize() << endl; 23 | cout << demo.pre_order_r(demo.get_root()) << endl; 24 | cout << demo.pre_order_i(demo.get_root()) << endl; 25 | 26 | cout << demo.post_order_r(demo.get_root()) << endl; 27 | cout << demo.post_order_i(demo.get_root()) << endl; 28 | 29 | cout << demo.in_order_r(demo.get_root()) << endl; 30 | cout << demo.in_order_i(demo.get_root()) << endl; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /TwoPointers/11_ContainerWithMostWater.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def maxArea(self, height): 7 | """ 8 | :type height: List[int] 9 | :rtype: int 10 | """ 11 | length = len(height) 12 | left = 0 13 | right = length - 1 14 | max_area = 0 15 | 16 | # To find the biggest container, we recursively find a container 17 | # which is much bigger than what we have find before. 18 | while left < right: 19 | area = (right - left) * min(height[left], height[right]) 20 | max_area = max(max_area, area) 21 | 22 | # To get a bigger container, we move point(lower height) to right 23 | if height[left] < height[right]: 24 | min_height = height[left] 25 | left += 1 26 | while height[left] < min_height: 27 | left += 1 28 | 29 | # To get a bigger container, we move point(lower height) to left 30 | else: 31 | min_height = height[right] 32 | right -= 1 33 | while height[right] < min_height: 34 | right -= 1 35 | 36 | return max_area 37 | 38 | """ 39 | [1,1] 40 | [1,2,3,4,8,7,6,5] 41 | [] 42 | """ 43 | -------------------------------------------------------------------------------- /TwoPointers/125_ValidPalindrome.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def isPalindrome(self, s): 7 | """ 8 | :type s: str 9 | :rtype: bool 10 | """ 11 | alpha_num_str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 12 | s = s.upper() 13 | s_l = len(s) 14 | pre = 0 15 | post = s_l - 1 16 | while pre < post and pre < s_l and post >= 0: 17 | # Remember the situation ",,..". 18 | # Make sure pre and post don't 19 | while pre < s_l and s[pre] not in alpha_num_str: 20 | pre += 1 21 | while post >= 0 and s[post] not in alpha_num_str: 22 | post -= 1 23 | if pre >= post: 24 | break 25 | if s[pre] != s[post]: 26 | return False 27 | pre += 1 28 | post -= 1 29 | 30 | return True 31 | 32 | """ 33 | "" 34 | "1a2" 35 | ",,,,...." 36 | "A man, a plan, a canal: Panama" 37 | "race a car" 38 | """ 39 | -------------------------------------------------------------------------------- /TwoPointers/19_RemoveNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-04-14 09:58:46 4 | */ 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * struct ListNode { 9 | * int val; 10 | * ListNode *next; 11 | * ListNode(int x) : val(x), next(NULL) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | ListNode* removeNthFromEnd(ListNode* head, int n) { 17 | ListNode *first = head; 18 | // Let the first pointer goto n+1'th node. 19 | int steps = 0; 20 | while(first){ 21 | if(steps == n+1){ 22 | break; 23 | } 24 | first = first->next; 25 | steps += 1; 26 | } 27 | 28 | // the node to be removed is the head node. 29 | if(steps < n+1){ 30 | return head->next; 31 | } 32 | 33 | ListNode *second = head; 34 | while(first){ 35 | second = second->next; 36 | first = first->next; 37 | } 38 | second->next = second->next->next; 39 | return head; 40 | } 41 | }; 42 | 43 | /* 44 | [1] 45 | 1 46 | [1,2,3,4,5,6,7,8] 47 | 5 48 | [1,2,3,4,5,6,7,8] 49 | 8 50 | */ 51 | -------------------------------------------------------------------------------- /TwoPointers/19_RemoveNthNodeFromEndOfList.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Definition for singly-linked list. 5 | # class ListNode(object): 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.next = None 9 | 10 | 11 | class Solution(object): 12 | def removeNthFromEnd(self, head, n): 13 | steps = 0 14 | first = head 15 | # Let the first pointer goto n+1'th node. 16 | while first: 17 | first = first.next 18 | steps += 1 19 | if steps == n + 1: 20 | break 21 | 22 | # the node to be removed is the head node. 23 | if steps < n + 1: 24 | return head.next 25 | 26 | # Let second move with first one by one. When first meet the NULL 27 | # Second will meet the (N+1)th Node from end of list. 28 | second = head 29 | while first: 30 | first = first.next 31 | second = second.next 32 | 33 | # Next node of the second will be removed. 34 | second.next = second.next.next 35 | return head 36 | 37 | """ 38 | [1] 39 | 1 40 | [1,2,3,4,5,6,7,8] 41 | 5 42 | [1,2,3,4,5,6,7,8] 43 | 8 44 | """ 45 | -------------------------------------------------------------------------------- /TwoPointers/209_MinimumSizeSubarraySum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | # Maintain a minimum window with two indices. 8 | def minSubArrayLen(self, s, nums): 9 | if not nums: 10 | return 0 11 | start, end, sums, min_len = 0, 0, nums[0], 0 12 | len_nums = len(nums) 13 | while end < len_nums: 14 | if sums < s and end + 1 < len_nums: 15 | end += 1 16 | sums += nums[end] 17 | if sums >= s: 18 | if min_len == 0: 19 | min_len = end - start + 1 20 | else: 21 | min_len = min(min_len, end - start + 1) 22 | sums -= nums[start] 23 | if start < end: 24 | start += 1 25 | if end == len_nums - 1 and sums < s: 26 | break 27 | return min_len 28 | 29 | """ 30 | 100 31 | [] 32 | 20 33 | [1,3,12,8,3,4,21] 34 | 0 35 | [1,1,2] 36 | 4 37 | [1,4,4] 38 | """ 39 | -------------------------------------------------------------------------------- /TwoPointers/283_MoveZeroes.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | 5 | 6 | class Solution(object): 7 | def moveZeroes(self, nums): 8 | # Get sum of zeros 9 | count = 0 10 | for num in nums: 11 | if not num: 12 | count += 1 13 | 14 | # Move the no-zero number to the right position. 15 | pos, i = 0, 0 16 | while pos < len(nums): 17 | if nums[pos]: 18 | nums[i] = nums[pos] 19 | i += 1 20 | pos += 1 21 | 22 | # Append the zeros 23 | if count: 24 | nums[-count:] = [0] * count 25 | return 26 | 27 | """ 28 | [] 29 | [1] 30 | [0] 31 | [0,0,0] 32 | [0,1,0,3,12] 33 | [7,6,5,4,0,4,0,5,6,0,7,0,0] 34 | """ 35 | -------------------------------------------------------------------------------- /TwoPointers/287_FindTheDuplicateNumber.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # Refer to: 5 | # https://leetcode.com/discuss/61514/understood-solution-space-without-modifying-explanation 6 | 7 | 8 | class Solution(object): 9 | """ 10 | Use two pointers the fast and the slow. The fast one goes forward two steps 11 | each time, while the slow one goes only step each time. 12 | In fact, they meet in a circle, the duplicate number 13 | must be the entry point of the circle when visiting the array from nums[0]. 14 | """ 15 | def findDuplicate(self, nums): 16 | # assert(len(nums) > 1) 17 | slow = nums[0] 18 | fast = nums[nums[0]] 19 | while slow != fast: 20 | slow = nums[slow] 21 | fast = nums[nums[fast]] 22 | 23 | target = 0 24 | while target != slow: 25 | target = nums[target] 26 | slow = nums[slow] 27 | return target 28 | 29 | """ 30 | [1] 31 | [1,1] 32 | [1,3,4,5,1,2] 33 | [1,3,4,1,1,2] 34 | """ 35 | -------------------------------------------------------------------------------- /TwoPointers/345_ReverseVowelsOfString.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: xuezaigds@gmail.com 4 | # @Last Modified time: 2016-07-04 12:05:02 5 | 6 | 7 | class Solution(object): 8 | def reverseVowels(self, s): 9 | # Scan while incrementing start and decrementing end. 10 | all_vowels = set(['a', 'e', 'i', 'o', 'u', 11 | 'A', 'E', 'I', 'O', 'U']) 12 | s = list(s) 13 | left, right = 0, len(s) - 1 14 | while left < right: 15 | if s[left] in all_vowels and s[right] in all_vowels: 16 | s[left], s[right] = s[right], s[left] 17 | left += 1 18 | right -= 1 19 | elif s[left] in all_vowels: 20 | right -= 1 21 | elif s[right] in all_vowels: 22 | left += 1 23 | else: 24 | left += 1 25 | right -= 1 26 | return "".join(s) 27 | 28 | """ 29 | "" 30 | "hello" 31 | "leetcode" 32 | "Administrator" 33 | """ 34 | -------------------------------------------------------------------------------- /TwoPointers/75_SortColors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @Author: xuezaigds@gmail.com 3 | * @Last Modified time: 2016-08-30 13:04:54 4 | */ 5 | 6 | class Solution { 7 | public: 8 | // Wiki: https://en.wikipedia.org/wiki/Dutch_national_flag_problem 9 | void sortColors(vector& nums) { 10 | int pos_put_red = 0, pos_put_blue = nums.size()-1; 11 | int scan_index = 0; 12 | while(scan_index <= pos_put_blue){ 13 | if(nums[scan_index] == 0){ 14 | swap(nums[scan_index++], nums[pos_put_red++]); 15 | } 16 | else if(nums[scan_index] == 2){ 17 | swap(nums[scan_index], nums[pos_put_blue--]); 18 | } 19 | else{ 20 | scan_index ++; 21 | } 22 | } 23 | } 24 | }; 25 | 26 | /* 27 | [0] 28 | [1,0] 29 | [0,1,2] 30 | [1,1,1,2,0,0,0,0,2,2,1,1,2] 31 | */ 32 | -------------------------------------------------------------------------------- /TwoPointers/75_SortColors.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Solution(object): 6 | def sortColors(self, nums): 7 | len_n = len(nums) 8 | # pos_put_0: next position to put 0 9 | # pos_put_2: next position to put 2 10 | pos_put_0 = 0 11 | pos_put_2 = len_n - 1 12 | index = 0 13 | while index <= pos_put_2: 14 | if nums[index] == 0: 15 | nums[index], nums[pos_put_0] = nums[pos_put_0], nums[index] 16 | pos_put_0 += 1 17 | index += 1 18 | 19 | elif nums[index] == 2: 20 | nums[index], nums[pos_put_2] = nums[pos_put_2], nums[index] 21 | pos_put_2 -= 1 22 | 23 | else: 24 | index += 1 25 | 26 | """ 27 | [0] 28 | [1,0] 29 | [0,1,2] 30 | [1,1,1,2,0,0,0,0,2,2,1,1,2] 31 | """ 32 | -------------------------------------------------------------------------------- /TwoPointers/README.md: -------------------------------------------------------------------------------- 1 | # 双指针 2 | 3 | 滑动窗口 4 | --------------------------------------------------------------------------------