diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..fc0a92bc6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# generated by python builder +*.pyc diff --git a/README-bitbucket.md b/README-bitbucket.md new file mode 100644 index 000000000..952717915 --- /dev/null +++ b/README-bitbucket.md @@ -0,0 +1,161 @@ +LeetCode +======== + +LeetCode C++ Solutions + +| Title | Solution | Add Date | Difficulty | +| ----- | -------- | -------- | ---------- | +|[Find Minimum in Rotated Sorted Array II](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)| [C++](./src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.II.cpp)|2014/10/20|Hard| +|[Find Minimum in Rotated Sorted Array](https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/)| [C++](./src/findMinimumInRotatedSortedArray/findMinimumInRotatedSortedArray.cpp)|2014/10/15|Medium| +|[Maximum Product Subarray](https://oj.leetcode.com/problems/maximum-product-subarray/)| [C++](./src/maximumProductSubarray/maximumProductSubarray.cpp)|2014/9/23|Medium| +|[Reverse Words in a String](https://oj.leetcode.com/problems/reverse-words-in-a-string/)| [C++](./src/reverseWordsInAString/reverseWordsInAString.cpp)|2014/3/5|Medium| +|[Evaluate Reverse Polish Notation](https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./src/evaluateReversePolishNotation/evaluateReversePolishNotation.cpp)|2013/11/27|Medium| +|[Max Points on a Line](https://oj.leetcode.com/problems/max-points-on-a-line/)| [C++](./src/maxPointsOnALine/maxPointsOnALine.cpp)|2013/11/22|Hard| +|[Sort List](https://oj.leetcode.com/problems/sort-list/)| [C++](./src/sortList/sortList.cpp)|2013/11/16|Medium| +|[Insertion Sort List](https://oj.leetcode.com/problems/insertion-sort-list/)| [C++](./src/insertionSortList/insertionSortList.cpp)|2013/11/12|Medium| +|[LRU Cache](https://oj.leetcode.com/problems/lru-cache/)| [C++](./src/LRUCache/LRUCache.cpp)|2013/11/9|Hard| +|[Binary Tree Postorder Traversal](https://oj.leetcode.com/problems/binary-tree-postorder-traversal/)| [C++](./src/binaryTreePostorderTraversal/binaryTreePostorderTraversal.cpp)|2013/11/7|Hard| +|[Binary Tree Preorder Traversal](https://oj.leetcode.com/problems/binary-tree-preorder-traversal/)| [C++](./src/binaryTreePreorderTraversal/binaryTreePreorderTraversal.cpp)|2013/11/5|Medium| +|[Reorder List](https://oj.leetcode.com/problems/reorder-list/)| [C++](./src/reorderList/reorderList.cpp)|2013/11/2|Medium| +|[Linked List Cycle II](https://oj.leetcode.com/problems/linked-list-cycle-ii/)| [C++](./src/linkedListCycle/linkedListCycle.II.cpp)|2013/10/30|Medium| +|[Linked List Cycle](https://oj.leetcode.com/problems/linked-list-cycle/)| [C++](./src/linkedListCycle/linkedListCycle.cpp)|2013/10/28|Medium| +|[Word Break II](https://oj.leetcode.com/problems/word-break-ii/)| [C++](./src/wordBreak/wordBreak.II.cpp)|2013/10/5|Hard| +|[Word Break](https://oj.leetcode.com/problems/word-break/)| [C++](./src/wordBreak/wordBreak.cpp)|2013/10/4|Medium| +|[Copy List with Random Pointer](https://oj.leetcode.com/problems/copy-list-with-random-pointer/)| [C++](./src/copyListWithRandomPointer/copyListWithRandomPointer.cpp)|2013/10/3|Hard| +|[Single Number II](https://oj.leetcode.com/problems/single-number-ii/)| [C++](./src/singleNumber/singleNumber.II.cpp)|2013/10/2|Medium| +|[Single Number](https://oj.leetcode.com/problems/single-number/)| [C++](./src/singleNumber/singleNumber.cpp)|2013/10/1|Medium| +|[Candy](https://oj.leetcode.com/problems/candy/)| [C++](./src/candy/candy.cpp)|2013/9/30|Hard| +|[Gas Station](https://oj.leetcode.com/problems/gas-station/)| [C++](./src/gasStation/gasStation.cpp)|2013/9/28|Medium| +|[Clone Graph](https://oj.leetcode.com/problems/clone-graph/)| [C++](./src/cloneGraph/cloneGraph.cpp)|2013/9/24|Medium| +|[Palindrome Partitioning II](https://oj.leetcode.com/problems/palindrome-partitioning-ii/)| [C++](./src/palindromePartitioning/palindromePartitioning.II.cpp)|2013/2/28|Hard| +|[Palindrome Partitioning](https://oj.leetcode.com/problems/palindrome-partitioning/)| [C++](./src/palindromePartitioning/palindromePartitioning.cpp)|2013/2/27|Medium| +|[Surrounded Regions](https://oj.leetcode.com/problems/surrounded-regions/)| [C++](./src/surroundedRegions/surroundedRegions.cpp)|2013/2/21|Medium| +|[Sum Root to Leaf Numbers](https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/)| [C++](./src/sumRootToLeafNumber/sumRootToLeafNumber.cpp)|2013/2/18|Medium| +|[Longest Consecutive Sequence](https://oj.leetcode.com/problems/longest-consecutive-sequence/)| [C++](./src/longestConsecutiveSequence/longestConsecutiveSequence.cpp)|2013/2/13|Hard| +|[Word Ladder II](https://oj.leetcode.com/problems/word-ladder-ii/)| [C++](./src/wordLadder/wordLadder.II.cpp)|2013/2/10|Hard| +|[Word Ladder](https://oj.leetcode.com/problems/word-ladder/)| [C++](./src/wordLadder/wordLadder.cpp)|2013/2/10|Medium| +|[Valid Palindrome](https://oj.leetcode.com/problems/valid-palindrome/)| [C++](./src/validPalindrome/validPalindrome.cpp)|2013/1/12|Easy| +|[Binary Tree Maximum Path Sum](https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/)| [C++](./src/binaryTreeMaximumPathSum/binaryTreeMaximumPathSum.cpp)|2012/11/7|Hard| +|[Best Time to Buy and Sell Stock III](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| [C++](./src/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.III.cpp)|2012/11/6|Hard| +|[Best Time to Buy and Sell Stock II](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [C++](./src/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.II.cpp)|2012/10/30|Medium| +|[Best Time to Buy and Sell Stock](https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [C++](./src/bestTimeToBuyAndSellStock/bestTimeToBuyAndSellStock.cpp)|2012/10/30|Medium| +|[Triangle](https://oj.leetcode.com/problems/triangle/)| [C++](./src/triangle/triangle.cpp)|2012/10/29|Medium| +|[Pascal's Triangle II](https://oj.leetcode.com/problems/pascals-triangle-ii/)| [C++](./src/pascalTriangle/pascalTriangle.II.cpp)|2012/10/28|Easy| +|[Pascal's Triangle](https://oj.leetcode.com/problems/pascals-triangle/)| [C++](./src/pascalTriangle/pascalTriangle.cpp)|2012/10/28|Easy| +|[Populating Next Right Pointers in Each Node II](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| [C++](./src/populatingNextRightPointersInEachNode/populatingNextRightPointersInEachNode.II.cpp)|2012/10/28|Hard| +|[Populating Next Right Pointers in Each Node](https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/)| [C++](./src/populatingNextRightPointersInEachNode/populatingNextRightPointersInEachNode.cpp)|2012/10/28|Medium| +|[Distinct Subsequences](https://oj.leetcode.com/problems/distinct-subsequences/)| [C++](./src/distinctSubsequences/distinctSubsequences.cpp)|2012/10/18|Hard| +|[Flatten Binary Tree to Linked List](https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/)| [C++](./src/flattenBinaryTreeToLinkedList/flattenBinaryTreeToLinkedList.cpp)|2012/10/14|Medium| +|[Path Sum II](https://oj.leetcode.com/problems/path-sum-ii/)| [C++](./src/pathSum/pathSum.II.cpp)|2012/10/14|Medium| +|[Path Sum](https://oj.leetcode.com/problems/path-sum/)| [C++](./src/pathSum/pathSum.cpp)|2012/10/13|Easy| +|[Minimum Depth of Binary Tree](https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/)| [C++](./src/minimumDepthOfBinaryTree/minimumDepthOfBinaryTree.cpp)|2012/10/9|Easy| +|[Balanced Binary Tree](https://oj.leetcode.com/problems/balanced-binary-tree/)| [C++](./src/balancedBinaryTree/balancedBinaryTree.cpp)|2012/10/8|Easy| +|[Convert Sorted List to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)| [C++](./src/convertSortedListToBinarySearchTree/convertSortedListToBinarySearchTree.cpp)|2012/10/2|Medium| +|[Convert Sorted Array to Binary Search Tree](https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)| [C++](./src/convertSortedArrayToBinarySearchTree/convertSortedArrayToBinarySearchTree.cpp)|2012/10/2|Medium| +|[Binary Tree Level Order Traversal II](https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [C++](./src/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.II.cpp)|2012/10/1|Easy| +|[Construct Binary Tree from Inorder and Postorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)| [C++](./src/constructBinaryTreeFromInorderAndPostorderTraversal/constructBinaryTreeFromInorderAndPostorderTraversal.cpp)|2012/9/30|Medium| +|[Construct Binary Tree from Preorder and Inorder Traversal](https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)| [C++](./src/constructBinaryTreeFromPreorderAndInorderTraversal/constructBinaryTreeFromPreorderAndInorderTraversal.cpp)|2012/9/30|Medium| +|[Maximum Depth of Binary Tree](https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/)| [C++](./src/maximumDepthOfBinaryTree/maximumDepthOfBinaryTree.cpp)|2012/9/29|Easy| +|[Binary Tree Zigzag Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [C++](./src/binaryTreeZigzagLevelOrderTraversal/binaryTreeZigzagLevelOrderTraversal.cpp)|2012/9/28|Medium| +|[Binary Tree Level Order Traversal](https://oj.leetcode.com/problems/binary-tree-level-order-traversal/)| [C++](./src/binaryTreeLevelOrderTraversal/binaryTreeLevelOrderTraversal.cpp)|2012/9/28|Easy| +|[Symmetric Tree](https://oj.leetcode.com/problems/symmetric-tree/)| [C++](./src/symmetricTree/symmetricTree.cpp)|2012/9/23|Easy| +|[Same Tree](https://oj.leetcode.com/problems/same-tree/)| [C++](./src/sameTree/sameTree.cpp)|2012/9/3|Easy| +|[Recover Binary Search Tree](https://oj.leetcode.com/problems/recover-binary-search-tree/)| [C++](./src/recoverBinarySearchTree/recoverBinarySearchTree.cpp)|2012/9/1|Hard| +|[Validate Binary Search Tree](https://oj.leetcode.com/problems/validate-binary-search-tree/)| [C++](./src/validateBinarySearchTree/validateBinarySearchTree.cpp)|2012/8/31|Medium| +|[Interleaving String](https://oj.leetcode.com/problems/interleaving-string/)| [C++](./src/interleavingString/interleavingString.cpp)|2012/8/30|Hard| +|[Unique Binary Search Trees II](https://oj.leetcode.com/problems/unique-binary-search-trees-ii/)| [C++](./src/uniqueBinarySearchTrees/uniqueBinarySearchTrees.II.cpp)|2012/8/27|Medium| +|[Unique Binary Search Trees](https://oj.leetcode.com/problems/unique-binary-search-trees/)| [C++](./src/uniqueBinarySearchTrees/uniqueBinarySearchTrees.cpp)|2012/8/27|Medium| +|[Binary Tree Inorder Traversal](https://oj.leetcode.com/problems/binary-tree-inorder-traversal/)| [C++](./src/binaryTreeInorderTraversal/binaryTreeInorderTraversal.cpp)|2012/8/27|Medium| +|[Restore IP Addresses](https://oj.leetcode.com/problems/restore-ip-addresses/)| [C++](./src/restoreIPAddresses/restoreIPAddresses.cpp)|2012/8/7|Medium| +|[Reverse Linked List II](https://oj.leetcode.com/problems/reverse-linked-list-ii/)| [C++](./src/reverseLinkedList/reverseLinkedList.II.cpp)|2012/6/27|Medium| +|[Subsets II](https://oj.leetcode.com/problems/subsets-ii/)| [C++](./src/subsets/subsets.II.cpp)|2012/6/25|Medium| +|[Decode Ways](https://oj.leetcode.com/problems/decode-ways/)| [C++](./src/decodeWays/decodeWays.cpp)|2012/6/25|Medium| +|[Gray Code](https://oj.leetcode.com/problems/gray-code/)| [C++](./src/grayCode/grayCode.cpp)|2012/5/20|Medium| +|[Merge Sorted Array](https://oj.leetcode.com/problems/merge-sorted-array/)| [C++](./src/mergeTwoSortedArray/mergeTwoSortedArray.cpp)|2012/5/20|Easy| +|[Scramble String](https://oj.leetcode.com/problems/scramble-string/)| [C++](./src/scrambleString/scrambleString.cpp)|2012/4/30|Hard| +|[Partition List](https://oj.leetcode.com/problems/partition-list/)| [C++](./src/partitionList/partitionList.cpp)|2012/4/30|Medium| +|[Maximal Rectangle](https://oj.leetcode.com/problems/maximal-rectangle/)| [C++](./src/maximalRectangle/maximalRectangle.cpp)|2012/4/23|Hard| +|[Largest Rectangle in Histogram](https://oj.leetcode.com/problems/largest-rectangle-in-histogram/)| [C++](./src/largestRectangleInHistogram/largestRectangleInHistogram.cpp)|2012/4/22|Hard| +|[Remove Duplicates from Sorted List II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [C++](./src/removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.II.cpp)|2012/4/22|Medium| +|[Remove Duplicates from Sorted List](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/)| [C++](./src/removeDuplicatesFromSortedList/removeDuplicatesFromSortedList.cpp)|2012/4/22|Easy| +|[Search in Rotated Sorted Array II](https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/)| [C++](./src/searchInRotatedSortedArray/searchInRotatedSortedArray.II.cpp)|2012/4/19|Medium| +|[Remove Duplicates from Sorted Array II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [C++](./src/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.II.cpp)|2012/4/19|Medium| +|[Word Search](https://oj.leetcode.com/problems/word-search/)| [C++](./src/wordSearch/wordSearch.cpp)|2012/4/18|Medium| +|[Subsets](https://oj.leetcode.com/problems/subsets/)| [C++](./src/subsets/subsets.cpp)|2012/4/18|Medium| +|[Combinations](https://oj.leetcode.com/problems/combinations/)| [C++](./src/combinations/combinations.cpp)|2012/4/18|Medium| +|[Minimum Window Substring](https://oj.leetcode.com/problems/minimum-window-substring/)| [C++](./src/minimumWindowSubstring/minimumWindowSubstring.cpp)|2012/4/15|Hard| +|[Sort Colors](https://oj.leetcode.com/problems/sort-colors/)| [C++](./src/sortColors/sortColors.cpp)|2012/4/8|Medium| +|[Search a 2D Matrix](https://oj.leetcode.com/problems/search-a-2d-matrix/)| [C++](./src/search2DMatrix/search2DMatrix.cpp)|2012/4/6|Medium| +|[Set Matrix Zeroes](https://oj.leetcode.com/problems/set-matrix-zeroes/)| [C++](./src/setMatrixZeroes/setMatrixZeroes.cpp)|2012/4/5|Medium| +|[Edit Distance](https://oj.leetcode.com/problems/edit-distance/)| [C++](./src/editDistance/editDistance.cpp)|2012/4/4|Hard| +|[Simplify Path](https://oj.leetcode.com/problems/simplify-path/)| [C++](./src/simplifyPath/simplifyPath.cpp)|2012/4/3|Medium| +|[Climbing Stairs](https://oj.leetcode.com/problems/climbing-stairs/)| [C++](./src/climbStairs/climbStairs.cpp)|2012/4/3|Easy| +|[Sqrt(x)](https://oj.leetcode.com/problems/sqrtx/)| [C++](./src/sqrt/sqrt.cpp)|2012/4/3|Medium| +|[Text Justification](https://oj.leetcode.com/problems/text-justification/)| [C++](./src/textJustification/textJustification.cpp)|2012/4/3|Hard| +|[Plus One](https://oj.leetcode.com/problems/plus-one/)| [C++](./src/plusOne/plusOne.cpp)|2012/4/2|Easy| +|[Valid Number](https://oj.leetcode.com/problems/valid-number/)| [C++](./src/validNumber/validNumber.cpp)|2012/4/2|Easy| +|[Add Binary](https://oj.leetcode.com/problems/add-binary/)| [C++](./src/addBinary/addBinary.cpp)|2012/4/2|Easy| +|[Merge Two Sorted Lists](https://oj.leetcode.com/problems/merge-two-sorted-lists/)| [C++](./src/mergeTwoSortedList/mergeTwoSortedList.cpp)|2012/3/30|Easy| +|[Minimum Path Sum](https://oj.leetcode.com/problems/minimum-path-sum/)| [C++](./src/minimumPathSum/minimumPathSum.cpp)|2012/3/28|Medium| +|[Unique Paths II](https://oj.leetcode.com/problems/unique-paths-ii/)| [C++](./src/uniquePaths/uniquePaths.II.cpp)|2012/3/28|Medium| +|[Unique Paths](https://oj.leetcode.com/problems/unique-paths/)| [C++](./src/uniquePaths/uniquePaths.cpp)|2012/3/28|Medium| +|[Rotate List](https://oj.leetcode.com/problems/rotate-list/)| [C++](./src/rotateList/rotateList.cpp)|2012/3/27|Medium| +|[Permutation Sequence](https://oj.leetcode.com/problems/permutation-sequence/)| [C++](./src/permutationSequence/permutationSequence.cpp)|2012/3/27|Medium| +|[Spiral Matrix II](https://oj.leetcode.com/problems/spiral-matrix-ii/)| [C++](./src/spiralMatrix/spiralMatrix.II.cpp)|2012/3/27|Medium| +|[Length of Last Word](https://oj.leetcode.com/problems/length-of-last-word/)| [C++](./src/lengthOfLastWord/lengthOfLastWord.cpp)|2012/3/27|Easy| +|[Insert Interval](https://oj.leetcode.com/problems/insert-interval/)| [C++](./src/insertInterval/insertInterval.cpp)|2012/3/27|Hard| +|[Merge Intervals](https://oj.leetcode.com/problems/merge-intervals/)| [C++](./src/mergeIntervals/mergeIntervals.cpp)|2012/3/26|Hard| +|[Jump Game](https://oj.leetcode.com/problems/jump-game/)| [C++](./src/jumpGame/jumpGame.cpp)|2012/3/24|Medium| +|[Spiral Matrix](https://oj.leetcode.com/problems/spiral-matrix/)| [C++](./src/spiralMatrix/spiralMatrix.cpp)|2012/3/24|Medium| +|[Maximum Subarray](https://oj.leetcode.com/problems/maximum-subarray/)| [C++](./src/maximumSubArray/maximumSubArray.cpp)|2012/3/21|Medium| +|[N-Queens II](https://oj.leetcode.com/problems/n-queens-ii/)| [C++](./src/nQueens/nQueuens.II.cpp)|2012/3/20|Hard| +|[N-Queens](https://oj.leetcode.com/problems/n-queens/)| [C++](./src/nQueens/nQueuens.cpp)|2012/3/19|Hard| +|["Pow(x, n)"](https://oj.leetcode.com/problems/powx-n/)| [C++](./src/pow/pow.cpp)|2012/3/19|Medium| +|[Anagrams](https://oj.leetcode.com/problems/anagrams/)| [C++](./src/anagrams/anagrams.cpp)|2012/3/19|Medium| +|[Rotate Image](https://oj.leetcode.com/problems/rotate-image/)| [C++](./src/rotateImage/rotateImage.cpp)|2012/3/17|Medium| +|[Permutations II](https://oj.leetcode.com/problems/permutations-ii/)| [C++](./src/permutations/permutations.II.cpp)|2012/3/16|Hard| +|[Permutations](https://oj.leetcode.com/problems/permutations/)| [C++](./src/permutations/permutations.cpp)|2012/3/16|Medium| +|[Jump Game II](https://oj.leetcode.com/problems/jump-game-ii/)| [C++](./src/jumpGame/jumpGame.II.cpp)|2012/3/16|Hard| +|[Wildcard Matching](https://oj.leetcode.com/problems/wildcard-matching/)| [C++](./src/wildcardMatching/wildcardMatching.cpp)|2012/3/15|Hard| +|[Multiply Strings](https://oj.leetcode.com/problems/multiply-strings/)| [C++](./src/multiplyStrings/multiplyStrings.cpp)|2012/3/12|Medium| +|[Trapping Rain Water](https://oj.leetcode.com/problems/trapping-rain-water/)| [C++](./src/trappingRainWater/trappingRainWater.cpp)|2012/3/10|Hard| +|[First Missing Positive](https://oj.leetcode.com/problems/first-missing-positive/)| [C++](./src/firstMissingPositive/firstMissingPositive.cpp)|2012/3/8|Hard| +|[Combination Sum II](https://oj.leetcode.com/problems/combination-sum-ii/)| [C++](./src/combinationSum/combinationSum.II.cpp)|2012/3/6|Medium| +|[Combination Sum](https://oj.leetcode.com/problems/combination-sum/)| [C++](./src/combinationSum/combinationSum.cpp)|2012/3/6|Medium| +|[Count and Say](https://oj.leetcode.com/problems/count-and-say/)| [C++](./src/countAndSay/countAndSay.cpp)|2012/3/5|Easy| +|[Sudoku Solver](https://oj.leetcode.com/problems/sudoku-solver/)| [C++](./src/sudokuSolver/sudokuSolver.cpp)|2012/3/4|Hard| +|[Valid Sudoku](https://oj.leetcode.com/problems/valid-sudoku/)| [C++](./src/validSudoku/validSudoku.cpp)|2012/3/3|Easy| +|[Search Insert Position](https://oj.leetcode.com/problems/search-insert-position/)| [C++](./src/searchInsertPosition/searchInsertPosition.cpp)|2012/3/3|Medium| +|[Search for a Range](https://oj.leetcode.com/problems/search-for-a-range/)| [C++](./src/searchForRange/searchForRange.cpp)|2012/3/2|Medium| +|[Search in Rotated Sorted Array](https://oj.leetcode.com/problems/search-in-rotated-sorted-array/)| [C++](./src/searchInRotatedSortedArray/searchInRotatedSortedArray.cpp)|2012/3/2|Hard| +|[Longest Valid Parentheses](https://oj.leetcode.com/problems/longest-valid-parentheses/)| [C++](./src/longestValidParentheses/longestValidParentheses.cpp)|2012/2/29|Hard| +|[Next Permutation](https://oj.leetcode.com/problems/next-permutation/)| [C++](./src/nextPermutation/nextPermutation.cpp)|2012/2/25|Medium| +|[Substring with Concatenation of All Words](https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/)| [C++](./src/substringWithConcatenationOfAllWords/substringWithConcatenationOfAllWords.cpp)|2012/2/23|Hard| +|[Divide Two Integers](https://oj.leetcode.com/problems/divide-two-integers/)| [C++](./src/divideTwoInt/divideTwoInt.cpp)|2012/2/18|Medium| +|[Implement strStr()](https://oj.leetcode.com/problems/implement-strstr/)| [C++](./src/strStr/strStr.cpp)|2012/2/18|Easy| +|[Remove Element](https://oj.leetcode.com/problems/remove-element/)| [C++](./src/removeElement/removeElement.cpp)|2012/2/16|Easy| +|[Remove Duplicates from Sorted Array](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/)| [C++](./src/removeDuplicatesFromSortedArray/removeDuplicatesFromSortedArray.cpp)|2012/2/16|Easy| +|[Reverse Nodes in k-Group](https://oj.leetcode.com/problems/reverse-nodes-in-k-group/)| [C++](./src/reverseNodesInKGroup/reverseNodesInKGroup.cpp)|2012/2/15|Hard| +|[Swap Nodes in Pairs](https://oj.leetcode.com/problems/swap-nodes-in-pairs/)| [C++](./src/swapNodesInPairs/swapNodesInPairs.cpp)|2012/2/14|Medium| +|[Merge k Sorted Lists](https://oj.leetcode.com/problems/merge-k-sorted-lists/)| [C++](./src/mergeKSortedLists/mergeKSortedLists.cpp)|2012/2/13|Hard| +|[Generate Parentheses](https://oj.leetcode.com/problems/generate-parentheses/)| [C++](./src/generateParentheses/generateParentheses.cpp)|2012/2/12|Medium| +|[Valid Parentheses](https://oj.leetcode.com/problems/valid-parentheses/)| [C++](./src/validParentheses/validParentheses.cpp)|2012/1/30|Easy| +|[Remove Nth Node From End of List](https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./src/removeNthNodeFromEndOfList/removeNthNodeFromEndOfList.cpp)|2012/1/27|Easy| +|[Letter Combinations of a Phone Number](https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/)| [C++](./src/letterCombinationsOfAPhoneNumber/letterCombinationsOfAPhoneNumber.cpp)|2012/1/26|Medium| +|[4Sum](https://oj.leetcode.com/problems/4sum/)| [C++](./src/4Sum/4Sum.cpp)|2012/1/26|Medium| +|[3Sum Closest](https://oj.leetcode.com/problems/3sum-closest/)| [C++](./src/3SumClosest/3SumClosest.cpp)|2012/1/18|Medium| +|[3Sum](https://oj.leetcode.com/problems/3sum/)| [C++](./src/3Sum/3Sum.cpp)|2012/1/17|Medium| +|[Longest Common Prefix](https://oj.leetcode.com/problems/longest-common-prefix/)| [C++](./src/longestCommonPrefix/longestCommonPrefix.cpp)|2012/1/17|Easy| +|[Roman to Integer](https://oj.leetcode.com/problems/roman-to-integer/)| [C++](./src/romanToInteger/romanToInteger.cpp)|2012/1/15|Easy| +|[Integer to Roman](https://oj.leetcode.com/problems/integer-to-roman/)| [C++](./src/integerToRoman/integerToRoman.cpp)|2012/1/15|Medium| +|[Container With Most Water](https://oj.leetcode.com/problems/container-with-most-water/)| [C++](./src/containerWithMostWater/containerWithMostWater.cpp)|2012/1/8|Medium| +|[Regular Expression Matching](https://oj.leetcode.com/problems/regular-expression-matching/)| [C++](./src/regularExpressionMatching/regularExpressionMatching.cpp)|2012/1/8|Hard| +|[Palindrome Number](https://oj.leetcode.com/problems/palindrome-number/)| [C++](./src/palindromeNumber/palindromeNumber.cpp)|2012/1/4|Easy| +|[String to Integer (atoi)](https://oj.leetcode.com/problems/string-to-integer-atoi/)| [C++](./src/stringToIntegerAtoi/stringToIntegerAtoi.cpp)|2011/12/26|Easy| +|[Reverse Integer](https://oj.leetcode.com/problems/reverse-integer/)| [C++](./src/reverseInteger/reverseInteger.cpp)|2011/12/25|Easy| +|[ZigZag Conversion](https://oj.leetcode.com/problems/zigzag-conversion/)| [C++](./src/zigZagConversion/zigZagConversion.cpp)|2011/12/5|Easy| +|[Longest Palindromic Substring](https://oj.leetcode.com/problems/longest-palindromic-substring/)| [C++](./src/longestPalindromicSubstring/longestPalindromicSubstring.cpp)|2011/11/11|Medium| +|[Add Two Numbers](https://oj.leetcode.com/problems/add-two-numbers/)| [C++](./src/addTwoNumbers/addTwoNumbers.cpp)|2011/11/1|Medium| +|[Longest Substring Without Repeating Characters](https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/)| [C++](./src/longestSubstringWithoutRepeatingCharacters/longestSubstringWithoutRepeatingCharacters.cpp)|2011/5/15|Medium| +|[Median of Two Sorted Arrays](https://oj.leetcode.com/problems/median-of-two-sorted-arrays/)| [C++](./src/medianOfTwoSortedArrays/medianOfTwoSortedArrays.cpp)|2011/3/27|Hard| +|[Two Sum](https://oj.leetcode.com/problems/two-sum/)| [C++](./src/twoSum/twoSum.cpp)|2011/3/13|Medium| diff --git a/src2/2Sum/2sum.py b/src2/2Sum/2sum.py new file mode 100644 index 000000000..35552b3b2 --- /dev/null +++ b/src2/2Sum/2sum.py @@ -0,0 +1,32 @@ +''' +Given an array of integers, find two numbers such that they add up to a specific target number. + +The function twoSum should return indices of the two numbers such that they add up to the target, + +where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. + +You may assume that each input would have exactly one solution. + +Input: numbers={2, 7, 11, 15}, target=9 +Output: index1=1, index2=2 +''' + + +class Solution: + # @return a tuple, (index1, index2) + def twoSum(self, num, target): + match = dict() + + for i in range(len(num)): + v = match.get(num[i], None) + if v != None: + return v + 1, i + 1 + + match[target - num[i]] = i + + return None + +if __name__ == '__main__': + s = Solution(); + print s.twoSum([3,2,4], 6) + \ No newline at end of file diff --git a/src2/3Sum/3Sum.py b/src2/3Sum/3Sum.py new file mode 100644 index 000000000..646b7e4d6 --- /dev/null +++ b/src2/3Sum/3Sum.py @@ -0,0 +1,65 @@ + +''' +Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? +Find all unique triplets in the array which gives the sum of zero. + +Note: +Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c) + +The solution set must not contain duplicate triplets. + For example, given array S = {-1 0 1 2 -1 -4}, + + A solution set is: + (-1, 0, 1) + (-1, -1, 2) + +''' +def binary_search(array, value): + low, high = 0, len(array) + while low < high: + mid = (low + high) / 2 + midval = array[mid] + if midval < value: + low = mid+1 + elif midval > value: + high = mid + else: + return mid + + return None + +class Solution: + # @return a list of lists of length 3, [[val1,val2,val3]]\ + def threeSum(self, num): + mapping = [] + num.sort() + numLen = len(num) + + # i step forward + for i in range(numLen): + if num[i] > 0 or (num[i] == num[i-1] and i != 0): + continue + + # j step backward + for j in reversed(range(i + 1, numLen)): + if j + 1 != numLen and num[j] == num[j+1]: + continue + + needed = 0-num[i]-num[j] + if needed < num[i]: + continue + if needed > num[j]: + break + + # binary_search is better for find middle value + if binary_search(num[i+1:j], needed) != None: + mapping.append([num[i], needed, num[j]]) + + return mapping + + +if __name__ == '__main__': + rst = Solution().threeSum([-2, -1, 0, 1, 2, 3]) + rst.sort() + print rst + print Solution().threeSum([]) diff --git a/src2/4Sum/4Sum.py b/src2/4Sum/4Sum.py new file mode 100644 index 000000000..be38f6737 --- /dev/null +++ b/src2/4Sum/4Sum.py @@ -0,0 +1,74 @@ +''' + +Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? +Find all unique quadruplets in the array which gives the sum of target. + +Note: +Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= c <= d) +The solution set must not contain duplicate quadruplets. + + For example, given array S = {1 0 -1 0 -2 2}, and target = 0. + + A solution set is: + (-1, 0, 0, 1) + (-2, -1, 1, 2) + (-2, 0, 0, 2) +''' + +def binary_search(array, value): + low, high = 0, len(array) + while low < high: + mid = (low + high) / 2 + midval = array[mid] + if midval < value: + low = mid+1 + elif midval > value: + high = mid + else: + return mid + + return None + +class Solution: + # @return a list of lists of length 4, [[val1,val2,val3,val4]] + def fourSum(self, num, target): + mapping = [] + num.sort() + itemNum = len(num) + for s in range(0, itemNum - 3): + if s != 0 and num[s] == num[s-1]: + continue + + for e in reversed(range(s + 3, itemNum)): + if e != itemNum-1 and num[e] == num[e+1]: + continue + + sumSE = num[s] + num[e] + neededBySE = target - sumSE + + if neededBySE < num[s+1]*2 or num[e-1]*2 < neededBySE: + continue + + for s2 in range(s + 1, e - 1): + if s2 != s+1 and num[s2] == num[s2-1]: + continue + + needed = neededBySE - num[s2] + if needed < num[s2 + 1]: + continue + if not binary_search(num[s2+1:e], needed) is None: + mapping.append([num[s], num[s2], needed, num[e]]) + return mapping + +if __name__ == '__main__': + #print Solution().fourSum([1, 0, -1, 0, -2, 2], 0) + #print Solution().fourSum([0,0], 0) + print Solution().fourSum([-1,2,2,-5,0,-1,4], 3) + a = "123455" + if a afs + sadfasdf + + + + + diff --git a/src2/AddTwoNumbers/add_two_numbers.py b/src2/AddTwoNumbers/add_two_numbers.py new file mode 100644 index 000000000..c8e9d11ce --- /dev/null +++ b/src2/AddTwoNumbers/add_two_numbers.py @@ -0,0 +1,112 @@ +''' +You are given two linked lists representing two non-negative numbers. +The digits are stored in reverse order and each of their nodes contain a single digit. +Add the two numbers and return it as a linked list. + +Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) +Output: 7 -> 0 -> 8 +342 + 465 = 807 +''' + +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None +# optimize cause too much code. + +class Solution: + + # @return carry, result + def splitSum(self, s): + if s >= 10: + return 1, s-10 + else: + return 0, s + + # @return new node + def addValue(self, node, sum): + node.next = ListNode(sum) + return node.next + + # @return a ListNode + def addTwoNumbers(self, l1, l2): + if l1 == None and l2 == None: + return None + + headValue = 0 + if l1 != None: + headValue += l1.val + l1 = l1.next + + if l2 != None: + headValue += l2.val + l2 = l2.next + + carry, headValue = self.splitSum(headValue) + result = head = ListNode(headValue) + + while l1 != None and l2 != None: + carry, sum = self.splitSum(l1.val + l2.val + carry) + result = self.addValue(result, sum) + + l1 = l1.next + l2 = l2.next + + while l1 != None: + carry, sum = self.splitSum(l1.val + carry) + result = self.addValue(result, sum) + l1 = l1.next + + while l2 != None: + carry, sum = self.splitSum(l2.val + carry) + result = self.addValue(result, sum) + l2 = l2.next + + if carry == 1: + result = self.addValue(result, 1) + return head + + def makeList(self, src): + if src == None: + return None + + p = head = ListNode(src[0]) + for i in range(1, len(src)): + p = self.addValue(p, src[i]) + return head + +makeList = Solution().makeList + +def show(l): + p = l + while p != None: + print p.val + p = p.next + +def list2Array(l): + r = list() + while l != None: + r.append(l.val) + l = l.next + return r + +def test(l1, l2, expect): + result = Solution().addTwoNumbers(makeList(l1), makeList(l2)) + result = list2Array(result) + if expect != result: + print "l1:", l1 + print "l2:", l2 + print "expect:", expect + print "result:", result + +if __name__ == '__main__': + test([2, 4, 3], [5, 6, 4], [7, 0, 8]) + test([2, 4, 3], [5, 6, 4, 1], [7, 0, 8, 1]) + test([2, 4, 3, 1], [5, 6, 4], [7, 0, 8, 1]) + diff --git a/src2/BinaryTreeRightSideView/binary_tree_right_side_view.py b/src2/BinaryTreeRightSideView/binary_tree_right_side_view.py new file mode 100644 index 000000000..210515113 --- /dev/null +++ b/src2/BinaryTreeRightSideView/binary_tree_right_side_view.py @@ -0,0 +1,49 @@ +import sys +sys.path.append('../../test_framework') +#from test_framework.binary_tree import * +from test_framework import * + +# Definition for a binary tree node +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + # @param root, a tree node + # @return a list of integers + def rightSideView(self, root): + stack = [] + p = root + result = [] + currentLevel = 0 + + while p != None: + # p is a most right node never traversed. + if currentLevel == len(result): + result.append(p.val) + + if p.right != None: + stack.append(p) + p = p.right + currentLevel += 1 + elif p.left != None: + stack.append(p) + p = p.left + currentLevel += 1 + else: + while stack + parent = stack[-1] + while p == parent.left: + p = parent + currentLevel -= 1 + stack.pop() + parent = stack[-1] + p = parent.left + return result + + +if __name__ == '__main__': + root = binary_tree.BinaryTree().build([1]) + Solution().rightSideView(root) \ No newline at end of file diff --git a/src2/CountPrimes/count_primes.js b/src2/CountPrimes/count_primes.js new file mode 100644 index 000000000..efa35aba0 --- /dev/null +++ b/src2/CountPrimes/count_primes.js @@ -0,0 +1,35 @@ +"use strict" +/** + * @param {number} n + * @return {number} + */ +function show(n){ + console.log(n); +} + +var countPrimes = function(n) { + var scanned = new Int8Array(n); + for (var i = 2; i < n; i++){ + if (!scanned[i]){ + for (var j = i * i; j < n; j+=i){ + scanned[j] = true; + } + } + } + show(scanned); + + var count = 0; + for (var k = 2; k < n; i++){ + if (!scanned[k]){ + count++; + } + } + return count; +}; + + +show(countPrimes(1)); +show(countPrimes(3)); +show(countPrimes(10)); +// show(countPrimes(25)); +show(countPrimes(1000)); \ No newline at end of file diff --git a/src2/CountPrimes/count_primes.py b/src2/CountPrimes/count_primes.py new file mode 100644 index 000000000..e2b6af81b --- /dev/null +++ b/src2/CountPrimes/count_primes.py @@ -0,0 +1,14 @@ +class Solution: + # @param {integer} n + # @return {integer} + def countPrimes(self, n): + scanned = [True] * (max(n+1, 2)) + scanned[0] = scanned[1] = False + for i in range(2, n+1): + if scanned[i]: + for j in range(i*i, n+1, i): + scanned[j] = False + return scanned.count(True) + +if __name__ == '__main__': + print Solution().countPrimes(10) \ No newline at end of file diff --git a/src2/FlattenNestedListIterator/flatten_nested_list_iterator.py b/src2/FlattenNestedListIterator/flatten_nested_list_iterator.py new file mode 100644 index 000000000..636e955de --- /dev/null +++ b/src2/FlattenNestedListIterator/flatten_nested_list_iterator.py @@ -0,0 +1,49 @@ +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger(object): +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ + +class NestedIterator(object): + + def __init__(self, nestedList): + """ + Initialize your data structure here. + :type nestedList: List[NestedInteger] + """ + + + def next(self): + """ + :rtype: int + """ + + + def hasNext(self): + """ + :rtype: bool + """ + + +# Your NestedIterator object will be instantiated and called as such: +# i, v = NestedIterator(nestedList), [] +# while i.hasNext(): v.append(i.next()) \ No newline at end of file diff --git a/src2/HappyNumber/happy_number.py b/src2/HappyNumber/happy_number.py new file mode 100644 index 000000000..6915fe3a5 --- /dev/null +++ b/src2/HappyNumber/happy_number.py @@ -0,0 +1,18 @@ +class Solution: + # @param {integer} n + # @return {boolean} + def isHappy(self, n): + loop = set([n]) + while n != 1: + m = str(n) + temp = reduce(lambda x,y: x + y, map(lambda x: int(x)*int(x), m)) + if (temp in loop): + return False + else: + loop.add(temp) + n = temp + return True + +if __name__ == '__main__': + print Solution().isHappy(2); + # print reduce(lambda x,y: int(x)*int(x) + int(y)*int(y), "82") \ No newline at end of file diff --git a/src2/MediaOfTwoSortedArrays/MediaOfTwoSortedArrayst.py b/src2/MediaOfTwoSortedArrays/MediaOfTwoSortedArrayst.py new file mode 100644 index 000000000..8d8e71e0f --- /dev/null +++ b/src2/MediaOfTwoSortedArrays/MediaOfTwoSortedArrayst.py @@ -0,0 +1,80 @@ +''' +There are two sorted arrays A and B of size m and n respectively. + +Find the median of the two sorted arrays. + +The overall run time complexity should be O(log (m+n)). +''' + +class Solution: + # get media of A --> ma + # get count of number in B that smaller than ma + def getNumBiggerThanValue(self, Array, Value): + # lower bounder is better + for i in range(len(Array)): + if Array[i] > Value: + return i + 1 + return len(Array) + + # return iA, iB + def moveFoward(self, A, B, iA, iB): + # min of A[iA + 1], B[iB] + if iB == len(B): + return iA + 1, iB + elif iA == len(A): + return iB + 1, iA + else + + # @return a float + def findMedianSortedArrays(self, A, B): + lenA = len(A) + lenB = len(B) + mid = (lenA + lenB) / 2 + if lenA >= lenB: + iA = len(A) / 2 + iB = self.getNumBiggerThanValue(B, A[iA]) + else: + iB = len(B) / 2 + iA = self.getNumBiggerThanValue(A, B[iB]) + A.append(0x8ffffffff) + B.append(0x8ffffffff) + + while True: + ## step + left = iA + iB + #print mid, left, iA, iB, ".." + if left == mid: + return min(A[iA], B[iB]) + elif left < mid: + # step forward + if A[iA - 1] > B[iB - 1]: + iB+=1 + else: + iA+=1 + elif left > mid: + # step backward + if A[iA] > B[iB]: + iA-=1 + else: + iB-=1 + #print "A:%d, B:%d" %(A[iA], B[iB]) + + +if __name__ == '__main__': + slu = Solution() + print slu.findMedianSortedArrays([1], [2]) + print slu.findMedianSortedArrays([1, 12, 15, 26, 38], [2, 13, 17, 30, 45, 50]) + print slu.findMedianSortedArrays([1, 12, 15, 26, 38], [2, 13, 17, 30, 45]) + print slu.findMedianSortedArrays([1, 2, 5, 6, 8], [13, 17, 30, 45, 50]) + print slu.findMedianSortedArrays([1, 2, 5, 6, 8, 9, 10], [13, 17, 30, 45, 50]) + print slu.findMedianSortedArrays([1, 2, 5, 6, 8, 9], [13, 17, 30, 45, 50]) + print slu.findMedianSortedArrays([1, 2, 5, 6, 8], [11, 13, 17, 30, 45, 50]) + print slu.findMedianSortedArrays([1], [2,3,4]) + ## [1,2,3] --> 2 + ## [1,2,3,4] --> 3 + ## [1,2,4,5,5,8] ==> 5 + ## [1,2,4,5,5,6,8] ==> 5 + + + + diff --git a/src2/MinStack/MinStack.py b/src2/MinStack/MinStack.py new file mode 100644 index 000000000..f410eaf9a --- /dev/null +++ b/src2/MinStack/MinStack.py @@ -0,0 +1,39 @@ +''' +Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. + +push(x) -- Push element x onto stack. +pop() -- Removes the element on top of the stack. +top() -- Get the top element. +getMin() -- Retrieve the minimum element in the stack. +''' +class MinStack: + # @param x, an integer + # @return an integer + def __init__(self): + self.m_nums = list() + self.m_minValue = 0x8fffffff + self.m_minIndex = 0 + + def push(self, x): + self.m_nums.append(x) + if self.m_minValue > x: + self.m_minValue, self.m_minIndex = x, len(self.m_nums) + + # @return nothing + def pop(self): + if self.m_minIndex == len(self.m_nums): + self.m_minValue = min(self.m_nums) + self.m_minIndex = self.m_nums.index(self.m_minValue) + + self.m_nums.pop() + + # @return an integer + def top(self): + if len(self.m_nums) == 0: + return None + return self.m_nums[0] + + # @return an integer + def getMin(self): + return self.m_minValue + #return min(self.m_nums) \ No newline at end of file diff --git a/src2/NumberOf1Bits/number_of_1_bits.py b/src2/NumberOf1Bits/number_of_1_bits.py new file mode 100644 index 000000000..b82694238 --- /dev/null +++ b/src2/NumberOf1Bits/number_of_1_bits.py @@ -0,0 +1,21 @@ +''' +Write a function that takes an unsigned integer and + +returns the number of '1' bits it has (also known as the Hamming weight). + +For example, the 32-bit integer '11' has binary representation + +00000000000000000000000000001011, so the function should return 3. +''' + +class Solution: + # @param n, an integer + # @return an integer + def hammingWeight(self, n): + p = 0 + for i in range(32): + p += (n >> i) & 1 + return p + +if __name__ == '__main__': + print Solution().hammingWeight(11) \ No newline at end of file diff --git a/src2/NumberOf1Bits/number_of_1_bits.rb b/src2/NumberOf1Bits/number_of_1_bits.rb new file mode 100644 index 000000000..6c0b25e36 --- /dev/null +++ b/src2/NumberOf1Bits/number_of_1_bits.rb @@ -0,0 +1,16 @@ +" +Write a function that takes an unsigned integer and + +returns the number of ’1' bits it has (also known as the Hamming weight). + +For example, the 32-bit integer ’11' has binary representation + +00000000000000000000000000001011, so the function should return 3. + +" + +# @param {Integer} n, a positive integer +# @return {Integer} +def hamming_weight(n) + [0..32].each x | puts(x) +end \ No newline at end of file diff --git a/src2/NumberOfIsland/number_of_island.py b/src2/NumberOfIsland/number_of_island.py new file mode 100644 index 000000000..e457242e7 --- /dev/null +++ b/src2/NumberOfIsland/number_of_island.py @@ -0,0 +1,34 @@ +class Solution: + + def traverseIsland(self, grid, col, line): + if (line < 0 or self.lineNum <= line or col < 0 or self.colNum <= col or grid[line][col] == '0'): + return + + grid[line][col] = '0' + self.traverseIsland(grid, col, line + 1) + self.traverseIsland(grid, col, line - 1) + self.traverseIsland(grid, col + 1, line) + self.traverseIsland(grid, col - 1, line) + + # @param grid, a list of list of characters + # @return an integer + def numIslands(self, grid): + islandNum = 0 + self.lineNum = len(grid) + if (self.lineNum == 0): + return 0 + self.colNum = len(grid[0]) + + for j in range(self.lineNum): + grid[j] = list(grid[j]) + + for j in range(self.lineNum): + line = grid[j] + for i in range(self.colNum): + if (line[i] == '1'): + islandNum += 1 + self.traverseIsland(grid, i, j) + return islandNum + +if __name__ == '__main__': + print Solution().numIslands(["1011"]) \ No newline at end of file diff --git a/src2/RemoveLinkedListElements/remove_linked_list_elements.py b/src2/RemoveLinkedListElements/remove_linked_list_elements.py new file mode 100644 index 000000000..406b067d9 --- /dev/null +++ b/src2/RemoveLinkedListElements/remove_linked_list_elements.py @@ -0,0 +1,33 @@ +import sys +sys.path.append('../../test_framework') +from test_framework import * + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param {ListNode} head + # @param {integer} val + # @return {ListNode} + def removeElements(self, head, val): + p = head; + while p != None: + pNext = p.next; + while pNext != None and pNext.val == val: + pNext = pNext.next + p.next = pNext + p = pNext + if head.val == val: + head = head.next + return head; + + +if __name__ == '__main__': + # head = makeList([1,2,3,4]) + # Solution().removeElements(head, 3).show() + + head = makeList([3,3,1]) + Solution().removeElements(head, 3).show() diff --git a/src2/ReverseInteger/ReverseInteger.py b/src2/ReverseInteger/ReverseInteger.py new file mode 100644 index 000000000..5df5ef05f --- /dev/null +++ b/src2/ReverseInteger/ReverseInteger.py @@ -0,0 +1,24 @@ +class Solution: + # @return an integer + def reverse(self, x): + strX = str(x) + #strX = list(strX) + prefix = '' + if strX[0] == '-': + strX = strX[1:] + prefix = '-' + + strX = list(strX) + strX.reverse() + strX = prefix + ''.join(strX) + x = int(strX) + if x > 2147483647: + return 0 + if x < -2147483648: + return 0 + return x + + +if __name__ == '__main__': + print Solution().reverse(2147483647) + print Solution().reverse(0) \ No newline at end of file diff --git a/src2/SortList/sort_list.py b/src2/SortList/sort_list.py new file mode 100644 index 000000000..15ea277e3 --- /dev/null +++ b/src2/SortList/sort_list.py @@ -0,0 +1,46 @@ +''' +Sort a linked list in O(n log n) time using constant space complexity. +''' + +import sys +sys.path.append('../../test_framework') +from test_framework import * + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param head, a ListNode + # @return a ListNode + def quickSortList(self, head): + middle = head + l = r = None + + p = head.next + lp = rp = middle + + while p != None: + pNext = p.next + if p.val >= middle.val: + p.next = lp + lp = p + else: + rp.next = p + rp = p + p = pNext + + rp.next = None + return lp + + def sortList(self, head): + # p = head + head = self.quickSortList(head) + head.show() + +if __name__ == '__main__': + head = makeList([5, 4, 5, 3, 7]) + # head.show() + Solution().sortList(head) \ No newline at end of file diff --git a/src2/WordBreak/word_break.py b/src2/WordBreak/word_break.py new file mode 100644 index 000000000..06fd33ca0 --- /dev/null +++ b/src2/WordBreak/word_break.py @@ -0,0 +1,47 @@ +''' +Given a string s and a dictionary of words dict, +determine if s can be segmented into a space-separated sequence of one or more dictionary words. + +For example, given +s = "leetcode", +dict = ["leet", "code"]. + +Return true because "leetcode" can be segmented as "leet code". +''' + +class Solution: + # @param s, a string + # @param dict, a set of string + # @return a boolean + def wordBreak_old(self, s, dict): + if s in dict: + return True + print "----------------" + for i in range(1, len(s)): + print s[:i], ":|:", s[i:] + if self.wordBreak(s[:i], dict) and self.wordBreak(s[i:], dict): + return True + return False + + def wordBreak(self, s, dict): + sLen = len(s) + charsInDict = [False] * (sLen) + + for i in range(0, sLen): + charsInDict[i] = s[:i+1] in dict + if charsInDict[i] is True: + continue + + for j in range(0, i): + charsInDict[i] = charsInDict[j] is True and s[j+1:i+1] in dict + return charsInDict[sLen-1] + +if __name__ == '__main__': + print Solution().wordBreak("leetcode", dict = ["leet", "code"]) + print Solution().wordBreak("goalspecial", dict = ["go","goal","goals","special"]) + print Solution().wordBreak("bccdbacdbdacddabbaaaadababadad", \ + ["cbc","bcda","adb","ddca","bad","bbb","dad","dac","ba","aa","bd",\ + "abab","bb","dbda","cb","caccc","d","dd","aadb","cc","b","bcc","bcd",\ + "cd","cbca","bbd","ddd","dabb","ab","acd","a","bbcc","cdcbd","cada",\ + "dbca","ac","abacd","cba","cdb","dbac","aada","cdcda","cdc","dbc","dbcb",\ + "bdb","ddbdd","cadaa","ddbc","babb"]) \ No newline at end of file diff --git a/test_framework/__init__.py b/test_framework/__init__.py new file mode 100644 index 000000000..1fae5c3ef --- /dev/null +++ b/test_framework/__init__.py @@ -0,0 +1 @@ +__all__ = ["binary_tree", "single_list"] diff --git a/test_framework/binary_tree.py b/test_framework/binary_tree.py new file mode 100644 index 000000000..cde64294d --- /dev/null +++ b/test_framework/binary_tree.py @@ -0,0 +1,50 @@ + +class BinaryTree: + def __init__(self, val = None): + self.val = val + self.left = None + self.right = None + + def setChild(self, leftValue, rightValue): + if (leftValue != None): + self.left = BinaryTree(leftValue) + if (rightValue != None): + self.right = BinaryTree(rightValue) + + def build(self, data): + if len(data) == 0: + return None + root = BinaryTree(data[0]) + openNode = [root] + for i in range(1, len(data), 2): + node = openNode.pop() + if i + 1 == len(data): + node.setChild(data[i], None) + else: + node.setChild(data[i], data[i+1]) + openNode.append([node.left, node.right]) + return root + + def show(self): + layer = [self] + p = self + level = 0 + while len(layer) != 0: + values = [] + nextLayer = [] + for node in layer: + if node == None: + values.append("#") + else: + values.append(node.val) + nextLayer.append(node.left) + nextLayer.append(node.right) + + print "level: %d, data:" % (level), + print values + layer = nextLayer + level += 1 + +if __name__ == '__main__': + root = BinaryTree().build([1,2,3]) + root.show() diff --git a/test_framework/single_list.py b/test_framework/single_list.py new file mode 100644 index 000000000..20fa61cb9 --- /dev/null +++ b/test_framework/single_list.py @@ -0,0 +1,42 @@ + +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + # @return next node + def addNext(self, sum): + self.next = ListNode(sum) + return self.next + + # @param [in] list + def show(self): + p = self + while p != None: + print p.val + p = p.next + + def toArray(self): + node = self + r = list() + while node != None: + r.append(node.val) + node = node.next + return r + +# @param [in] list +# @return header ListNode +def makeList(array): + if array == None: + return None + + p = head = ListNode(array[0]) + for i in range(1, len(array)): + p = p.addNext(array[i]) + return head + +def test(): + print "this is the test of ListNode." + +if __name__ == '__main__': + test() \ No newline at end of file