diff --git a/.DS_Store b/.DS_Store index f6ffae7..064b9a2 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/.gitignore b/.gitignore index a7a48f7..4201a9b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ /local.properties /app/app.iml build +out/ diff --git a/Leetcode-Java.iml b/Leetcode-Java.iml deleted file mode 100644 index 943250f..0000000 --- a/Leetcode-Java.iml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ProFile b/ProFile deleted file mode 100644 index e69de29..0000000 diff --git a/README.md b/README.md index a0c2910..065216c 100644 --- a/README.md +++ b/README.md @@ -16,364 +16,395 @@ - [Facebook面试总结](https://github.com/dingjikerbo/leetcode/blob/master/doc/Facebook.md) - [Bitset技巧](https://github.com/dingjikerbo/leetcode/blob/master/doc/BitSet.md) - [Map新接口](https://github.com/dingjikerbo/leetcode/blob/master/doc/Map.md) + - [其它题目](extras.md)

## **三、所有题目列表** -|#|Title|Solution|Score|Backup| -|---|----| ----- |----|---------| -|1|[Two Sum](https://leetcode.com/problems/two-sum/)|[Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TwoSum.java)|100| -|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/AddTwoNumber.java)|80| -|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestSubstringWithoutRepeatingCharacters.java)||这个系列的所有题都要多做几遍| -|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MedianOfTwoSortedArrays.java)|70|这题很经典,多做几遍| -|5|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestPalindromicSubstring.java)|85|这题对比动态规划和最优算法| -|6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ZigZagConversion.java)|| -|7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseInteger.java)|95| -|8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/String2Integer.java)|90|很考代码能力,容易错| -|9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromeNumber.java)|| -|10|[Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RegularExpressionMatching.java)|60|这题很经典,多做几遍,和#44一起| -|11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ContainerWithMostWater.java)|| -|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/IntegerToRoman.java)|| -|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RomanToInteger.java)|| -|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestCommonPrefix.java)|| -|15|[3Sum](https://leetcode.com/problems/3sum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ThreeSum.java)|70| -|16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ThreeSumClosest.java)|| -|17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LetterCombinationOfPhoneNumber.java)|85|| -|18|[4Sum](https://leetcode.com/problems/4sum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FourSum.java)|| -|19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveNthNodeFromEndOfList.java)|| -|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidParentheses.java)|100| -|21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MergeTwoSortedList.java)|90| -|22|[Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GenerateParentheses.java)|80|这题看两遍| -|23|[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MergeKSortedList.java)|70| -|24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SwapNodesInPairs.java)|| -|25|[Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseNodesInKGroup.java)|80| -|26|[Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArray.java)|80| -|27|[Remove Element](https://leetcode.com/problems/remove-element/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveElement.java)|| -|28|[ Implement strStr()](https://leetcode.com/problems/implement-strstr/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/StrStr.java)|70| -|29|[Divide Two Integers](https://leetcode.com/problems/divide-two-integers/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/DivideTwoIntegers.java)|| -|30|[Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SubstringWithConcatenationOfAllWords.java)|| -|31|[Next Permutation](https://leetcode.com/problems/next-permutation/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NextPermutation.java)|| -|32|[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestValidParentheses.java)|| -|33|[Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArray.java)|80| -|34|[Search for a Range](https://leetcode.com/problems/search-for-a-range/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SearchForARange.java)|| -|35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SearchInsertPosition.java)|| -|36|[Valid Sudoku](https://leetcode.com/problems/valid-sudoku/#/description)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidSudoku.java)|80| -|37|[Sudoku Solver](https://leetcode.com/problems/sudoku-solver/#/description)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SudokuSolver.java)|70|这道题是典型的back tracking,多做几遍| -|38|[Count and Say](https://leetcode.com/problems/count-and-say/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CountAndSay.java)|80| -|39|[Combination Sum](https://leetcode.com/problems/combination-sum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CombinationSum.java)|70|排列组合系列的题要多做几遍| -|40|[Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CombinationSumII.java)|70| -|41|[First Missing Positive](https://leetcode.com/problems/first-missing-positive/#/description)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FirstMissingPositive.java)|| -|42|[Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TrappingRainWater.java)|95| -|43|[Multiply Strings](https://leetcode.com/problems/multiply-strings/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MultiplyStrings.java)|80| -|44|[Wildcard Matching](https://leetcode.com/problems/wildcard-matching/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WildcardMatching.java)|60|和#10多做几遍| -|45|[Jump Game II](https://leetcode.com/problems/jump-game-ii/#/description)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/JumpGameII.java)|| -|46|[Permutations](https://leetcode.com/problems/permutations/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Permutations.java)|| -|47|[Permutations II](https://leetcode.com/problems/permutations-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PermutationsII.java)|70|多做几遍| -|48|[Rotate Image](https://leetcode.com/problems/rotate-image/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RotateImage.java)|100| -|49|[Group Anagrams](https://leetcode.com/problems/anagrams/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GroupAnagrams.java)|95| -|50|[Pow(x, n)](https://leetcode.com/problems/powx-n/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Pow.java)|80| -|51|[N-Queens](https://leetcode.com/problems/n-queens/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NQueens.java)|| -|52|[N-Queens II](https://leetcode.com/problems/n-queens-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NQueensII.java)|| -|53|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximumSubarray.java)|95| -|54|[Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SpiralMatrix.java)|85|| -|55|[Jump Game](https://leetcode.com/problems/jump-game/#/description)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/JumpGame.java)|| -|56|[Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MergeIntervals.java)|70| -|57|[Insert Interval](https://leetcode.com/problems/insert-interval/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/InsertInterval.java)|75|这题要多做几遍| -|60|[Permutation Sequence](https://leetcode.com/problems/permutation-sequence/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PermutationSequence.java)|70|这题思路巧妙,多做两遍| -|61|[Rotate List](https://leetcode.com/problems/rotate-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RotateList.java)|90|| -|66|[Plus One](https://leetcode.com/problems/plus-one/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PlusOne.java)|100|这题多看一遍| -|67|[Add Binary](https://leetcode.com/problems/add-binary/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/AddBinary.java)|100| -|68|[Text Justification](https://leetcode.com/problems/text-justification/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TextJustification.java)|| -|69|[Sqrt(x)](https://leetcode.com/problems/sqrtx/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Sqrt.java)|85| -|71|[Simplify Path](https://leetcode.com/problems/simplify-path/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SimplifyPath.java)|80| -|72|[Edit Distance](https://leetcode.com/problems/edit-distance/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/EditDistance.java)|75| -|73|[Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/description/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SetMatrixZeroes.java)|90| -|74|[Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Search2DMatrix.java)|| -|75|[Sort Colors](https://leetcode.com/problems/sort-colors/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SortColors.java)|65|这题多做几遍,很有意思| -|76|[Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MinimumWindowSubstring.java)|50|这题以及类似的题一定要多做几遍,很经典,参见window| -|77|[Combinations](https://leetcode.com/problems/combinations)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Combinations.java)|| -|78|[Subsets](https://leetcode.com/problems/subsets/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Subsets.java)|85| -|79|[Word Search](https://leetcode.com/problems/word-search/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordSearch.java)|85| -|80|[Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArrayII.java)|100| -|81|[Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArrayII.java)|70| -|82|[Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedListII.java)|75| -|83|[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedList.java)|100| -|84|[Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LargestRectangleInHistogram.java)|70| -|85|[Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximalRectangle.java)|75| -|86|[Partition List](https://leetcode.com/problems/partition-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PartitionList.java)|90|| -|88|[Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MergeSortedArray.java)|100| -|90|[Subsets II](https://leetcode.com/problems/subsets-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SubsetsII.java)|80| -|91|[Decode Ways](https://leetcode.com/problems/decode-ways/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/DecodeWays.java)|75|这题多做几遍,包括#639| -|92|[Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseLinkedListII.java)|80|| -|93|[Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RestoreIPAddresses.java)|80|多看两遍| -|94|[Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeInorderTraversal.java)|100| -|95|[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/UniqueBinarySearchTreesII.java)|70|多做几遍,递归和DP| -|96|[Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/UniqueBinarySearchTrees.java)|80| -|98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidateBinarySearchTree.java)|85|注意溢出| -|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RecoverBinarySearchTree.java)|60|这题很容易错,要多做几遍| -|100|[Same Tree](https://leetcode.com/problems/same-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SameTree.java)|100| -|101|[Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SymmetricTree.java)|95| -|102|[Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversal.java)|85| -|103|[Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeZigzagLevelOrderTraversal.java)|80| -|104|[Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximumDepthOfBinaryTree.java)|100| -|105|[Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromPreorderInorderTraversal.java)|95| -|106|[Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromInorderAndPostorderTraversal.java)|90| -|107|[Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversalII.java)|100| -|108|[Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ConvertSortedArrayToBinarySearchTree.java)|100| -|109|[Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ConvertSortedListToBinarySearchTree.java)|90|| -|110|[Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BalancedBinaryTree.java)|80| -|111|[Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MinimumDepthOfBinaryTree.java)|80| -|112|[Path Sum](https://leetcode.com/problems/path-sum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PathSum.java)|85| -|113|[Path Sum II](https://leetcode.com/problems/path-sum-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PathSumII.java)|65|错了好几次,得多做几遍| -|114|[Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FlattenBinaryTreeToLinkedList.java)|80| -|116|[Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNode.java)|80| -|117|[Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNodeII.java)|80| -|118|[Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PascalsTriangle.java)|80|| -|119|[Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/description/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PascalTriangleII.java)|80|| -|121|[Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BestTimeBuySellStock.java)|100| -|122|[Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockII.java)|100| -|123|[Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIII.java)|75| -|124|[Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeMaximumPathSum.java)|60| -|125|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidPalindrome.java)|100| -|126|[Word Ladder II](https://leetcode.com/problems/word-ladder-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordLadderII.java)|| -|127|[Word Ladder](https://leetcode.com/problems/word-ladder/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordLadder.java)|70|此题非常经典,务必连同ii多做几遍,将双端BFS吃透| -|128|[Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestConsecutiveSequence.java)|60| -|129|[Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SumRootToLeafNumbers.java)|60|这题错了几次,多做几遍| -|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SurroundedRegions.java)|65| -|131|[Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromePartitioning.java)|| -|132|[Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromePartitioningII.java)|| -|133|[Clone Graph](https://leetcode.com/problems/clone-graph/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CloneGraph.java)|70|这题不难,多看两遍,BFS方法再做两遍| -|138|[Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CopyListWithRandomPointer.java)|95|有一个易错点| -|139|[Word Break](https://leetcode.com/problems/word-break/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordBreak.java)|80|多看两遍| -|140|[Word Break II](https://leetcode.com/problems/word-break-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordBreakII.java)|75|这题多做两遍,很典型| -|141|[Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LinkedListCycle.java)|75| -|142|[Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LinkedListCycleII.java)|90|| -|143|[Reorder List](https://leetcode.com/problems/reorder-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReorderList.java)|90|| -|144|[Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreePreorderTraversal.java)|85| -|145|[Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreePostorderTraversal.java)|80| -|146|[LRU Cache](https://leetcode.com/problems/lru-cache/)|[Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LRUCache.java)|95|好题目,多做几遍| -|147|[Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/InsertionSortList.java)|90|| -|148|[Sort List](https://leetcode.com/problems/sort-list)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SortList.java)|90|| -|149|[Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaxPointsOnALine.java)|60| -|150|[Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/EvaluateReversePolishNotation.java)|70|| -|151|[Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/description/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseWordsInAString.java)|70|这题虽然不难,但是也错了几次| -|152|[Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximumProductSubarray.java)|| -|153|[Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindMinimumInRotatedSortedArray.java)|| -|154|[Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindMinimumInRotatedSortedArrayII.java)|| -|155|[Min Stack](https://leetcode.com/problems/min-stack/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MinStack.java)|95| -|156|[Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeUpsideDown.java)|70|这道题挺有意思,多做几遍| -|157|[Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4.java)|80|这题多做几遍,结合#158| -|158|[Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4II.java)|70| -|159|[Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostTwoDistinctCharacters.java)|100|多看两遍| -|160|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/IntersectionOfTwoLinkedLists.java)|100| -|161|[One Edit Distance](https://leetcode.com/problems/one-edit-distance/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/OneEditDistance.java)|85|和#72做两遍| -|162|[Find Peak Element](https://leetcode.com/problems/find-peak-element/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindPeakElement.java)|90|| -|163|[Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MissingRanges.java)|65|多做几遍,太容易错了| -|164|[Maximum Gap](https://leetcode.com/problems/maximum-gap/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximumGap.java)|65| -|167|[Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TwoSumII.java)|100| -|168|[Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ExcelSheetColumnTitle.java)|| -|169|[Majority Element](https://leetcode.com/problems/majority-element/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MajorityElement.java)|100|| -|170|[Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TwoSumIII.java)|100|这道题再多做一遍| -|171|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ExcelSheetColumnNumber.java)|| -|172|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FactorialTrailingZeroes.java)|100| -|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BSTIterator.java)|70|多留意一下| -|179|[Largest Number](https://leetcode.com/problems/largest-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LargestNumber.java)|90| -|186|[Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/description/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseWordsInAStringII.java)|90|| -|188|[Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIV.java)|| -|189|[Rotate Array](https://leetcode.com/problems/rotate-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RotateArray.java)|100|| -|190|[Reverse Bits](https://leetcode.com/problems/reverse-bits/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseBits.java)|85| -|198|[House Robber](https://leetcode.com/problems/house-robber/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/HouseRobber.java)|80| -|199|[Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeRightSideView.java)|80| -|200|[Number of Islands](https://leetcode.com/problems/number-of-islands/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumberOfIslands.java)|85|这道题很经典,而且方法不止一种,每种方法都多做几遍,包括UF,#305| -|203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveLinkedListElements.java)|| -|204|[Count Primes](https://leetcode.com/problems/count-primes/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CountPrimes.java)|85| -|206|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseLinkedList.java)|90| -|207|[Course Schedule](https://leetcode.com/problems/course-schedule/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CourseSchedule.java)|100|典型的拓扑排序| -|208|[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Trie.java)|80|和#211多留意,trie很典型| -|209|[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MinimumSizeSubarraySum.java)|85| -|210|[Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CourseScheduleII.java)|95|| -|211|[Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordDictionary.java)|85| -|212|[Word Search II](https://leetcode.com/problems/word-search-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordSearchII.java)|| -|213|[House Robber II](https://leetcode.com/problems/house-robber-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/HouseRobberII.java)|80| -|214|[Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ShortestPalindrome.java)|| -|215|[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/KthLargestElementInArray.java)|65|这题很经典,三种解法都要了然于胸| -|216|[Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CombinationSumIII.java)|65| -|217|[Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ContainsDuplicate.java)|100| -|218|[The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TheSkylineProblem.java)|60|这题多做两遍| -|219|[Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ContainsDuplicateII.java)|95| -|220|[Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ContainsDuplicateIII.java)|65| -|221|[Maximal Square](https://leetcode.com/problems/maximal-square/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximalSquare.java)|80| -|222|[Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CountCompleteTreeNodes.java)|70|一般的做法会超时| -|223|[Rectangle Area](https://leetcode.com/problems/rectangle-area/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RectangleArea.java)|95| -|224|[Basic Calculator](https://leetcode.com/problems/basic-calculator/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BasicCalculator.java)|80|| -|225|[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MyStack.java)|90| -|226|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/InvertBinaryTree.java)|80| -|228|[Summary Ranges](https://leetcode.com/problems/summary-ranges/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SummaryRanges.java)|70|| -|229|[Majority Element II](https://leetcode.com/problems/majority-element-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MajorityElementII.java)|70|| -|230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/KthSmallestElementInBST.java)|85|注意Follow Up| -|232|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MyQueue.java)|95| -|233|[Number of Digit One](https://leetcode.com/problems/number-of-digit-one/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumberOfDigitOne.java)|| -|234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromeLinkedList.java)|75| -|235|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)|[Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinarySearchTree.java)|100| -|236|[Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinaryTree.java)|50|这题很经典,多做几遍,留意节点不在树中的情况| -|237|[Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/DeleteNodeInALinkedList.java)|100|| -|238|[Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ProductOfArrayExceptSelf.java)|85| -|239|[Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SlidingWindowMaximum.java)|75|这题非常经典,多做几遍,包括常规算法(优先队列,treemap)及优化算法双端队列| -|240|[Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Search2DMatrixII.java)|100| -|241|[Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/DifferenceWaysToAddParentheses.java)|| -|242|[Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidAnagram.java)|100| -|243|[Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ShortestWordDistance.java)|80| -|244|[Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ShortestWordDistanceII.java)|80|| -|245|[Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ShortestWordDistanceIII.java)|80|| -|246|[Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/StrobogrammaticNumber.java)|70|#247一个系列,多看两遍| -|247|[Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/StrobogrammaticNumberII.java)|70|多看两遍| -|249|[Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GroupShiftedStrings.java)|| -|250|[Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CountUnivalueSubtrees.java)|70|这题要多做几遍| -|251|[Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Vector2D.java)|100| -|252|[Meeting Rooms](https://leetcode.com/problems/meeting-rooms/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MeetingRooms.java)|100| -|253|[Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MeetingRoomsII.java)|90| -|254|[Factor Combinations](https://leetcode.com/problems/factor-combinations/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FactorCombinations.java)|80|| -|255|[Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/VerifyPreorderSequenceInBinarySearchTree.java)|85|很简单,粗心错了| -|256|[Paint House](https://leetcode.com/problems/paint-house/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PaintHouse.java)|95| -|257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreePaths.java)|80| -|259|[3Sum Smaller](https://leetcode.com/problems/3sum-smaller/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ThreeSumSmaller.java)|95|这题虽然简单,但是因为思维定式还是错了几次| -|261|[Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GraphValidTree.java)|70|这题多做几遍| -|263|[Ugly Number](https://leetcode.com/problems/ugly-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/UglyNumber.java)|85| -|264|[Ugly Number II](https://leetcode.com/problems/ugly-number-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/UglyNumberII.java)|70| -|265|[Paint House II](https://leetcode.com/problems/paint-house-ii)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PaintHouseII.java)|60| -|266|[Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromePermutation.java)|100| -|267|[Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromePermutationII.java)|80|典型,多看两遍| -|268|[Missing Number](https://leetcode.com/problems/missing-number)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MissingNumber.java)|100|| -|269|[Alien Dictionary](https://leetcode.com/problems/alien-dictionary/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/AlienDictionary.java)|70|这题要多做几遍| -|270|[Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValue.java)|90| -|271|[Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/EncodeAndDecodeStrings.java)|65|思路巧妙,多看几遍| -|272|[Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValueII.java)|60|这题非常值得多做几遍,几种写法都试试| -|273|[Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/IntegerToEnglishWords.java)|75|多做几遍,做到bug free| -|274|[H-Index](https://leetcode.com/problems/h-index/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/HIndex.java)|80| -|275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/HIndexII.java)|75| -|277|[Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindCelebrity.java)|100| -|278|[First Bad Version](https://leetcode.com/problems/first-bad-version/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FirstBadVersion.java)|100| -|279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PerfectSquares.java)|95| -|280|[Wiggle Sort](https://leetcode.com/problems/wiggle-sort/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WiggleSort.java)|80|思路巧妙,多看两遍| -|281|[Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ZigzagIterator.java)|85|多做三遍,考虑扩展到k的情况| -|282|[Expression Add Operators](https://leetcode.com/problems/expression-add-operators/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ExpressionAddOperators.java)|50| -|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MoveZeroes.java)|100| -|284|[Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PeekingIterator.java)|100| -|285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/InorderSuccessorInBST.java)|70|这道题有意思,要多做几遍| -|286|[Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WallsAndGates.java)|70|多看两遍| -|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindTheDuplicateNumber.java)|| -|288|[Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidWordAbbr.java)|70|这题不难,多做两遍,题目意思容易理解错| -|289|[Game of Life](https://leetcode.com/problems/game-of-life/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GameOfLife.java)|70|| -|293|[Flip Game](https://leetcode.com/problems/flip-game/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FlipGame.java)|90|| -|294|[Flip Game II](https://leetcode.com/problems/flip-game-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FlipGameII.java)|90|| -|295|[Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindMedianFromDataStream.java)|| -|297|[Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)|[Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/Codec.java)|80|好题目,多做做,递归的非递归的| -|298|[Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeLongestConsecutiveSequence.java)|70|多做三遍,尽可能简洁| -|300|[Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestIncreasingSubsequence.java)|| -|301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveInvalidParentheses.java)|70|比较难,多做几遍| -|302|[Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SmallestRectangleEnclosingBlackPixels.java)||| -|303|[Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumArray.java)|100| -|304|[Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumMatrix.java)|65| -|305|[Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumberOfIslandsII.java)|70|这题多做几遍,经典的UF| -|307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumArrayII.java)|70|和#303, #304, #308定要多做几遍,掌握BIT| -|308|[Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumMatrixII.java)|70| -|309|[Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockWithCoolDown.java)|| -|310|[Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MinimumHeightTrees.java)|60|这题多做几遍| -|311|[Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SparseMatrixMultiplication.java)|80| -|312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BurstBalloons.java)|60| -|313|[Super Ugly Number](https://leetcode.com/problems/super-ugly-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SuperUglyNumber.java)||| -|314|[Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryTreeVerticalOrderTraversal.java)|80| -|315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CountOfSmallerNumbersAfterSelf.java)|60| -|316|[Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RemoveDuplicateLetters.java)|70| -|317|[Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ShortestDistanceFromAllBuildings.java)|75|典型的bfs,多做两遍| -|319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BulbSwitcher.java)|90| -|320|[Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GeneralizedAbbreviation.java)|70|这题是典型的back tracking,多做几遍| -|323|[Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NumberOfConnectedComponents.java)|90|典型的图,多看两遍| -|324|[Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WiggleSortII.java)|60| -|325|[Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaximumSizeSubarraySumEqualsK.java)|75|这题思路有意思,多做几遍| -|328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/OddEvenLinkedList.java)|90| -|329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestIncreasingPathInAMatrix.java)|70|这题要多做几遍| -|332|[Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReconstructItinerary.java)||| -|333|[Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LargestBSTSubtree.java)|50|这道题虽然不难,但是折腾了很久,一定要多做| -|334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/IncreasingTripletSubsequence.java)|75| -|335|[Self Crossing](https://leetcode.com/problems/self-crossing/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SelfCrossing.java)|80| -|336|[Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PalindromePairs.java)|| -|337|[House Robber III](https://leetcode.com/problems/house-robber-iii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/HouseRobberIII.java)|70|建议再做两遍| -|339|[Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NestedListWeightSum.java)|| -|340|[Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostKDistinctCharacters.java)|80|和#159类似| -|341|[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NestedIterator.java)|75|这题有点意思,多做两遍| -|344|[Reverse String](https://leetcode.com/problems/reverse-string/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseString.java)|100|| -|345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseVowelsOfaString.java)|100|| -|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MovingAverage.java)|95| -|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TopKFrequentElements.java)|85| -|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/IntersectionOfTwoArrays.java)||| -|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/IntersectionOfTwoArraysII.java)||| -|351|[Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/AndroidUnlockPatterns.java)|70|这题多做几遍| -|357|[Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/CountNumberWithUniqueDigits.java)|| -|358|[Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RearrangeStringKDistanceApart.java)|| -|359|[Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LoggerRateLimiter.java)|100|这题如果不考虑空间消耗的话其实很简单| -|361|[Bomb Enemy](https://leetcode.com/problems/bomb-enemy/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BombEnemy.java)|65|这题多做几遍,开始没思路| -|364|[Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/NestedListWeightSumII.java)|| -|366|[Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindLeavesOfBinaryTree.java)|60|这道题刚开始还没思路| -|367|[Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidPerfectSquare.java)||| -|369|[Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PlusOneLinkedList.java)|100|| -|370|[Range Addition](https://leetcode.com/problems/range-addition/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RangeAddition.java)|80|| -|373|[Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindKPairsWithSmallestSums.java)||| -|374|[Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLower.java)|100| -|375|[Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLowerII.java)|60| -|377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/combinationSum4.java)|65| -|378|[Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/KthSmallestElementInASortedMatrix.java)||| -|380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RandomizedSet.java)|75|这道题很有意思,多做几遍| -|381|[Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RandomizedCollection.java)|| -|382|[Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LinkedListRandomNode.java)|| -|384|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ShuffleAnArray.java)|75| -|387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FirstUniqueCharacterInAString.java)|100| -|388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestAbsoluteFilePath.java)|65|其实不难,乍看没思路,多做几遍| -|391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PerfectRectangle.java)|70|这题很trick,多做两遍| -|393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/UTFValidation.java)|60|错了很多次,多做几遍| -|394|[Decode String](https://leetcode.com/problems/decode-string/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/DecodeString.java)|75|这题容易错,多做四遍| -|395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtLeastKRepeatingCharacters.java)|65| -|398|[Random Pick Index](https://leetcode.com/problems/random-pick-index/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RandomPickIndex.java)|80| -|399|[Evaluate Division](https://leetcode.com/problems/evaluate-division/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/EvaluateDivision.java)|60|这题多做几遍| -|401|[Binary Watch](https://leetcode.com/problems/binary-watch/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BinaryWatch.java)|| -|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SumOfLeftLeaves.java)|80| -|406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/QueueReconstructionByHeight.java)|60|这题开始没思路,多做几遍| -|407|[Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TrappingRainWaterII.java)|| -|408|[Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/validWordAbbreviation.java)|80|多做两遍| -|409|[Longest Palindrome](https://leetcode.com/problems/longest-palindrome/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestPalindrome.java)|| -|410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SplitArrayLargestSum.java)|| -|412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FizzBuzz.java)|100| -|413|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ThirdMaximumNumber.java)|80|| -|418|[Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SentenceScreenFitting.java)|65|这题思路巧妙,多做几遍,常规思路超时| -|422|[Valid Word Square](https://leetcode.com/problems/valid-word-square/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ValidWordSquare.java)|90| -|425|[Word Squares](https://leetcode.com/problems/word-squares/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/WordSquare.java)|70|这题很典型,多做几遍| -|436|[Find Right Interval](https://leetcode.com/problems/find-right-interval/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindRightInterval.java)||| -|437|[Path Sum III](https://leetcode.com/problems/path-sum-iii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/PathSumIII.java)|60|这道题错了很多遍,要重点关注| -|438|[Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindAllAnagramsInString.java)|75|这道题非常经典,最优解法需要多做几遍,保证once bug free| -|442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindAllDuplicatesInAnArray.java)|80|| -|445|[Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/discuss/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/AddTwoNumbersII.java)|80|| -|448|[Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindAllNumbersDisappearedInAnArray.java)|80|| -|449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SerializeAndDeserializeBST.java)|90|和#297一样| -|450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/DeleteNodeInBST.java)|60|这题非常经典,值得多做十遍| -|451|[Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SortCharactersByFrequency.java)||| -|459|[Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RepeatedSubstringPattern.java)||| -|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TotalHammingDistance.java)|| -|480|[Sliding Window Median](https://leetcode.com/problems/sliding-window-median/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SlidingWindowMedian.java)|70|| -|482|[License Key Formatting](https://leetcode.com/problems/license-key-formatting/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LicenseKeyFormatting.java)|90|| -|483|[Smallest Good Base](https://leetcode.com/problems/smallest-good-base/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SmallestGoodBase.java)||| -|485|[Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaxConsecutiveOnes.java)|100|| -|487|[Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MaxConsecutiveOnesII.java)|80|| -|501|[Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindModeInBinarySearchTree.java)|70|不难,容易错,多做两次| -|508|[Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum/submissions/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/MostFrequentSubtreeSum.java)|| -|513|[Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindBottomLeftTreeValue.java)|100|| -|515|[Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindLargestValueInEachTreeRow.java)|100|| -|524|[Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/LongestWordInDictionaryThroughDeleting.java)||| -|526|[Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/BeautifulArrangement.java)|80|| -|535|[Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/EncodeAndDecodeTinyURL.java)|100|| -|541|[Reverse String II](https://leetcode.com/problems/reverse-string-ii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseStringII.java)|100|| -|557|[Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/ReverseWordsInAStringIII.java)|100|| -|560|[Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/SubarraySumEqualsK.java)|70|| -|637|[Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/#/description)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/AverageOfLevelsInBinaryTree.java)|100|| -|652|[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/FindDuplicateSubtrees.java)|70|开始还没思路| -|653|[Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/TwoSumIV.java)|90|| -|684|[Redundant Connection](https://leetcode.com/problems/redundant-connection/)| [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/RedundantConnection.java)||| \ No newline at end of file +|#| Title |Solution|Score|Backup| +|---|-------------| ----- |----|---------| +|1|[Two Sum](https://leetcode.com/problems/two-sum/)|[Java](leetcode/solution/src/TwoSum.java)|100| +|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [Java](leetcode/solution/src/AddTwoNumber.java)|80| +|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [Java](leetcode/solution/src/LongestSubstringWithoutRepeatingCharacters.java)||这个系列的所有题都要多做几遍| +|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [Java](leetcode/solution/src/MedianOfTwoSortedArrays.java)|70|这题很经典,多做几遍| +|5|[Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [Java](leetcode/solution/src/LongestPalindromicSubstring.java)|85|这题对比动态规划和最优算法| +|6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)| [Java](leetcode/solution/src/ZigZagConversion.java)|| +|7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [Java](leetcode/solution/src/ReverseInteger.java)|95| +|8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)| [Java](leetcode/solution/src/String2Integer.java)|90|很考代码能力,容易错| +|9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)| [Java](leetcode/solution/src/PalindromeNumber.java)|| +|10|[Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/)| [Java](leetcode/solution/src/RegularExpressionMatching.java)|60|这题很经典,多做几遍,和#44一起| +|11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [Java](leetcode/solution/src/ContainerWithMostWater.java)|| +|12|[Integer to Roman](https://leetcode.com/problems/integer-to-roman/)| [Java](leetcode/solution/src/IntegerToRoman.java)|| +|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [Java](leetcode/solution/src/RomanToInteger.java)|| +|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)| [Java](leetcode/solution/src/LongestCommonPrefix.java)|| +|15|[3Sum](https://leetcode.com/problems/3sum/)| [Java](leetcode/solution/src/ThreeSum.java)|70| +|16|[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [Java](leetcode/solution/src/ThreeSumClosest.java)|| +|17|[Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Java](leetcode/solution/src/LetterCombinationOfPhoneNumber.java)|85|| +|18|[4Sum](https://leetcode.com/problems/4sum/)| [Java](leetcode/solution/src/FourSum.java)|| +|19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [Java](leetcode/solution/src/RemoveNthNodeFromEndOfList.java)|| +|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Java](leetcode/solution/src/ValidParentheses.java)|100| +|21|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Java](leetcode/solution/src/MergeTwoSortedList.java)|90| +|22|[Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Java](leetcode/solution/src/GenerateParentheses.java)|80|这题看两遍| +|23|[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)| [Java](leetcode/solution/src/MergeKSortedList.java)|70| +|24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Java](leetcode/solution/src/SwapNodesInPairs.java)|| +|25|[Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)| [Java](leetcode/solution/src/ReverseNodesInKGroup.java)|80| +|26|[Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Java](leetcode/solution/src/RemoveDuplicatesFromSortedArray.java)|80| +|27|[Remove Element](https://leetcode.com/problems/remove-element/)| [Java](leetcode/solution/src/RemoveElement.java)|| +|28|[ Implement strStr()](https://leetcode.com/problems/implement-strstr/)| [Java](leetcode/solution/src/StrStr.java)|70| +|29|[Divide Two Integers](https://leetcode.com/problems/divide-two-integers/)| [Java](leetcode/solution/src/DivideTwoIntegers.java)|| +|30|[Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/)| [Java](leetcode/solution/src/SubstringWithConcatenationOfAllWords.java)|| +|31|[Next Permutation](https://leetcode.com/problems/next-permutation/)| [Java](leetcode/solution/src/NextPermutation.java)|| +|32|[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [Java](leetcode/solution/src/LongestValidParentheses.java)|| +|33|[Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)| [Java](leetcode/solution/src/SearchInRotatedSortedArray.java)|80| +|34|[Search for a Range](https://leetcode.com/problems/search-for-a-range/)| [Java](leetcode/solution/src/SearchForARange.java)|| +|35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)| [Java](leetcode/solution/src/SearchInsertPosition.java)|| +|36|[Valid Sudoku](https://leetcode.com/problems/valid-sudoku/#/description)| [Java](leetcode/solution/src/ValidSudoku.java)|80| +|37|[Sudoku Solver](https://leetcode.com/problems/sudoku-solver/#/description)| [Java](leetcode/solution/src/SudokuSolver.java)|70|这道题是典型的back tracking,多做几遍| +|38|[Count and Say](https://leetcode.com/problems/count-and-say/)| [Java](leetcode/solution/src/CountAndSay.java)|80| +|39|[Combination Sum](https://leetcode.com/problems/combination-sum/)| [Java](leetcode/solution/src/CombinationSum.java)|70|排列组合系列的题要多做几遍| +|40|[Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Java](leetcode/solution/src/CombinationSumII.java)|70| +|41|[First Missing Positive](https://leetcode.com/problems/first-missing-positive/#/description)| [Java](leetcode/solution/src/FirstMissingPositive.java)|| +|42|[Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)| [Java](leetcode/solution/src/TrappingRainWater.java)|95| +|43|[Multiply Strings](https://leetcode.com/problems/multiply-strings/)| [Java](leetcode/solution/src/MultiplyStrings.java)|80| +|44|[Wildcard Matching](https://leetcode.com/problems/wildcard-matching/)| [Java](leetcode/solution/src/WildcardMatching.java)|60|和#10多做几遍| +|45|[Jump Game II](https://leetcode.com/problems/jump-game-ii/#/description)| [Java](leetcode/solution/src/JumpGameII.java)|| +|46|[Permutations](https://leetcode.com/problems/permutations/)| [Java](leetcode/solution/src/Permutations.java)|| +|47|[Permutations II](https://leetcode.com/problems/permutations-ii/)| [Java](leetcode/solution/src/PermutationsII.java)|70|多做几遍| +|48|[Rotate Image](https://leetcode.com/problems/rotate-image/)| [Java](leetcode/solution/src/RotateImage.java)|100| +|49|[Group Anagrams](https://leetcode.com/problems/anagrams/)| [Java](leetcode/solution/src/GroupAnagrams.java)|95| +|50|[Pow(x, n)](https://leetcode.com/problems/powx-n/)| [Java](leetcode/solution/src/Pow.java)|80| +|51|[N-Queens](https://leetcode.com/problems/n-queens/)| [Java](leetcode/solution/src/NQueens.java)|| +|52|[N-Queens II](https://leetcode.com/problems/n-queens-ii/)| [Java](leetcode/solution/src/NQueensII.java)|| +|53|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)| [Java](leetcode/solution/src/MaximumSubarray.java)|95| +|54|[Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)| [Java](leetcode/solution/src/SpiralMatrix.java)|85|| +|55|[Jump Game](https://leetcode.com/problems/jump-game/#/description)| [Java](leetcode/solution/src/JumpGame.java)|| +|56|[Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Java](leetcode/solution/src/MergeIntervals.java)|70| +|57|[Insert Interval](https://leetcode.com/problems/insert-interval/)| [Java](leetcode/solution/src/InsertInterval.java)|75|这题要多做几遍| +|60|[Permutation Sequence](https://leetcode.com/problems/permutation-sequence/)| [Java](leetcode/solution/src/PermutationSequence.java)|70|这题思路巧妙,多做两遍| +|61|[Rotate List](https://leetcode.com/problems/rotate-list/)| [Java](leetcode/solution/src/RotateList.java)|90|| +|66|[Plus One](https://leetcode.com/problems/plus-one/)| [Java](leetcode/solution/src/PlusOne.java)|100|这题多看一遍| +|67|[Add Binary](https://leetcode.com/problems/add-binary/)| [Java](leetcode/solution/src/AddBinary.java)|100| +|68|[Text Justification](https://leetcode.com/problems/text-justification/)| [Java](leetcode/solution/src/TextJustification.java)|| +|69|[Sqrt(x)](https://leetcode.com/problems/sqrtx/)| [Java](leetcode/solution/src/Sqrt.java)|85| +|71|[Simplify Path](https://leetcode.com/problems/simplify-path/)| [Java](leetcode/solution/src/SimplifyPath.java)|80| +|72|[Edit Distance](https://leetcode.com/problems/edit-distance/)| [Java](leetcode/solution/src/EditDistance.java)|75| +|73|[Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/description/)| [Java](leetcode/solution/src/SetMatrixZeroes.java)|90| +|74|[Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)| [Java](leetcode/solution/src/Search2DMatrix.java)|| +|75|[Sort Colors](https://leetcode.com/problems/sort-colors/)| [Java](leetcode/solution/src/SortColors.java)|65|这题多做几遍,很有意思| +|76|[Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)| [Java](leetcode/solution/src/MinimumWindowSubstring.java)|50|这题以及类似的题一定要多做几遍,很经典,参见window| +|77|[Combinations](https://leetcode.com/problems/combinations)| [Java](leetcode/solution/src/Combinations.java)|| +|78|[Subsets](https://leetcode.com/problems/subsets/)| [Java](leetcode/solution/src/Subsets.java)|85| +|79|[Word Search](https://leetcode.com/problems/word-search/)| [Java](leetcode/solution/src/WordSearch.java)|85| +|80|[Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| [Java](leetcode/solution/src/RemoveDuplicatesFromSortedArrayII.java)|100| +|81|[Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)| [Java](leetcode/solution/src/SearchInRotatedSortedArrayII.java)|70| +|82|[Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| [Java](leetcode/solution/src/RemoveDuplicatesFromSortedListII.java)|75| +|83|[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)| [Java](leetcode/solution/src/RemoveDuplicatesFromSortedList.java)|100| +|84|[Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)| [Java](leetcode/solution/src/LargestRectangleInHistogram.java)|70| +|85|[Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [Java](leetcode/solution/src/MaximalRectangle.java)|75| +|86|[Partition List](https://leetcode.com/problems/partition-list/)| [Java](leetcode/solution/src/PartitionList.java)|90|| +|88|[Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Java](leetcode/solution/src/MergeSortedArray.java)|100| +|90|[Subsets II](https://leetcode.com/problems/subsets-ii/)| [Java](leetcode/solution/src/SubsetsII.java)|80| +|91|[Decode Ways](https://leetcode.com/problems/decode-ways/)| [Java](leetcode/solution/src/DecodeWays.java)|75|这题多做几遍,包括#639| +|92|[Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/)| [Java](leetcode/solution/src/ReverseLinkedListII.java)|80|| +|93|[Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/)| [Java](leetcode/solution/src/RestoreIPAddresses.java)|80|多看两遍| +|94|[Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)| [Java](leetcode/solution/src/BinaryTreeInorderTraversal.java)|100| +|95|[Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)| [Java](leetcode/solution/src/UniqueBinarySearchTreesII.java)|70|多做几遍,递归和DP| +|96|[Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)| [Java](leetcode/solution/src/UniqueBinarySearchTrees.java)|80| +|98|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)| [Java](leetcode/solution/src/ValidateBinarySearchTree.java)|85|注意溢出| +|99|[Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/)| [Java](leetcode/solution/src/RecoverBinarySearchTree.java)|60|这题很容易错,要多做几遍| +|100|[Same Tree](https://leetcode.com/problems/same-tree/)| [Java](leetcode/solution/src/SameTree.java)|100| +|101|[Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [Java](leetcode/solution/src/SymmetricTree.java)|95| +|102|[Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [Java](leetcode/solution/src/BinaryTreeLevelOrderTraversal.java)|85| +|103|[Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Java](leetcode/solution/src/BinaryTreeZigzagLevelOrderTraversal.java)|80| +|104|[Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [Java](leetcode/solution/src/MaximumDepthOfBinaryTree.java)|100| +|105|[Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)| [Java](leetcode/solution/src/ConstructBinaryTreeFromPreorderInorderTraversal.java)|95| +|106|[Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)| [Java](leetcode/solution/src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java)|90| +|107|[Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Java](leetcode/solution/src/BinaryTreeLevelOrderTraversalII.java)|100| +|108|[Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)| [Java](leetcode/solution/src/ConvertSortedArrayToBinarySearchTree.java)|100| +|109|[Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)| [Java](leetcode/solution/src/ConvertSortedListToBinarySearchTree.java)|90|| +|110|[Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/)| [Java](leetcode/solution/src/BalancedBinaryTree.java)|80| +|111|[Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)| [Java](leetcode/solution/src/MinimumDepthOfBinaryTree.java)|80| +|112|[Path Sum](https://leetcode.com/problems/path-sum/)| [Java](leetcode/solution/src/PathSum.java)|85| +|113|[Path Sum II](https://leetcode.com/problems/path-sum-ii/)| [Java](leetcode/solution/src/PathSumII.java)|65|错了好几次,得多做几遍| +|114|[Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)| [Java](leetcode/solution/src/FlattenBinaryTreeToLinkedList.java)|80| +|116|[Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)| [Java](leetcode/solution/src/PopulatingNextRightPointersInEachNode.java)|80| +|117|[Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| [Java](leetcode/solution/src/PopulatingNextRightPointersInEachNodeII.java)|80| +|118|[Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Java](leetcode/solution/src/PascalsTriangle.java)|80|| +|119|[Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/description/)| [Java](leetcode/solution/src/PascalTriangleII.java)|80|| +|121|[Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Java](leetcode/solution/src/BestTimeBuySellStock.java)|100| +|122|[Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Java](leetcode/solution/src/BestTimeBuySellStockII.java)|100| +|123|[Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| [Java](leetcode/solution/src/BestTimeBuySellStockIII.java)|75| +|124|[Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| [Java](leetcode/solution/src/BinaryTreeMaximumPathSum.java)|60| +|125|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)| [Java](leetcode/solution/src/ValidPalindrome.java)|100| +|126|[Word Ladder II](https://leetcode.com/problems/word-ladder-ii/)| [Java](leetcode/solution/src/WordLadderII.java)|| +|127|[Word Ladder](https://leetcode.com/problems/word-ladder/)| [Java](leetcode/solution/src/WordLadder.java)|70|此题非常经典,务必连同ii多做几遍,将双端BFS吃透| +|128|[Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)| [Java](leetcode/solution/src/LongestConsecutiveSequence.java)|60| +|129|[Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)| [Java](leetcode/solution/src/SumRootToLeafNumbers.java)|100|| +|130|[Surrounded Regions](https://leetcode.com/problems/surrounded-regions/)| [Java](leetcode/solution/src/SurroundedRegions.java)|65| +|131|[Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/)| [Java](leetcode/solution/src/PalindromePartitioning.java)|| +|132|[Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/)| [Java](leetcode/solution/src/PalindromePartitioningII.java)|| +|133|[Clone Graph](https://leetcode.com/problems/clone-graph/)| [Java](leetcode/solution/src/CloneGraph.java)|70|这题不难,多看两遍,BFS方法再做两遍| +|135|[Candy](https://leetcode.com/problems/candy/)|[Java](leetcode/solution/src/Candy.java)|80|| +|138|[Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/)| [Java](leetcode/solution/src/CopyListWithRandomPointer.java)|95|有一个易错点| +|139|[Word Break](https://leetcode.com/problems/word-break/)| [Java](leetcode/solution/src/WordBreak.java)|80|多看两遍| +|140|[Word Break II](https://leetcode.com/problems/word-break-ii/)| [Java](leetcode/solution/src/WordBreakII.java)|75|这题多做两遍,很典型| +|141|[Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)| [Java](leetcode/solution/src/LinkedListCycle.java)|75| +|142|[Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)| [Java](leetcode/solution/src/LinkedListCycleII.java)|90|| +|143|[Reorder List](https://leetcode.com/problems/reorder-list/)| [Java](leetcode/solution/src/ReorderList.java)|90|| +|144|[Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)| [Java](leetcode/solution/src/BinaryTreePreorderTraversal.java)|85| +|145|[Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)| [Java](leetcode/solution/src/BinaryTreePostorderTraversal.java)|80| +|146|[LRU Cache](https://leetcode.com/problems/lru-cache/)|[Java](leetcode/solution/src/LRUCache.java)|95|好题目,多做几遍| +|147|[Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)| [Java](leetcode/solution/src/InsertionSortList.java)|90|| +|148|[Sort List](https://leetcode.com/problems/sort-list)| [Java](leetcode/solution/src/SortList.java)|90|| +|149|[Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/)| [Java](leetcode/solution/src/MaxPointsOnALine.java)|60| +|150|[Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [Java](leetcode/solution/src/EvaluateReversePolishNotation.java)|70|| +|151|[Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/description/)| [Java](leetcode/solution/src/ReverseWordsInAString.java)|70|这题虽然不难,但是也错了几次| +|152|[Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)| [Java](leetcode/solution/src/MaximumProductSubarray.java)|| +|153|[Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)| [Java](leetcode/solution/src/FindMinimumInRotatedSortedArray.java)|| +|154|[Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)| [Java](leetcode/solution/src/FindMinimumInRotatedSortedArrayII.java)|| +|155|[Min Stack](https://leetcode.com/problems/min-stack/)| [Java](leetcode/solution/src/MinStack.java)|95| +|156|[Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down/)| [Java](leetcode/solution/src/BinaryTreeUpsideDown.java)|70|这道题挺有意思,多做几遍| +|157|[Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/)| [Java](leetcode/solution/src/ReadNCharactersGivenRead4.java)|80|这题多做几遍,结合#158| +|158|[Read N Characters Given Read4 II - Call multiple times](https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/)| [Java](leetcode/solution/src/ReadNCharactersGivenRead4II.java)|70| +|159|[Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Java](leetcode/solution/src/LongestSubstringWithAtMostTwoDistinctCharacters.java)|100|多看两遍| +|160|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)| [Java](leetcode/solution/src/IntersectionOfTwoLinkedLists.java)|100| +|161|[One Edit Distance](https://leetcode.com/problems/one-edit-distance/)| [Java](leetcode/solution/src/OneEditDistance.java)|85|和#72做两遍| +|162|[Find Peak Element](https://leetcode.com/problems/find-peak-element/)| [Java](leetcode/solution/src/FindPeakElement.java)|90|| +|163|[Missing Ranges](https://leetcode.com/problems/missing-ranges/)| [Java](leetcode/solution/src/MissingRanges.java)|65|多做几遍,太容易错了| +|164|[Maximum Gap](https://leetcode.com/problems/maximum-gap/)| [Java](leetcode/solution/src/MaximumGap.java)|65| +|167|[Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)| [Java](leetcode/solution/src/TwoSumII.java)|100| +|168|[Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/)| [Java](leetcode/solution/src/ExcelSheetColumnTitle.java)|| +|169|[Majority Element](https://leetcode.com/problems/majority-element/)| [Java](leetcode/solution/src/MajorityElement.java)|100|| +|170|[Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/)| [Java](leetcode/solution/src/TwoSumIII.java)|100|这道题再多做一遍| +|171|[Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/)| [Java](leetcode/solution/src/ExcelSheetColumnNumber.java)|| +|172|[Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/)| [Java](leetcode/solution/src/FactorialTrailingZeroes.java)|100| +|173|[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/)| [Java](leetcode/solution/src/BSTIterator.java)|70|多留意一下| +|179|[Largest Number](https://leetcode.com/problems/largest-number/)| [Java](leetcode/solution/src/LargestNumber.java)|90| +|186|[Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/description/)| [Java](leetcode/solution/src/ReverseWordsInAStringII.java)|90|| +|188|[Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Java](leetcode/solution/src/BestTimeBuySellStockIV.java)|| +|189|[Rotate Array](https://leetcode.com/problems/rotate-array/)| [Java](leetcode/solution/src/RotateArray.java)|100|| +|190|[Reverse Bits](https://leetcode.com/problems/reverse-bits/)| [Java](leetcode/solution/src/ReverseBits.java)|85| +|198|[House Robber](https://leetcode.com/problems/house-robber/)| [Java](leetcode/solution/src/HouseRobber.java)|80| +|199|[Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/)| [Java](leetcode/solution/src/BinaryTreeRightSideView.java)|80| +|200|[Number of Islands](https://leetcode.com/problems/number-of-islands/)| [Java](leetcode/solution/src/NumberOfIslands.java)|85|这道题很经典,而且方法不止一种,每种方法都多做几遍,包括UF,#305| +|203|[Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/)| [Java](leetcode/solution/src/RemoveLinkedListElements.java)|| +|204|[Count Primes](https://leetcode.com/problems/count-primes/)| [Java](leetcode/solution/src/CountPrimes.java)|85| +|206|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Java](leetcode/solution/src/ReverseLinkedList.java)|90| +|207|[Course Schedule](https://leetcode.com/problems/course-schedule/)| [Java](leetcode/solution/src/CourseSchedule.java)|100|典型的拓扑排序| +|208|[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)| [Java](leetcode/solution/src/Trie.java)|80|和#211多留意,trie很典型| +|209|[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/)| [Java](leetcode/solution/src/MinimumSizeSubarraySum.java)|85| +|210|[Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [Java](leetcode/solution/src/CourseScheduleII.java)|95|| +|211|[Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)| [Java](leetcode/solution/src/WordDictionary.java)|85| +|212|[Word Search II](https://leetcode.com/problems/word-search-ii/)| [Java](leetcode/solution/src/WordSearchII.java)|| +|213|[House Robber II](https://leetcode.com/problems/house-robber-ii/)| [Java](leetcode/solution/src/HouseRobberII.java)|80| +|214|[Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/)| [Java](leetcode/solution/src/ShortestPalindrome.java)|| +|215|[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/)| [Java](leetcode/solution/src/KthLargestElementInArray.java)|65|这题很经典,三种解法都要了然于胸| +|216|[Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)| [Java](leetcode/solution/src/CombinationSumIII.java)|65| +|217|[Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)| [Java](leetcode/solution/src/ContainsDuplicate.java)|100| +|218|[The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/)| [Java](leetcode/solution/src/TheSkylineProblem.java)|60|这题多做两遍| +|219|[Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)| [Java](leetcode/solution/src/ContainsDuplicateII.java)|95| +|220|[Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/)| [Java](leetcode/solution/src/ContainsDuplicateIII.java)|65| +|221|[Maximal Square](https://leetcode.com/problems/maximal-square/)| [Java](leetcode/solution/src/MaximalSquare.java)|80| +|222|[Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/)| [Java](leetcode/solution/src/CountCompleteTreeNodes.java)|70|一般的做法会超时| +|223|[Rectangle Area](https://leetcode.com/problems/rectangle-area/)| [Java](leetcode/solution/src/RectangleArea.java)|95| +|224|[Basic Calculator](https://leetcode.com/problems/basic-calculator/)| [Java](leetcode/solution/src/BasicCalculator.java)|80|| +|225|[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/)| [Java](leetcode/solution/src/MyStack.java)|90| +|226|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/)| [Java](leetcode/solution/src/InvertBinaryTree.java)|80| +|228|[Summary Ranges](https://leetcode.com/problems/summary-ranges/)| [Java](leetcode/solution/src/SummaryRanges.java)|70|| +|229|[Majority Element II](https://leetcode.com/problems/majority-element-ii/)| [Java](leetcode/solution/src/MajorityElementII.java)|70|| +|230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [Java](leetcode/solution/src/KthSmallestElementInBST.java)|85|注意Follow Up| +|232|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)| [Java](leetcode/solution/src/MyQueue.java)|95| +|233|[Number of Digit One](https://leetcode.com/problems/number-of-digit-one/)| [Java](leetcode/solution/src/NumberOfDigitOne.java)|| +|234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [Java](leetcode/solution/src/PalindromeLinkedList.java)|75| +|235|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)|[Java](leetcode/solution/src/LowestCommonAncestorOfBinarySearchTree.java)|100| +|236|[Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)| [Java](leetcode/solution/src/LowestCommonAncestorOfBinaryTree.java)|50|这题很经典,多做几遍,留意节点不在树中的情况| +|237|[Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [Java](leetcode/solution/src/DeleteNodeInALinkedList.java)|100|| +|238|[Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)| [Java](leetcode/solution/src/ProductOfArrayExceptSelf.java)|85| +|239|[Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)| [Java](leetcode/solution/src/SlidingWindowMaximum.java)|75|这题非常经典,多做几遍,包括常规算法(优先队列,treemap)及优化算法双端队列| +|240|[Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/)| [Java](leetcode/solution/src/Search2DMatrixII.java)|100| +|241|[Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/)| [Java](leetcode/solution/src/DifferenceWaysToAddParentheses.java)|| +|242|[Valid Anagram](https://leetcode.com/problems/valid-anagram/)| [Java](leetcode/solution/src/ValidAnagram.java)|100| +|243|[Shortest Word Distance](https://leetcode.com/problems/shortest-word-distance/)| [Java](leetcode/solution/src/ShortestWordDistance.java)|80| +|244|[Shortest Word Distance II](https://leetcode.com/problems/shortest-word-distance-ii/)| [Java](leetcode/solution/src/ShortestWordDistanceII.java)|80|| +|245|[Shortest Word Distance III](https://leetcode.com/problems/shortest-word-distance-iii/)| [Java](leetcode/solution/src/ShortestWordDistanceIII.java)|80|| +|246|[Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/)| [Java](leetcode/solution/src/StrobogrammaticNumber.java)|70|#247一个系列,多看两遍| +|247|[Strobogrammatic Number II](https://leetcode.com/problems/strobogrammatic-number-ii/)| [Java](leetcode/solution/src/StrobogrammaticNumberII.java)|70|多看两遍| +|249|[Group Shifted Strings](https://leetcode.com/problems/group-shifted-strings/)| [Java](leetcode/solution/src/GroupShiftedStrings.java)|| +|250|[Count Univalue Subtrees](https://leetcode.com/problems/count-univalue-subtrees/)| [Java](leetcode/solution/src/CountUnivalueSubtrees.java)|70|这题要多做几遍| +|251|[Flatten 2D Vector](https://leetcode.com/problems/flatten-2d-vector/)| [Java](leetcode/solution/src/Vector2D.java)|100| +|252|[Meeting Rooms](https://leetcode.com/problems/meeting-rooms/)| [Java](leetcode/solution/src/MeetingRooms.java)|100| +|253|[Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/)| [Java](leetcode/solution/src/MeetingRoomsII.java)|90| +|254|[Factor Combinations](https://leetcode.com/problems/factor-combinations/)| [Java](leetcode/solution/src/FactorCombinations.java)|80|| +|255|[Verify Preorder Sequence in Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/)| [Java](leetcode/solution/src/VerifyPreorderSequenceInBinarySearchTree.java)|85|很简单,粗心错了| +|256|[Paint House](https://leetcode.com/problems/paint-house/)| [Java](leetcode/solution/src/PaintHouse.java)|95| +|257|[Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)| [Java](leetcode/solution/src/BinaryTreePaths.java)|80| +|259|[3Sum Smaller](https://leetcode.com/problems/3sum-smaller/)| [Java](leetcode/solution/src/ThreeSumSmaller.java)|95|这题虽然简单,但是因为思维定式还是错了几次| +|261|[Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/)| [Java](leetcode/solution/src/GraphValidTree.java)|70|这题多做几遍| +|263|[Ugly Number](https://leetcode.com/problems/ugly-number/)| [Java](leetcode/solution/src/UglyNumber.java)|85| +|264|[Ugly Number II](https://leetcode.com/problems/ugly-number-ii/)| [Java](leetcode/solution/src/UglyNumberII.java)|70| +|265|[Paint House II](https://leetcode.com/problems/paint-house-ii)| [Java](leetcode/solution/src/PaintHouseII.java)|60| +|266|[Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/)| [Java](leetcode/solution/src/PalindromePermutation.java)|100| +|267|[Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/)| [Java](leetcode/solution/src/PalindromePermutationII.java)|80|典型,多看两遍| +|268|[Missing Number](https://leetcode.com/problems/missing-number)| [Java](leetcode/solution/src/MissingNumber.java)|100|| +|269|[Alien Dictionary](https://leetcode.com/problems/alien-dictionary/)| [Java](leetcode/solution/src/AlienDictionary.java)|70|这题要多做几遍| +|270|[Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/)| [Java](leetcode/solution/src/ClosestBinarySearchTreeValue.java)|90| +|271|[Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/)| [Java](leetcode/solution/src/EncodeAndDecodeStrings.java)|65|思路巧妙,多看几遍| +|272|[Closest Binary Search Tree Value II](https://leetcode.com/problems/closest-binary-search-tree-value-ii/)| [Java](leetcode/solution/src/ClosestBinarySearchTreeValueII.java)|60|这题非常值得多做几遍,几种写法都试试| +|273|[Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)| [Java](leetcode/solution/src/IntegerToEnglishWords.java)|75|多做几遍,做到bug free| +|274|[H-Index](https://leetcode.com/problems/h-index/)| [Java](leetcode/solution/src/HIndex.java)|80| +|275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [Java](leetcode/solution/src/HIndexII.java)|75| +|277|[Find the Celebrity](https://leetcode.com/problems/find-the-celebrity/)| [Java](leetcode/solution/src/FindCelebrity.java)|100| +|278|[First Bad Version](https://leetcode.com/problems/first-bad-version/)| [Java](leetcode/solution/src/FirstBadVersion.java)|100| +|279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/)| [Java](leetcode/solution/src/PerfectSquares.java)|95| +|280|[Wiggle Sort](https://leetcode.com/problems/wiggle-sort/)| [Java](leetcode/solution/src/WiggleSort.java)|80|思路巧妙,多看两遍| +|281|[Zigzag Iterator](https://leetcode.com/problems/zigzag-iterator/)| [Java](leetcode/solution/src/ZigzagIterator.java)|85|多做三遍,考虑扩展到k的情况| +|282|[Expression Add Operators](https://leetcode.com/problems/expression-add-operators/)| [Java](leetcode/solution/src/ExpressionAddOperators.java)|50| +|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/)| [Java](leetcode/solution/src/MoveZeroes.java)|100| +|284|[Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [Java](leetcode/solution/src/PeekingIterator.java)|100| +|285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/)| [Java](leetcode/solution/src/InorderSuccessorInBST.java)|70|这道题有意思,要多做几遍| +|286|[Walls and Gates](https://leetcode.com/problems/walls-and-gates/)| [Java](leetcode/solution/src/WallsAndGates.java)|70|多看两遍| +|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)| [Java](leetcode/solution/src/FindTheDuplicateNumber.java)|| +|288|[Unique Word Abbreviation](https://leetcode.com/problems/unique-word-abbreviation/)| [Java](leetcode/solution/src/ValidWordAbbr.java)|70|这题不难,多做两遍,题目意思容易理解错| +|289|[Game of Life](https://leetcode.com/problems/game-of-life/)| [Java](leetcode/solution/src/GameOfLife.java)|70|| +|293|[Flip Game](https://leetcode.com/problems/flip-game/)| [Java](leetcode/solution/src/FlipGame.java)|90|| +|294|[Flip Game II](https://leetcode.com/problems/flip-game-ii/)| [Java](leetcode/solution/src/FlipGameII.java)|90|| +|295|[Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)| [Java](leetcode/solution/src/FindMedianFromDataStream.java)|| +|297|[Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)|[Java](leetcode/solution/src/Codec.java)|80|好题目,多做做,递归的非递归的| +|298|[Binary Tree Longest Consecutive Sequence](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/)| [Java](leetcode/solution/src/BinaryTreeLongestConsecutiveSequence.java)|70|多做三遍,尽可能简洁| +|299|[Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)|[Java](leetcode/solution/src/BullsAndCows.java)|| +|300|[Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)| [Java](leetcode/solution/src/LongestIncreasingSubsequence.java)|| +|301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)| [Java](leetcode/solution/src/RemoveInvalidParentheses.java)|70|比较难,多做几遍| +|302|[Smallest Rectangle Enclosing Black Pixels](https://leetcode.com/problems/smallest-rectangle-enclosing-black-pixels/)| [Java](leetcode/solution/src/SmallestRectangleEnclosingBlackPixels.java)||| +|303|[Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)| [Java](leetcode/solution/src/NumArray.java)|100| +|304|[Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/)| [Java](leetcode/solution/src/NumMatrix.java)|65| +|305|[Number of Islands II](https://leetcode.com/problems/number-of-islands-ii/)| [Java](leetcode/solution/src/NumberOfIslandsII.java)|70|这题多做几遍,经典的UF| +|307|[Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/)| [Java](leetcode/solution/src/NumArrayII.java)|70|和#303, #304, #308定要多做几遍,掌握BIT| +|308|[Range Sum Query 2D - Mutable](https://leetcode.com/problems/range-sum-query-2d-mutable/)| [Java](leetcode/solution/src/NumMatrixII.java)|70| +|309|[Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)| [Java](leetcode/solution/src/BestTimeBuySellStockWithCoolDown.java)|| +|310|[Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/)| [Java](leetcode/solution/src/MinimumHeightTrees.java)|60|这题多做几遍| +|311|[Sparse Matrix Multiplication](https://leetcode.com/problems/sparse-matrix-multiplication/)| [Java](leetcode/solution/src/SparseMatrixMultiplication.java)|80| +|312|[Burst Balloons](https://leetcode.com/problems/burst-balloons/)| [Java](leetcode/solution/src/BurstBalloons.java)|60| +|313|[Super Ugly Number](https://leetcode.com/problems/super-ugly-number/)| [Java](leetcode/solution/src/SuperUglyNumber.java)||| +|314|[Binary Tree Vertical Order Traversal](https://leetcode.com/problems/binary-tree-vertical-order-traversal/)| [Java](leetcode/solution/src/BinaryTreeVerticalOrderTraversal.java)|80| +|315|[Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| [Java](leetcode/solution/src/CountOfSmallerNumbersAfterSelf.java)|60| +|316|[Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/)| [Java](leetcode/solution/src/RemoveDuplicateLetters.java)|70| +|317|[Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/)| [Java](leetcode/solution/src/ShortestDistanceFromAllBuildings.java)|75|典型的bfs,多做两遍| +|319|[Bulb Switcher](https://leetcode.com/problems/bulb-switcher/)| [Java](leetcode/solution/src/BulbSwitcher.java)|90| +|320|[Generalized Abbreviation](https://leetcode.com/problems/generalized-abbreviation/)| [Java](leetcode/solution/src/GeneralizedAbbreviation.java)|70|这题是典型的back tracking,多做几遍| +|322|[Coin Change](https://leetcode.com/problems/coin-change/)|[Java](leetcode/solution/src/CoinChange.java)|80|| +|323|[Number of Connected Components in an Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)| [Java](leetcode/solution/src/NumberOfConnectedComponents.java)|90|典型的图,多看两遍| +|324|[Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/)| [Java](leetcode/solution/src/WiggleSortII.java)|60| +|325|[Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/)| [Java](leetcode/solution/src/MaximumSizeSubarraySumEqualsK.java)|75|这题思路有意思,多做几遍| +|328|[Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)| [Java](leetcode/solution/src/OddEvenLinkedList.java)|90| +|329|[Longest Increasing Path in a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)| [Java](leetcode/solution/src/LongestIncreasingPathInAMatrix.java)|70|这题要多做几遍| +|332|[Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/)| [Java](leetcode/solution/src/ReconstructItinerary.java)||| +|333|[Largest BST Subtree](https://leetcode.com/problems/largest-bst-subtree/)| [Java](leetcode/solution/src/LargestBSTSubtree.java)|50|这道题虽然不难,但是折腾了很久,一定要多做| +|334|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/)| [Java](leetcode/solution/src/IncreasingTripletSubsequence.java)|75| +|335|[Self Crossing](https://leetcode.com/problems/self-crossing/)| [Java](leetcode/solution/src/SelfCrossing.java)|80| +|336|[Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/)| [Java](leetcode/solution/src/PalindromePairs.java)|| +|337|[House Robber III](https://leetcode.com/problems/house-robber-iii/)| [Java](leetcode/solution/src/HouseRobberIII.java)|70|建议再做两遍| +|339|[Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/)| [Java](leetcode/solution/src/NestedListWeightSum.java)|| +|340|[Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [Java](leetcode/solution/src/LongestSubstringWithAtMostKDistinctCharacters.java)|80|和#159类似| +|341|[Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [Java](leetcode/solution/src/NestedIterator.java)|75|这题有点意思,多做两遍| +|344|[Reverse String](https://leetcode.com/problems/reverse-string/)| [Java](leetcode/solution/src/ReverseString.java)|100|| +|345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/)| [Java](leetcode/solution/src/ReverseVowelsOfaString.java)|100|| +|346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/)| [Java](leetcode/solution/src/MovingAverage.java)|95| +|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)| [Java](leetcode/solution/src/TopKFrequentElements.java)|85| +|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)| [Java](leetcode/solution/src/IntersectionOfTwoArrays.java)||| +|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)| [Java](leetcode/solution/src/IntersectionOfTwoArraysII.java)||| +|351|[Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/)| [Java](leetcode/solution/src/AndroidUnlockPatterns.java)|70|这题多做几遍| +|357|[Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/)| [Java](leetcode/solution/src/CountNumberWithUniqueDigits.java)|| +|358|[Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [Java](leetcode/solution/src/RearrangeStringKDistanceApart.java)|| +|359|[Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/)| [Java](leetcode/solution/src/LoggerRateLimiter.java)|100|这题如果不考虑空间消耗的话其实很简单| +|361|[Bomb Enemy](https://leetcode.com/problems/bomb-enemy/)| [Java](leetcode/solution/src/BombEnemy.java)|65|这题多做几遍,开始没思路| +|364|[Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/)| [Java](leetcode/solution/src/NestedListWeightSumII.java)|| +|366|[Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/)| [Java](leetcode/solution/src/FindLeavesOfBinaryTree.java)|60|这道题刚开始还没思路| +|367|[Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square)| [Java](leetcode/solution/src/ValidPerfectSquare.java)||| +|369|[Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [Java](leetcode/solution/src/PlusOneLinkedList.java)|100|| +|370|[Range Addition](https://leetcode.com/problems/range-addition/)| [Java](leetcode/solution/src/RangeAddition.java)|80|| +|373|[Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/)| [Java](leetcode/solution/src/FindKPairsWithSmallestSums.java)||| +|374|[Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)| [Java](leetcode/solution/src/GuessNumberHigherOrLower.java)|100| +|375|[Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [Java](leetcode/solution/src/GuessNumberHigherOrLowerII.java)|60| +|377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [Java](leetcode/solution/src/combinationSum4.java)|65| +|378|[Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/)| [Java](leetcode/solution/src/KthSmallestElementInASortedMatrix.java)||| +|380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/)| [Java](leetcode/solution/src/RandomizedSet.java)|75|这道题很有意思,多做几遍| +|381|[Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/)| [Java](leetcode/solution/src/RandomizedCollection.java)|| +|382|[Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/)| [Java](leetcode/solution/src/LinkedListRandomNode.java)|| +|384|[Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/)| [Java](leetcode/solution/src/ShuffleAnArray.java)|75| +|387|[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/)| [Java](leetcode/solution/src/FirstUniqueCharacterInAString.java)|100| +|388|[Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/)| [Java](leetcode/solution/src/LongestAbsoluteFilePath.java)|65|其实不难,乍看没思路,多做几遍| +|391|[Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/)| [Java](leetcode/solution/src/PerfectRectangle.java)|70|这题很trick,多做两遍| +|393|[UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/)| [Java](leetcode/solution/src/UTFValidation.java)|60|错了很多次,多做几遍| +|394|[Decode String](https://leetcode.com/problems/decode-string/)| [Java](leetcode/solution/src/DecodeString.java)|75|这题容易错,多做四遍| +|395|[Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/)| [Java](leetcode/solution/src/LongestSubstringWithAtLeastKRepeatingCharacters.java)|65| +|398|[Random Pick Index](https://leetcode.com/problems/random-pick-index/)| [Java](leetcode/solution/src/RandomPickIndex.java)|80| +|399|[Evaluate Division](https://leetcode.com/problems/evaluate-division/)| [Java](leetcode/solution/src/EvaluateDivision.java)|60|这题多做几遍| +|401|[Binary Watch](https://leetcode.com/problems/binary-watch/)| [Java](leetcode/solution/src/BinaryWatch.java)|| +|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/)| [Java](leetcode/solution/src/SumOfLeftLeaves.java)|80| +|406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/)| [Java](leetcode/solution/src/QueueReconstructionByHeight.java)|60|这题开始没思路,多做几遍| +|407|[Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/)| [Java](leetcode/solution/src/TrappingRainWaterII.java)|| +|408|[Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/)| [Java](leetcode/solution/src/validWordAbbreviation.java)|80|多做两遍| +|409|[Longest Palindrome](https://leetcode.com/problems/longest-palindrome/)| [Java](leetcode/solution/src/LongestPalindrome.java)|| +|410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum)| [Java](leetcode/solution/src/SplitArrayLargestSum.java)|| +|412|[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)| [Java](leetcode/solution/src/FizzBuzz.java)|100| +|413|[Third Maximum Number](https://leetcode.com/problems/third-maximum-number/)| [Java](leetcode/solution/src/ThirdMaximumNumber.java)|80|| +|418|[Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting/)| [Java](leetcode/solution/src/SentenceScreenFitting.java)|65|这题思路巧妙,多做几遍,常规思路超时| +|422|[Valid Word Square](https://leetcode.com/problems/valid-word-square/)| [Java](leetcode/solution/src/ValidWordSquare.java)|90| +|425|[Word Squares](https://leetcode.com/problems/word-squares/)| [Java](leetcode/solution/src/WordSquare.java)|70|这题很典型,多做几遍| +|436|[Find Right Interval](https://leetcode.com/problems/find-right-interval/)| [Java](leetcode/solution/src/FindRightInterval.java)||| +|437|[Path Sum III](https://leetcode.com/problems/path-sum-iii/)| [Java](leetcode/solution/src/PathSumIII.java)|60|这道题错了很多遍,要重点关注| +|438|[Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/)| [Java](leetcode/solution/src/FindAllAnagramsInString.java)|75|这道题非常经典,最优解法需要多做几遍,保证once bug free| +|442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/)| [Java](leetcode/solution/src/FindAllDuplicatesInAnArray.java)|80|| +|445|[Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/discuss/)| [Java](leetcode/solution/src/AddTwoNumbersII.java)|80|| +|448|[Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array)| [Java](leetcode/solution/src/FindAllNumbersDisappearedInAnArray.java)|80|| +|449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst)| [Java](leetcode/solution/src/SerializeAndDeserializeBST.java)|90|和#297一样| +|450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [Java](leetcode/solution/src/DeleteNodeInBST.java)|60|这题非常经典,值得多做十遍| +|451|[Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/)| [Java](leetcode/solution/src/SortCharactersByFrequency.java)||| +|459|[Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/)| [Java](leetcode/solution/src/RepeatedSubstringPattern.java)||| +|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/)| [Java](leetcode/solution/src/TotalHammingDistance.java)|| +|480|[Sliding Window Median](https://leetcode.com/problems/sliding-window-median/)| [Java](leetcode/solution/src/SlidingWindowMedian.java)|70|| +|482|[License Key Formatting](https://leetcode.com/problems/license-key-formatting/)| [Java](leetcode/solution/src/LicenseKeyFormatting.java)|90|| +|483|[Smallest Good Base](https://leetcode.com/problems/smallest-good-base/)| [Java](leetcode/solution/src/SmallestGoodBase.java)||| +|485|[Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)| [Java](leetcode/solution/src/MaxConsecutiveOnes.java)|100|| +|487|[Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/)| [Java](leetcode/solution/src/MaxConsecutiveOnesII.java)|80|| +|501|[Find Mode in Binary Search Tree](https://leetcode.com/problems/find-mode-in-binary-search-tree/)| [Java](leetcode/solution/src/FindModeInBinarySearchTree.java)|70|不难,容易错,多做两次| +|508|[Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum/submissions/)| [Java](leetcode/solution/src/MostFrequentSubtreeSum.java)|| +|513|[Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/)| [Java](leetcode/solution/src/FindBottomLeftTreeValue.java)|100|| +|515|[Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/)| [Java](leetcode/solution/src/FindLargestValueInEachTreeRow.java)|100|| +|524|[Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/)| [Java](leetcode/solution/src/LongestWordInDictionaryThroughDeleting.java)||| +|526|[Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/)| [Java](leetcode/solution/src/BeautifulArrangement.java)|80|| +|535|[Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/)| [Java](leetcode/solution/src/EncodeAndDecodeTinyURL.java)|100|| +|538|[Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/)|[Java](leetcode/solution/src/ConvertBSTToGreaterTree.java)|100|| +|541|[Reverse String II](https://leetcode.com/problems/reverse-string-ii/)| [Java](leetcode/solution/src/ReverseStringII.java)|100|| +|543|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/)|[Java](leetcode/solution/src/DiameterOfBinaryTree.java)|80|这题易错| +|547|[Friend Circles](https://leetcode.com/problems/friend-circles/)|[Java](leetcode/solution/src/FriendCircles.java)|70|| +|557|[Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/)| [Java](leetcode/solution/src/ReverseWordsInAStringIII.java)|100|| +|560|[Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/)| [Java](leetcode/solution/src/SubarraySumEqualsK.java)|70|| +|563|[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/)|[Java](leetcode/solution/src/BinaryTreeTilt.java)|90|| +|564|[Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/)|[Java](leetcode/solution/src/FindTheClosestPalindrome.java)|80|此题暴力法即可| +|572|[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)|[Java](leetcode/solution/src/SubtreeOfAnotherTree.java)|80|| +|606|[Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)|[Java](leetcode/solution/src/ConstructStringFromBinaryTree.java)|90|| +|617|[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)|[Java](leetcode/solution/src/MergeTwoBinaryTrees.java)|100|很简单| +|621|[Task Scheduler](https://leetcode.com/problems/task-scheduler/)|[Java](leetcode/solution/src/TaskScheduler.java)|70|| +|637|[Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/#/description)| [Java](leetcode/solution/src/AverageOfLevelsInBinaryTree.java)|100|| +|652|[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/)| [Java](leetcode/solution/src/FindDuplicateSubtrees.java)|70|开始还没思路| +|653|[Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| [Java](leetcode/solution/src/TwoSumIV.java)|90|| +|654|[Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/description/)|[Java](leetcode/solution/src/MaximumBinaryTree.java)|100|| +|669|[Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/)|[Java](leetcode/solution/src/TrimABinarySearchTree.java)|100|| +|681|[Next Closest Time](https://leetcode.com/problems/next-closest-time/)|[Java](leetcode/solution/src/NextClosestTime.java)|80|这题多做几遍| +|683|[K Empty Slots](https://leetcode.com/problems/k-empty-slots/)|[Java](leetcode/solution/src/KEmptySlots.java)|80|| +|684|[Redundant Connection](https://leetcode.com/problems/redundant-connection/)| [Java](leetcode/solution/src/RedundantConnection.java)||| +|687|[Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/)|[Java](leetcode/solution/src/LongestUnivaluePath.java)|70|| +|695|[Max Area of Island](https://leetcode.com/problems/max-area-of-island/)|[Java](leetcode/solution/src/MaxAreaOfIsland.java)|100|| +|703|[Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/)|[Java](leetcode/solution/src/KthLargestElementInAStream.java)|100|| +|771|[Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/)|[Java](leetcode/solution/src/JewelsAndStones.java)|100|| +|814|[Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/)|[Java](leetcode/solution/src/JewelsAndStones.java)|80|| +|819|[Most Common Word](https://leetcode.com/problems/most-common-word/)|[Java](leetcode/solution/src/MostCommonWord.java)|85|| +|843|[Guess the Word](https://leetcode.com/problems/guess-the-word/)|[Java](leetcode/solution/src/GuessTheWord.java)|90|| +|844|[Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/)|[Java](leetcode/solution/src/BackspaceStringCompare.java)|100|| +|849|[Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/)|[Java](leetcode/solution/src/MaximizeDistanceToClosestPerson.java)|80|| +|857|[Minimum Cost to Hire K Workers](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/)|[Java](leetcode/solution/src/MinimumCostToHireKWorkers.java)|70|| +|872|[Leaf-Similar Trees](https://leetcode.com/problems/leaf-similar-trees/)|[Java](leetcode/solution/src/LeafSimilarTrees.java)|80|| +|889|[Construct Binary Tree from Preorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/)|[Java](leetcode/solution/src/ConstructBinaryTreeFromPreorderAndPostorderTraversal.java)|80|| +|904|[Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/)|[Java](leetcode/solution/src/FruitIntoBaskets.java)|90|| +|929|[Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/)|[Java](leetcode/solution/src/UniqueEmailAddresses.java)|90|| \ No newline at end of file diff --git a/amazon/.gitignore b/amazon/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/amazon/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/amazon/amazon.iml b/amazon/amazon.iml deleted file mode 100644 index c9e9249..0000000 --- a/amazon/amazon.iml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/amazon/build.gradle b/amazon/build.gradle deleted file mode 100644 index 7ab6e83..0000000 --- a/amazon/build.gradle +++ /dev/null @@ -1,9 +0,0 @@ -apply plugin: 'java' - -dependencies { - compile fileTree(include: ['*.jar'], dir: 'libs') - compile project(':library') -} - -sourceCompatibility = "1.7" -targetCompatibility = "1.7" diff --git a/amazon/src/main/java/com/leetcode/amazon/AddTwoNumbers.java b/amazon/src/main/java/com/leetcode/amazon/AddTwoNumbers.java deleted file mode 100644 index 5b700cf..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/AddTwoNumbers.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 17/8/11. - */ - -public class AddTwoNumbers { - - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - if (l1 == null) { - return l2; - } - if (l2 == null) { - return l1; - } - ListNode dummy = new ListNode(0), node = dummy; - - int flag = 0; - for (ListNode p1 = l1, p2 = l2; p1 != null || p2 != null || flag > 0; ) { - int n1 = p1 != null ? p1.val : 0; - int n2 = p2 != null ? p2.val : 0; - int sum = n1 + n2 + flag; - ListNode p = new ListNode(sum % 10); - flag = sum / 10; - node.next = p; - node = node.next; - - if (p1 != null) { - p1 = p1.next; - } - if (p2 != null) { - p2 = p2.next; - } - } - - return dummy.next; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/BestTimeToBuyAndSellStock.java b/amazon/src/main/java/com/leetcode/amazon/BestTimeToBuyAndSellStock.java deleted file mode 100644 index 55badd3..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/BestTimeToBuyAndSellStock.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/10. - */ - -public class BestTimeToBuyAndSellStock { - - public int maxProfit(int[] prices) { - int maxProfit = 0, min = Integer.MAX_VALUE; - - for (int price : prices) { - int profit = price - min; - if (profit > maxProfit) { - maxProfit = profit; - } - min = Math.min(min, price); - } - - return maxProfit; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/BinaryTreeVerticalOrderTraversal.java b/amazon/src/main/java/com/leetcode/amazon/BinaryTreeVerticalOrderTraversal.java deleted file mode 100644 index 83d6639..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/BinaryTreeVerticalOrderTraversal.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -/** - * Created by liwentian on 17/8/14. - */ - -public class BinaryTreeVerticalOrderTraversal { - - public List> verticalOrder(TreeNode root) { - List> result = new LinkedList<>(); - - if (root == null) { - return result; - } - - HashMap> map = new HashMap<>(); - HashMap valueMap = new HashMap<>(); - - Queue queue = new LinkedList<>(); - queue.offer(root); - addNode(root, map, valueMap, 0); - - int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; - - while (!queue.isEmpty()) { - TreeNode node = queue.poll(); - - int val = valueMap.get(node); - - if (node.left != null) { - queue.offer(node.left); - addNode(node.left, map, valueMap, val - 1); - } - - if (node.right != null) { - queue.offer(node.right); - addNode(node.right, map, valueMap, val + 1); - } - - min = Math.min(min, val); - max = Math.max(max, val); - } - - for (int i = min; i <= max; i++) { - result.add(map.get(i)); - } - - return result; - } - - private void addNode(TreeNode node, HashMap> map, HashMap values, int level) { - List list = map.get(level); - if (list == null) { - list = new LinkedList<>(); - map.put(level, list); - } - list.add(node.val); - values.put(node, level); - } - -} diff --git a/amazon/src/main/java/com/leetcode/amazon/CopyListWithRandomPointer.java b/amazon/src/main/java/com/leetcode/amazon/CopyListWithRandomPointer.java deleted file mode 100644 index 52bfbf6..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/CopyListWithRandomPointer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.RandomListNode; - -/** - * Created by liwentian on 17/8/9. - */ - -public class CopyListWithRandomPointer { - - public RandomListNode copyRandomList(RandomListNode head) { - for (RandomListNode node = head; node != null; ) { - RandomListNode next = node.next; - - RandomListNode copy = new RandomListNode(node.label); - copy.next = next; - node.next = copy; - node = next; - } - - for (RandomListNode node = head; node != null; ) { - node.next.random = node.random != null ? node.random.next : null; - node = node.next.next; - } - - RandomListNode dummy = new RandomListNode(0), cur = dummy; - for (RandomListNode node = head; node != null; ) { - cur.next = node.next; - cur = cur.next; - - node.next = node.next.next; - node = node.next; - } - - return dummy.next; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/CountPrimes.java b/amazon/src/main/java/com/leetcode/amazon/CountPrimes.java deleted file mode 100644 index 86a31b1..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/CountPrimes.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/12. - */ - -public class CountPrimes { - - public int countPrimes(int n) { - boolean[] f = new boolean[n]; - int count = 0; - for (int i = 2; i < n; i++) { - if (!f[i]) { - count++; - for (int j = 2; j * i < n; j++) { - f[i * j] = true; - } - } - } - return count; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/EncodeAndDecodeTinyUrl.java b/amazon/src/main/java/com/leetcode/amazon/EncodeAndDecodeTinyUrl.java deleted file mode 100644 index 7436d91..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/EncodeAndDecodeTinyUrl.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.leetcode.amazon; - -import java.util.HashMap; -import java.util.Random; - -/** - * Created by liwentian on 2017/10/16. - */ - -public class EncodeAndDecodeTinyUrl { - - private static final String SRC = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - - private static final String URL_PREFIX = "http://tinyurl.com/"; - - private HashMap mMap = new HashMap<>(); - - private static final int SHORT_URL_LEN = 6; - - private Random mRandom = new Random(System.currentTimeMillis()); - - public String encode(String longUrl) { - String shortUrl = ""; - do { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < SHORT_URL_LEN; i++) { - sb.append(SRC.charAt(mRandom.nextInt(SRC.length()))); - } - shortUrl = sb.toString(); - } while (mMap.containsKey(shortUrl)); - mMap.put(shortUrl, longUrl); - return URL_PREFIX + shortUrl; - } - - // Decodes a shortened URL to its original URL. - public String decode(String shortUrl) { - return mMap.get(shortUrl.replaceAll(URL_PREFIX, "")); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/FindAllAnagramsInAString.java b/amazon/src/main/java/com/leetcode/amazon/FindAllAnagramsInAString.java deleted file mode 100644 index c576ec5..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/FindAllAnagramsInAString.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.leetcode.amazon; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 17/8/9. - */ - -public class FindAllAnagramsInAString { - - // abacbabc -> abc - public List findAnagrams(String s, String p) { - int[] count = new int[26], temp = new int[26]; - - for (char c : p.toCharArray()) { - count[c - 'a']++; - } - - List result = new LinkedList<>(); - - int sl = s.length(), pl = p.length(); - for (int start = 0, end = 0; end < sl; ) { - char c = s.charAt(end); - - if (count[c - 'a'] == 0) { - if (start <= end) { - temp[s.charAt(start++) - 'a']--; - } else { - end++; - } - continue; - } - - if (temp[c - 'a'] >= count[c - 'a']) { - temp[s.charAt(start++) - 'a']--; - continue; - } - - temp[c - 'a']++; - - if (end - start + 1 == pl) { - result.add(start); - temp[s.charAt(start++) - 'a']--; - } - - end++; - } - - return result; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/InsertDeleteGetRandom.java b/amazon/src/main/java/com/leetcode/amazon/InsertDeleteGetRandom.java deleted file mode 100644 index 3feb1b2..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/InsertDeleteGetRandom.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.leetcode.amazon; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Random; - -/** - * Created by liwentian on 17/8/10. - */ - -public class InsertDeleteGetRandom { - - private HashMap mMap; - - private List mList; - - private Random mRandom; - - /** - * Initialize your data structure here. - */ - public InsertDeleteGetRandom() { - mMap = new HashMap<>(); - mList = new ArrayList<>(); - mRandom = new Random(); - } - - /** - * Inserts a value to the set. Returns true if the set did not already contain the specified element. - */ - public boolean insert(int val) { - if (mMap.containsKey(val)) { - return false; - } - mMap.put(val, mList.size()); - mList.add(val); - return true; - } - - /** - * Removes a value from the set. Returns true if the set contained the specified element. - */ - public boolean remove(int val) { - if (!mMap.containsKey(val)) { - return false; - } - - int idx = mMap.remove(val); - - if (idx != mList.size() - 1) { - int tail = mList.get(mList.size() - 1); - mList.set(idx, tail); - mMap.put(tail, idx); - } - - mList.remove(mList.size() - 1); - return true; - } - - /** - * Get a random element from the set. - */ - public int getRandom() { - if (mList.isEmpty()) { - return -1; - } - int idx = mRandom.nextInt(mList.size()); - return mList.get(idx); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/InsertInterval.java b/amazon/src/main/java/com/leetcode/amazon/InsertInterval.java deleted file mode 100644 index 44ed78f..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/InsertInterval.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.Interval; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 17/8/14. - */ - -public class InsertInterval { - - public List insert(List intervals, Interval newInterval) { - List result = new LinkedList<>(); - - for (int i = 0; i < intervals.size(); i++) { - Interval interval = intervals.get(i); - - if (newInterval.start > interval.end) { - result.add(interval); - } else if (newInterval.end < interval.start) { - result.add(newInterval); - newInterval = interval; - } else { - newInterval.start = Math.min(newInterval.start, interval.start); - newInterval.end = Math.max(newInterval.end, interval.end); - } - } - - if (newInterval != null) { - result.add(newInterval); - } - - return result; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/IntersectionOfTwoLinkedLists.java b/amazon/src/main/java/com/leetcode/amazon/IntersectionOfTwoLinkedLists.java deleted file mode 100644 index 9b16ad2..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/IntersectionOfTwoLinkedLists.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 17/8/10. - */ - -public class IntersectionOfTwoLinkedLists { - - public ListNode getIntersectionNode(ListNode headA, ListNode headB) { - int lenA = 0, lenB = 0; - for (ListNode node = headA; node != null; node = node.next) { - lenA++; - } - for (ListNode node = headB; node != null; node = node.next) { - lenB++; - } - ListNode node1 = lenA > lenB ? headA : headB; - ListNode node2 = lenA > lenB ? headB : headA; - - for (int i = 0; i < Math.abs(lenA - lenB); i++) { - node1 = node1.next; - } - - while (node1 != null && node1 != node2) { - node1 = node1.next; - node2 = node2.next; - } - - return node1; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/KthLargestElementInAnArray.java b/amazon/src/main/java/com/leetcode/amazon/KthLargestElementInAnArray.java deleted file mode 100644 index fe04f14..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/KthLargestElementInAnArray.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.leetcode.amazon; - -import java.util.PriorityQueue; - -/** - * Created by liwentian on 17/8/11. - */ - -public class KthLargestElementInAnArray { - - // nlgn - public int findKthLargest(int[] nums, int k) { - PriorityQueue queue = new PriorityQueue<>(); - for (int n : nums) { - queue.offer(n); - if (queue.size() > k) { - queue.poll(); - } - } - return queue.peek(); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/LRUCache.java b/amazon/src/main/java/com/leetcode/amazon/LRUCache.java deleted file mode 100644 index 732cb6d..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/LRUCache.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.leetcode.amazon; - -import java.util.HashMap; - -/** - * Created by liwentian on 17/8/9. - */ - -public class LRUCache { - - private int mCapacity; - - private ListNode mHead; - - private HashMap mMap; - - public LRUCache(int capacity) { - mCapacity = capacity; - mHead = new ListNode(); - mMap = new HashMap<>(); - } - - public int get(int key) { - ListNode node = mMap.get(key); - if (node == null) { - return -1; - } - node.remove(); - mHead.add(node); - return node.value; - } - - public void put(int key, int value) { - ListNode node = mMap.get(key); - - if (node != null) { - node.remove(); - mHead.add(node); - node.value = value; - } else { - if (mMap.size() >= mCapacity) { - node = mHead.prev; - node.remove(); - mMap.remove(node.key); - } - node = new ListNode(); - node.key = key; - node.value = value; - mMap.put(key, node); - mHead.add(node); - } - } - - private class ListNode { - ListNode prev, next; - - int key, value; - - ListNode() { - prev = this; - next = this; - } - - void remove() { - prev.next = next; - next.prev = prev; - } - - void add(ListNode node) { - node.next = next; - next.prev = node; - - node.prev = this; - this.next = node; - } - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/LetterCombinationsOfAPhoneNumber.java b/amazon/src/main/java/com/leetcode/amazon/LetterCombinationsOfAPhoneNumber.java deleted file mode 100644 index 1f54c81..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/LetterCombinationsOfAPhoneNumber.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.leetcode.amazon; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 17/8/10. - */ - -public class LetterCombinationsOfAPhoneNumber { - - private final String[] ARR = { - "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" - }; - - public List letterCombinations(String digits) { - List list = new LinkedList<>(); - if (!digits.isEmpty()) { - helper(digits, 0, list, ""); - } - return list; - } - - private void helper(String digits, int start, List list, String s) { - if (start >= digits.length()) { - list.add(s); - return; - } - int n = digits.charAt(start) - '0'; - for (char c : ARR[n].toCharArray()) { - helper(digits, start + 1, list, s + c); - } - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/LinkedListCycle.java b/amazon/src/main/java/com/leetcode/amazon/LinkedListCycle.java deleted file mode 100644 index d25dde4..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/LinkedListCycle.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.leetcode.amazon; - - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 17/8/11. - */ - -public class LinkedListCycle { - - public boolean hasCycle(ListNode head) { - if (head == null || head.next == null) { - return false; - } - ListNode slow = head, fast = head.next.next; - while (slow != null && fast != null && fast.next != null && slow != fast) { - slow = slow.next; - fast = fast.next.next; - } - return slow == fast; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/LongestPalindromicSubstring.java b/amazon/src/main/java/com/leetcode/amazon/LongestPalindromicSubstring.java deleted file mode 100644 index 4161510..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/LongestPalindromicSubstring.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/10. - */ - -/** - * h - */ -public class LongestPalindromicSubstring { - - private int maxLen, begin; - - public String longestPalindrome(String s) { - for (int i = 0; i < s.length(); i++) { - helper(s, i, i); - helper(s, i, i + 1); - } - return s.substring(begin, begin + maxLen); - } - - private void helper(String s, int i, int j) { - for ( ; i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j); i--, j++); - int len = j - i - 1; - if (len > maxLen) { - maxLen = len; - begin = i + 1; - } - } - - -} diff --git a/amazon/src/main/java/com/leetcode/amazon/LongestSubstringWithoutRepeatingCharacters.java b/amazon/src/main/java/com/leetcode/amazon/LongestSubstringWithoutRepeatingCharacters.java deleted file mode 100644 index e3749b7..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/LongestSubstringWithoutRepeatingCharacters.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/13. - */ - -public class LongestSubstringWithoutRepeatingCharacters { - - public int lengthOfLongestSubstring(String s) { - int[] count = new int[256]; - - int maxLen = 0; - - for (int i = 0, j = 0; j < s.length(); ) { - if (count[s.charAt(j)] == 0) { - count[s.charAt(j)]++; - maxLen = Math.max(maxLen, j - i + 1); - j++; - } else { - --count[s.charAt(i++)]; - } - } - - return maxLen; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/LowestCommonAncestorOfABinarySearchTree.java b/amazon/src/main/java/com/leetcode/amazon/LowestCommonAncestorOfABinarySearchTree.java deleted file mode 100644 index 4b8b13e..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/LowestCommonAncestorOfABinarySearchTree.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - -/** - * Created by liwentian on 17/8/10. - */ - -public class LowestCommonAncestorOfABinarySearchTree { - - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - TreeNode node = root; - - while (node != null) { - if (p.val < node.val && q.val < node.val) { - node = node.left; - } else if (p.val > node.val && q.val > node.val) { - node = node.right; - } else { - return node; - } - } - - return null; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/LowestCommonAncestorOfABinaryTree.java b/amazon/src/main/java/com/leetcode/amazon/LowestCommonAncestorOfABinaryTree.java deleted file mode 100644 index ad5dea1..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/LowestCommonAncestorOfABinaryTree.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - -/** - * Created by liwentian on 17/8/9. - */ - -public class LowestCommonAncestorOfABinaryTree { - - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (root == null || root == p || root == q) { - return root; - } - - TreeNode left = lowestCommonAncestor(root.left, p, q); - TreeNode right = lowestCommonAncestor(root.right, p, q); - - if (left != null) { - return right != null ? root : left; - } else { - return right; - } - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/Main.java b/amazon/src/main/java/com/leetcode/amazon/Main.java deleted file mode 100644 index f1b07ad..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/Main.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - -import java.util.HashMap; -import java.util.LinkedHashMap; - -/** - * Created by liwentian on 2017/10/16. - */ - -public class Main { - - public class LargestBSTSubtree { - - class Result { - int count; - int lower; - int upper; - - Result(int count, int lower, int upper) { - this.count = count; - this.lower = lower; - this.upper = upper; - } - } - - public int largestBSTSubtree(TreeNode root) { - Result res = helper(root); - return Math.abs(res.count); - } - - private Result helper(TreeNode root) { - if (root == null) { - return new Result(0, Integer.MAX_VALUE, Integer.MIN_VALUE); - } - - Result left = helper(root.left); - Result right = helper(root.right); - - // 注意这里的等号千万别掉了,因为可能树中有节点相同 - if (left.count < 0 || right.count < 0 || left.upper >= root.val || right.lower <= root.val) { - return new Result(-1 * Math.max(Math.abs(left.count), Math.abs(right.count)), 0, 0); - } - - return new Result(left.count + right.count + 1, Math.min(left.lower, root.val), Math.max(right.upper, root.val)); - } - } - - public static void main(String[] args) { - - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/MeetingRoomII.java b/amazon/src/main/java/com/leetcode/amazon/MeetingRoomII.java deleted file mode 100644 index db58181..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/MeetingRoomII.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.Interval; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.PriorityQueue; - -/** - * Created by liwentian on 17/8/14. - */ - -public class MeetingRoomII { - - - public int minMeetingRooms(Interval[] intervals) { - Arrays.sort(intervals, new Comparator() { - @Override - public int compare(Interval interval, Interval t1) { - return interval.start - t1.start; - } - }); - - PriorityQueue queue = new PriorityQueue<>(new Comparator() { - @Override - public int compare(Integer integer, Integer t1) { - return integer - t1; - } - }); - - int count = 0; - for (int i = 0; i < intervals.length; i++) { - if (queue.isEmpty() || intervals[i].start < queue.peek()) { - count++; - } else { - queue.poll(); - } - queue.offer(intervals[i].end); - } - - return count; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/MeetingRooms.java b/amazon/src/main/java/com/leetcode/amazon/MeetingRooms.java deleted file mode 100644 index 99da747..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/MeetingRooms.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.Interval; - -import java.util.Arrays; -import java.util.Comparator; - -/** - * Created by liwentian on 17/8/14. - */ - -public class MeetingRooms { - - public boolean canAttendMeetings(Interval[] intervals) { - Arrays.sort(intervals, new Comparator() { - @Override - public int compare(Interval interval, Interval t1) { - return interval.start - t1.start; - } - }); - - for (int i = 1; i < intervals.length; i++) { - if (intervals[i].start < intervals[i - 1].end) { - return false; - } - } - - return true; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/MergeIntervals.java b/amazon/src/main/java/com/leetcode/amazon/MergeIntervals.java deleted file mode 100644 index d3d418a..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/MergeIntervals.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.Interval; - -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 17/8/14. - */ - -public class MergeIntervals { - - public List merge(List intervals) { - Collections.sort(intervals, new Comparator() { - @Override - public int compare(Interval interval, Interval t1) { - return interval.start - t1.start; - } - }); - - List result = new LinkedList<>(); - - Interval curInterval = null; - - for (Interval interval : intervals) { - if (curInterval == null) { - curInterval = interval; - } else if (interval.start <= curInterval.end) { - curInterval.end = Math.max(curInterval.end, interval.end); - } else { - result.add(curInterval); - curInterval = interval; - } - } - - if (curInterval != null) { - result.add(curInterval); - } - - return result; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/MergeKSortedLists.java b/amazon/src/main/java/com/leetcode/amazon/MergeKSortedLists.java deleted file mode 100644 index 119a927..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/MergeKSortedLists.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.leetcode.amazon; - - -import com.leetcode.library.ListNode; - -import java.util.Comparator; -import java.util.PriorityQueue; - -/** - * Created by liwentian on 17/8/11. - */ - -public class MergeKSortedLists { - - public ListNode mergeKLists(ListNode[] lists) { - ListNode dummy = new ListNode(0), cur = dummy; - - PriorityQueue queue = new PriorityQueue<>(new Comparator() { - @Override - public int compare(ListNode node1, ListNode node2) { - if (node1.val == node2.val) { - return 0; - } else if (node1.val < node2.val) { - return -1; - } else { - return 1; - } - } - }); - - for (ListNode node : lists) { - if (node != null) { - queue.offer(node); - } - } - - while (!queue.isEmpty()) { - ListNode node = queue.poll(); - cur.next = node; - cur = cur.next; - if (node.next != null) { - queue.offer(node.next); - } - } - - return dummy.next; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/MergeTwoSortedLists.java b/amazon/src/main/java/com/leetcode/amazon/MergeTwoSortedLists.java deleted file mode 100644 index a06828f..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/MergeTwoSortedLists.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 17/8/11. - */ - -public class MergeTwoSortedLists { - - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(0), cur = dummy; - for (ListNode p1 = l1, p2 = l2; p1 != null || p2 != null; ) { - if (p1 == null) { - cur.next = p2; - break; - } - if (p2 == null) { - cur.next = p1; - break; - } - if (p1.val < p2.val) { - cur.next = p1; - p1 = p1.next; - } else { - cur.next = p2; - p2 = p2.next; - } - cur = cur.next; - } - return dummy.next; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/MinStack.java b/amazon/src/main/java/com/leetcode/amazon/MinStack.java deleted file mode 100644 index 4014510..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/MinStack.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.leetcode.amazon; - -import java.util.Stack; - -/** - * Created by liwentian on 17/8/10. - */ - -public class MinStack { - - private Stack mStack; - private Stack mStack2; - - public MinStack() { - mStack = new Stack(); - mStack2 = new Stack<>(); - } - - public void push(int x) { - mStack.push(x); - - if (mStack2.isEmpty() || x < mStack2.peek()) { - mStack2.push(x); - } else { - mStack2.push(mStack2.peek()); - } - } - - public void pop() { - mStack.pop(); - mStack2.pop(); - } - - public int top() { - return mStack.peek(); - } - - public int getMin() { - return mStack2.peek(); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/NumberOfIslands.java b/amazon/src/main/java/com/leetcode/amazon/NumberOfIslands.java deleted file mode 100644 index 723ad22..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/NumberOfIslands.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.leetcode.amazon; - -import java.util.LinkedList; -import java.util.Queue; - -/** - * Created by dingjikerbo on 2017/8/6. - */ - -public class NumberOfIslands { - - public int numIslands(char[][] grid) { - int num = 0; - for (int i = 0; i < grid.length; i++) { - for (int j = 0; j < grid[0].length; j++) { - if (grid[i][j] == '1') { - num++; - dfs(grid, i, j); - } - } - } - return num; - } - - - private void bfs(char[][] grid, int i0, int j0) { - int[] dx = {-1, 1, 0, 0}, dy = {0, 0, -1, 1}; - - Queue queue = new LinkedList<>(); - queue.add(new int[] {i0, j0}); - - while (!queue.isEmpty()) { - int[] cur = queue.poll(); - int i = cur[0], j = cur[1]; - - for (int k = 0; k < dx.length; k++) { - int x = i + dx[k], y = j + dy[k]; - if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] != '1') { - continue; - } - grid[x][y] = '0'; - queue.add(new int[] {x, y}); - } - } - } - - private void dfs(char[][] grid, int i, int j) { - if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1') { - return; - } - - grid[i][j] = '0'; - dfs(grid, i + 1, j); - dfs(grid, i - 1, j); - dfs(grid, i, j + 1); - dfs(grid, i, j - 1); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/PalindromeLinkedList.java b/amazon/src/main/java/com/leetcode/amazon/PalindromeLinkedList.java deleted file mode 100644 index 150ad57..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/PalindromeLinkedList.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 17/8/11. - */ - -public class PalindromeLinkedList { - - public boolean isPalindrome(ListNode head) { - if (head == null) { - return true; - } - ListNode slow = head; - for (ListNode fast = head; fast != null && fast.next != null && fast.next.next != null; ) { - slow = slow.next; - fast = fast.next.next; - } - - ListNode node = reverse(slow.next); - slow.next = null; - - for ( ; head != null && node != null; head = head.next, node = node.next) { - if (head.val != node.val) { - return false; - } - } - return true; - } - - private ListNode reverse(ListNode head) { - ListNode dummy = new ListNode(0); - while (head != null) { - ListNode next = head.next; - head.next = dummy.next; - dummy.next = head; - head = next; - } - return dummy.next; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/PascalTriangleII.java b/amazon/src/main/java/com/leetcode/amazon/PascalTriangleII.java deleted file mode 100644 index c9ee057..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/PascalTriangleII.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leetcode.amazon; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by liwentian on 17/8/12. - */ - -public class PascalTriangleII { - - public List getRow(int rowIndex) { - List list = new ArrayList<>(); - - for (int i = 0; i <= rowIndex; i++) { - int prev = 1; - for (int j = 1; j < list.size(); j++) { - int n = list.get(j) + prev; - prev = list.get(j); - list.set(j, n); - } - list.add(1); - } - - return list; - } - -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ProductOfArrayExceptSelf.java b/amazon/src/main/java/com/leetcode/amazon/ProductOfArrayExceptSelf.java deleted file mode 100644 index 3c99992..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ProductOfArrayExceptSelf.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/9. - */ - -public class ProductOfArrayExceptSelf { - - public int[] productExceptSelf(int[] nums) { - if (nums.length == 0) { - return null; - } - - int[] result = new int[nums.length]; - result[0] = 1; - - for (int i = 1; i < nums.length; i++) { - result[i] = result[i - 1] * nums[i - 1]; - } - - for (int i = nums.length - 1, right = 1; i >= 0; i--) { - result[i] *= right; - right *= nums[i]; - } - - return result; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ReverseLinkedList.java b/amazon/src/main/java/com/leetcode/amazon/ReverseLinkedList.java deleted file mode 100644 index 0b08f09..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ReverseLinkedList.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 17/8/10. - */ - -public class ReverseLinkedList { - - public ListNode reverseList(ListNode head) { - ListNode dummy = new ListNode(0); - - for (ListNode node = head; node != null; ) { - ListNode next = node.next; - - node.next = dummy.next; - dummy.next = node; - - node = next; - } - - return dummy.next; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ReverseWordsInAString.java b/amazon/src/main/java/com/leetcode/amazon/ReverseWordsInAString.java deleted file mode 100644 index 93250ea..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ReverseWordsInAString.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/14. - */ - -public class ReverseWordsInAString { - - public String reverseWords(String s) { - StringBuilder sb = new StringBuilder(); - - for (int i = 0, j = 0; i < s.length(); ) { - if (s.charAt(i) == ' ') { - i++; - j = i; - } else if (j >= s.length() || s.charAt(j) == ' ') { - sb.insert(0, s.substring(i, j) + " "); - i = j; - } else { - j++; - } - } - - if (sb.length() > 0) { - sb.setLength(sb.length() - 1); - } - - return sb.toString(); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ReverseWordsInAStringII.java b/amazon/src/main/java/com/leetcode/amazon/ReverseWordsInAStringII.java deleted file mode 100644 index 0244dce..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ReverseWordsInAStringII.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/12. - */ - -public class ReverseWordsInAStringII { - - public void reverseWords(char[] s) { - for (int i = 0, j = i; i < s.length; ) { - if (j >= s.length || s[j] == ' ') { - reverse(s, i, j - 1); - for (i = j; j < s.length && s[j] == ' '; j++, i = j) ; - } else { - j++; - } - } - reverse(s, 0, s.length - 1); - } - - private void reverse(char[] s, int start, int end) { - for (int i = start, j = end; i < j; i++, j--) { - char t = s[i]; - s[i] = s[j]; - s[j] = t; - } - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/SearchA2DMatrixII.java b/amazon/src/main/java/com/leetcode/amazon/SearchA2DMatrixII.java deleted file mode 100644 index ac449b1..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/SearchA2DMatrixII.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/11. - */ - -public class SearchA2DMatrixII { - - public boolean searchMatrix(int[][] matrix, int target) { - if (matrix.length == 0) { - return false; - } - for (int i = 0, j = matrix[0].length - 1; j >= 0 && i < matrix.length; ) { - if (target < matrix[i][j]) { - j--; - } else if (target > matrix[i][j]) { - i++; - } else { - return true; - } - } - return false; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/SerializeAndDeserializeBST.java b/amazon/src/main/java/com/leetcode/amazon/SerializeAndDeserializeBST.java deleted file mode 100644 index 16e9ff3..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/SerializeAndDeserializeBST.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.Queue; - -/** - * Created by liwentian on 17/8/12. - */ - -public class SerializeAndDeserializeBST { - - // Encodes a tree to a single string. - public String serialize(TreeNode root) { - if (root == null) { - return "X"; - } - - return root.val + "," + serialize(root.left) + "," + serialize(root.right); - } - - // Decodes your encoded data to tree. - public TreeNode deserialize(String data) { - String[] texts = data.split(","); - Queue queue = new LinkedList<>(Arrays.asList(texts)); - return helper(queue); - } - - private TreeNode helper(Queue queue) { - if (queue.isEmpty()) { - return null; - } - String s = queue.poll(); - if (s.equals("X")) { - return null; - } - TreeNode root = new TreeNode(Integer.parseInt(s)); - root.left = helper(queue); - root.right = helper(queue); - return root; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/SerializeAndDeserializeBinaryTree.java b/amazon/src/main/java/com/leetcode/amazon/SerializeAndDeserializeBinaryTree.java deleted file mode 100644 index e136913..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/SerializeAndDeserializeBinaryTree.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.Queue; - -/** - * Created by dingjikerbo on 2017/8/7. - */ - -public class SerializeAndDeserializeBinaryTree { - - // Encodes a tree to a single string. - public String serialize(TreeNode root) { - if (root == null) { - return "x"; - } - String s = String.valueOf(root.val) + ","; - s += serialize(root.left) + ","; - s += serialize(root.right); - return s; - } - - // Decodes your encoded data to tree. - public TreeNode deserialize(String data) { - String[] texts = data.split(","); - Queue queue = new LinkedList<>(Arrays.asList(texts)); - return helper(queue); - } - - private TreeNode helper(Queue queue) { - if (queue.isEmpty()) { - return null; - } - String s = queue.poll(); - if (s.equals("x")) { - return null; - } - TreeNode root = new TreeNode(Integer.parseInt(s)); - root.left = helper(queue); - root.right = helper(queue); - return root; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/SetMatrixZeroes.java b/amazon/src/main/java/com/leetcode/amazon/SetMatrixZeroes.java deleted file mode 100644 index d103ff9..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/SetMatrixZeroes.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/12. - */ - -public class SetMatrixZeroes { - - public void setZeroes(int[][] matrix) { - if (matrix.length == 0) { - return; - } - - int row = matrix.length, col = matrix[0].length; - - boolean clearRow = false, clearCol = false; - - for (int i = 0; i < col; i++) { - if (matrix[0][i] == 0) { - clearRow = true; - break; - } - } - - for (int i = 0; i < row; i++) { - if (matrix[i][0] == 0) { - clearCol = true; - break; - } - } - - for (int i = 1; i < row; i++) { - for (int j = 1; j < col; j++) { - if (matrix[i][j] == 0) { - matrix[0][j] = 0; - matrix[i][0] = 0; - } - } - } - - for (int i = 1; i < col; i++) { - if (matrix[0][i] == 0) { - for (int j = 0; j < row; j++) { - matrix[j][i] = 0; - } - } - } - - for (int i = 1; i < row; i++) { - if (matrix[i][0] == 0) { - for (int j = 0; j < col; j++) { - matrix[i][j] = 0; - } - } - } - - if (clearRow) { - for (int i = 0; i < col; i++) { - matrix[0][i] = 0; - } - } - - if (clearCol) { - for (int i = 0; i < row; i++) { - matrix[i][0] = 0; - } - } - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/SlidingWindowMaximum.java b/amazon/src/main/java/com/leetcode/amazon/SlidingWindowMaximum.java deleted file mode 100644 index 94fa163..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/SlidingWindowMaximum.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.leetcode.amazon; - -import java.util.Comparator; -import java.util.TreeMap; - -/** - * Created by liwentian on 17/8/10. - */ - -public class SlidingWindowMaximum { - - public int[] maxSlidingWindow(int[] nums, int k) { - if (nums.length == 0) { - return new int[0]; - } - - TreeMap map = new TreeMap<>(new Comparator() { - @Override - public int compare(Integer i1, Integer i2) { - return i2 - i1; - } - }); - - for (int i = 0; i < k; i++) { - map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); - } - - int[] result = new int[nums.length - k + 1]; - result[0] = map.firstKey(); - - for (int i = 1; i < result.length; i++) { - int count = map.getOrDefault(nums[i - 1], 0); - if (count <= 1) { - map.remove(nums[i - 1]); - } else { - map.put(nums[i - 1], count - 1); - } - map.put(nums[i + k - 1], map.getOrDefault(nums[i + k - 1], 0) + 1); - result[i] = map.firstKey(); - } - - return result; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/StringToInteger.java b/amazon/src/main/java/com/leetcode/amazon/StringToInteger.java deleted file mode 100644 index 3982085..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/StringToInteger.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/12. - */ - -public class StringToInteger { - - // 非法字符 - // 前后空格 - // 空字符 - // 正负号 - // 溢出 - public int myAtoi(String str) { - str = str.trim(); - - if (str.isEmpty()) { - return 0; - } - - int sign = 1; - long result = 0; - - int i = 0; - - char c = str.charAt(0); - if (c == '+' || c == '-') { - sign = c == '-' ? -1 : 1; - i++; - } - - for (; i < str.length(); i++) { - c = str.charAt(i); - - if (c >= '0' && c <= '9') { - result = result * 10 + (c - '0'); - - if (result * sign > Integer.MAX_VALUE || result * sign < Integer.MIN_VALUE) { - break; - } - } else { - break; - } - } - - result *= sign; - - if (result > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } else if (result < Integer.MIN_VALUE) { - return Integer.MIN_VALUE; - } else { - return (int) result; - } - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/Subsets.java b/amazon/src/main/java/com/leetcode/amazon/Subsets.java deleted file mode 100644 index a481784..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/Subsets.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.leetcode.amazon; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 17/8/12. - */ - -public class Subsets { - - public List> subsets(int[] nums) { - List> result = new LinkedList<>(); - helper(nums, result, new LinkedList(), 0); - return result; - } - - private void helper(int[] nums, List> result, LinkedList list, int index) { - if (index == nums.length) { - result.add(new LinkedList<>(list)); - return; - } - - list.add(nums[index]); - helper(nums, result, list, index + 1); - list.remove(list.size() - 1); - - helper(nums, result, list, index + 1); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ThirdMaximumNumber.java b/amazon/src/main/java/com/leetcode/amazon/ThirdMaximumNumber.java deleted file mode 100644 index e90e298..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ThirdMaximumNumber.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/12. - */ - -public class ThirdMaximumNumber { - - public int thirdMax(int[] nums) { - int count = 0; - - long first = (long) Integer.MIN_VALUE - 1; - long second = (long) Integer.MIN_VALUE - 1; - long third = (long) Integer.MIN_VALUE - 1; - - for (int n : nums) { - if (n == first || n == second || n == third) { - continue; - } - - if (n > first) { - count++; - third = second; - second = first; - first = n; - } else if (n > second) { - count++; - third = second; - second = n; - } else if (n >= third) { - count++; - third = n; - } - } - - return (int) (count >= 3 ? third : first); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/TrappingRainWater.java b/amazon/src/main/java/com/leetcode/amazon/TrappingRainWater.java deleted file mode 100644 index c899201..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/TrappingRainWater.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/11. - */ - -public class TrappingRainWater { - - public int trap(int[] height) { - int len = height.length; - - if (len == 0) { - return 0; - } - - int[] left = new int[len]; - int[] right = new int[len]; - - left[0] = 0; - right[len - 1] = 0; - - for (int i = 1; i < len; i++) { - left[i] = Math.max(left[i - 1], height[i - 1]); - } - for (int i = len - 2; i>= 0; i--) { - right[i] = Math.max(right[i + 1], height[i + 1]); - } - int sum = 0; - for (int i = 0; i < len; i++) { - int high = Math.min(left[i], right[i]); - if (high > height[i]) { - sum += high - height[i]; - } - } - return sum; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/TwoSum.java b/amazon/src/main/java/com/leetcode/amazon/TwoSum.java deleted file mode 100644 index 10f0ce8..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/TwoSum.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leetcode.amazon; - -import java.util.HashMap; - -/** - * Created by liwentian on 17/8/5. - */ - -public class TwoSum { - - public int[] twoSum(int[] nums, int target) { - HashMap map = new HashMap<>(); - for (int i = 0; i < nums.length; i++) { - map.put(nums[i], i); - } - for (int i = 0; i < nums.length; i++) { - Integer index = map.get(target - nums[i]); - if (index != null && index != i) { - return new int[] { - i, index - }; - } - } - return null; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/TwoSumII.java b/amazon/src/main/java/com/leetcode/amazon/TwoSumII.java deleted file mode 100644 index 9ceaae7..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/TwoSumII.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/5. - */ - -public class TwoSumII { - - public int[] twoSum(int[] numbers, int target) { - for (int i = 0, j = numbers.length - 1; i < j; ) { - int s = numbers[i] + numbers[j]; - if (s > target) { - j--; - } else if (s < target) { - i++; - } else { - return new int[] {i + 1, j + 1}; - } - } - return null; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/TwoSumIII.java b/amazon/src/main/java/com/leetcode/amazon/TwoSumIII.java deleted file mode 100644 index a2cb113..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/TwoSumIII.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.leetcode.amazon; - -import java.util.HashMap; - -/** - * Created by liwentian on 17/8/5. - */ - -/** - * 本题支持相同数存在 - */ -public class TwoSumIII { - - private HashMap mMap; - - public TwoSumIII() { - mMap = new HashMap<>(); - } - - /** Add the number to an internal data structure.. */ - public void add(int number) { - mMap.put(number, mMap.getOrDefault(number, 0) + 1); - } - - /** Find if there exists any pair of numbers which sum is equal to the value. */ - public boolean find(int value) { - for (Integer n : mMap.keySet()) { - int cnt = mMap.getOrDefault(value - n, 0); - if (value - n != n && cnt > 0) { - return true; - } - if (value - n == n && cnt > 1) { - return true; - } - } - return false; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ValidAnagram.java b/amazon/src/main/java/com/leetcode/amazon/ValidAnagram.java deleted file mode 100644 index 6c6d32a..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ValidAnagram.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/11. - */ - -public class ValidAnagram { - - public boolean isAnagram(String s, String t) { - if (s.length() != t.length()) { - return false; - } - int[] count = new int[256]; - for (int i = 0; i < s.length(); i++) { - count[s.charAt(i)]++; - count[t.charAt(i)]--; - } - for (int i = 'a'; i <= 'z'; i++) { - if (count[i] != 0) { - return false; - } - } - return true; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ValidParentheses.java b/amazon/src/main/java/com/leetcode/amazon/ValidParentheses.java deleted file mode 100644 index 2e429b2..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ValidParentheses.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/9. - */ - -public class ValidParentheses { - - public boolean isValid(String s) { - char[] stack = new char[s.length()]; - int top = -1; - - for (char c : s.toCharArray()) { - switch (c) { - case ')': - if (top >= 0 && stack[top] == '(') { - top--; - } else { - return false; - } - break; - case '}': - if (top >= 0 && stack[top] == '{') { - top--; - } else { - return false; - } - break; - case ']': - if (top >= 0 && stack[top] == '[') { - top--; - } else { - return false; - } - break; - default: - stack[++top] = c; - break; - } - } - - return top < 0; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ValidSudoku.java b/amazon/src/main/java/com/leetcode/amazon/ValidSudoku.java deleted file mode 100644 index 9bb195d..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ValidSudoku.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.leetcode.amazon; - -import java.util.Arrays; - -/** - * Created by liwentian on 17/8/14. - */ - -public class ValidSudoku { - - private boolean check(char c, boolean[] f) { - if (c == '.') { - return true; - } - if (f[c - '1']) { - return false; - } - f[c - '1'] = true; - return true; - } - - public boolean isValidSudoku(char[][] board) { - boolean[] f = new boolean[9]; - for (int i = 0; i < 9; i++) { - Arrays.fill(f, false); - for (int j = 0; j < 9; j++) { - if (!check(board[i][j], f)) { - return false; - } - } - } - - for (int i = 0; i < 9; i++) { - Arrays.fill(f, false); - for (int j = 0; j < 9; j++) { - if (!check(board[j][i], f)) { - return false; - } - } - } - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - Arrays.fill(f, false); - for (int m = 0; m < 3; m++) { - for (int n = 0; n < 3; n++) { - int x = i * 3 + m, y = j * 3 + n; - if (!check(board[x][y], f)) { - return false; - } - } - } - } - } - return true; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/ValidateBinarySearchTree.java b/amazon/src/main/java/com/leetcode/amazon/ValidateBinarySearchTree.java deleted file mode 100644 index 9975996..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/ValidateBinarySearchTree.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - -/** - * Created by liwentian on 17/8/11. - */ - -public class ValidateBinarySearchTree { - - public boolean isValidBST(TreeNode root) { - return isValidBST(root, (long) Integer.MIN_VALUE - 1, (long) Integer.MAX_VALUE + 1); - } - - private boolean isValidBST(TreeNode root, long lower, long upper) { - if (root == null) { - return true; - } - return root.val > lower && root.val < upper - && isValidBST(root.left, lower, root.val) - && isValidBST(root.right, root.val, upper); - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/WordBreak.java b/amazon/src/main/java/com/leetcode/amazon/WordBreak.java deleted file mode 100644 index a83b175..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/WordBreak.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leetcode.amazon; - -import java.util.List; - -/** - * Created by liwentian on 17/8/13. - */ - -public class WordBreak { - - public boolean wordBreak(String s, List wordDict) { - boolean[] f = new boolean[s.length() + 1]; - f[0] = true; - - for (int i = 1; i <= s.length(); i++) { - for (int j = 0; j < i; j++) { - if (f[j] && wordDict.contains(s.substring(j, i))) { - f[i] = true; - break; - } - } - } - - return f[s.length()]; - } -} diff --git a/amazon/src/main/java/com/leetcode/amazon/WordLadder.java b/amazon/src/main/java/com/leetcode/amazon/WordLadder.java deleted file mode 100644 index edec35c..0000000 --- a/amazon/src/main/java/com/leetcode/amazon/WordLadder.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.leetcode.amazon; - -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -/** - * Created by liwentian on 17/8/10. - */ - -public class WordLadder { - - public int ladderLength(String beginWord, String endWord, List wordList) { - Queue queue = new LinkedList<>(); - Queue next = new LinkedList<>(); - - queue.add(beginWord); - - int level = 1; - - while (!queue.isEmpty()) { - String word = queue.poll(); - - for (int i = 0; i < word.length(); i++) { - for (char c = 'a'; c <= 'z'; c++) { - if (c == word.charAt(i)) { - continue; - } - String s = word.substring(0, i) + c + word.substring(i + 1); - - if (s.equals(endWord)) { - return level + 1; - } - - if (wordList.contains(s)) { - wordList.remove(s); - System.out.println(String.format("level %d, add %s", level, s)); - next.add(s); - } - } - } - - if (queue.isEmpty()) { - level++; - queue.addAll(next); - next.clear(); - } - } - - return 0; - } -} diff --git a/app/.gitignore b/app/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/app/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/app/build.gradle b/app/build.gradle deleted file mode 100644 index 532a5a6..0000000 --- a/app/build.gradle +++ /dev/null @@ -1,28 +0,0 @@ -apply plugin: 'com.android.application' - -android { - compileSdkVersion 24 - buildToolsVersion '26.0.2' - defaultConfig { - applicationId "com.inuker.leetcode" - minSdkVersion 18 - targetSdkVersion 24 - versionCode 1 - versionName "1.0" - testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" - } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } -} - -dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { - exclude group: 'com.android.support', module: 'support-annotations' - }) - testCompile 'junit:junit:4.12' -} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro deleted file mode 100644 index 07d416a..0000000 --- a/app/proguard-rules.pro +++ /dev/null @@ -1,17 +0,0 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in D:\android\sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/app/src/androidTest/java/com/inuker/leetcode/ExampleInstrumentedTest.java b/app/src/androidTest/java/com/inuker/leetcode/ExampleInstrumentedTest.java deleted file mode 100644 index add180a..0000000 --- a/app/src/androidTest/java/com/inuker/leetcode/ExampleInstrumentedTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.inuker.leetcode; - -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.runner.AndroidJUnit4; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - -/** - * Instrumentation test, which will execute on an Android device. - * - * @see Testing documentation - */ -@RunWith(AndroidJUnit4.class) -public class ExampleInstrumentedTest { - @Test - public void useAppContext() throws Exception { - // Context of the app under test. - Context appContext = InstrumentationRegistry.getTargetContext(); - - assertEquals("com.inuker.leetcode", appContext.getPackageName()); - } -} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml deleted file mode 100644 index 74f2694..0000000 --- a/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/java/com/inuker/leetcode/MainActivity.java b/app/src/main/java/com/inuker/leetcode/MainActivity.java deleted file mode 100644 index 3a9ccca..0000000 --- a/app/src/main/java/com/inuker/leetcode/MainActivity.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.inuker.leetcode; - -import android.app.Activity; -import android.os.Bundle; - -import java.util.concurrent.DelayQueue; - -public class MainActivity extends Activity { - - private DelayQueue - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - } -} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml deleted file mode 100644 index 0694e9a..0000000 --- a/app/src/main/res/layout/activity_main.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png deleted file mode 100644 index cde69bc..0000000 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher.png and /dev/null differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png deleted file mode 100644 index c133a0c..0000000 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher.png and /dev/null differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png deleted file mode 100644 index bfa42f0..0000000 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher.png and /dev/null differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png deleted file mode 100644 index 324e72c..0000000 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and /dev/null differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png deleted file mode 100644 index aee44e1..0000000 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and /dev/null differ diff --git a/app/src/main/res/values-w820dp/dimens.xml b/app/src/main/res/values-w820dp/dimens.xml deleted file mode 100644 index 63fc816..0000000 --- a/app/src/main/res/values-w820dp/dimens.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - 64dp - diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml deleted file mode 100644 index 3ab3e9c..0000000 --- a/app/src/main/res/values/colors.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - #3F51B5 - #303F9F - #FF4081 - diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml deleted file mode 100644 index 47c8224..0000000 --- a/app/src/main/res/values/dimens.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - 16dp - 16dp - diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml deleted file mode 100644 index 3577d86..0000000 --- a/app/src/main/res/values/strings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - leetcode - diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml deleted file mode 100644 index ff6c9d2..0000000 --- a/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - diff --git a/app/src/test/java/com/inuker/leetcode/ExampleUnitTest.java b/app/src/test/java/com/inuker/leetcode/ExampleUnitTest.java deleted file mode 100644 index b79e122..0000000 --- a/app/src/test/java/com/inuker/leetcode/ExampleUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.inuker.leetcode; - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Example local unit test, which will execute on the development machine (host). - * - * @see Testing documentation - */ -public class ExampleUnitTest { - @Test - public void addition_isCorrect() throws Exception { - assertEquals(4, 2 + 2); - } -} \ No newline at end of file diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 19ccc6c..0000000 --- a/build.gradle +++ /dev/null @@ -1,25 +0,0 @@ -// Top-level build file where you can add configuration options common to all sub-projects/modules. - -buildscript { - repositories { - jcenter() - maven { url 'https://maven.google.com' } - } - dependencies { - classpath 'com.android.tools.build:gradle:3.0.0' - - // NOTE: Do not place your application dependencies here; they belong - // in the individual module build.gradle files - } -} - -allprojects { - repositories { - jcenter() - maven { url 'https://maven.google.com' } - } -} - -task clean(type: Delete) { - delete rootProject.buildDir -} diff --git a/doc/.DS_Store b/doc/.DS_Store deleted file mode 100644 index af8dfbe..0000000 Binary files a/doc/.DS_Store and /dev/null differ diff --git a/doc/Attention.md b/doc/Attention.md index 80997c1..4f3a6e0 100644 --- a/doc/Attention.md +++ b/doc/Attention.md @@ -96,6 +96,6 @@ return -1; 不能直接写return o1 > o2 ? 1 : -1; 因为可能存在重复的数,在TreeMap中查找key时通过comparator等于0,上述写法导致永远找不到key。 -三十,StringBuilder的insert(0, c)不要频繁调用,不如append,最后reverse。 +三十,StringBuilder的insert(0, c)不要频繁调用,看源码要array copy,性能很差。不如append,最后reverse。 三十一,List在allAll一个PriorityQueue时,是不会带顺序的,正确的做法是while(!queue.isEmpty()) {list.add(queue.poll());} \ No newline at end of file diff --git a/ebook/.DS_Store b/ebook/.DS_Store index f67cd4f..b10b743 100644 Binary files a/ebook/.DS_Store and b/ebook/.DS_Store differ diff --git a/extras.md b/extras.md new file mode 100644 index 0000000..afee170 --- /dev/null +++ b/extras.md @@ -0,0 +1,5 @@ +# 其它题目 + +### Google + - [Remove consecutive node from single list](leetcode/solution/src/RemoveDuplicateList.java) + - [Reverse pairs](leetcode/solution/src/CountReversePairs.java) \ No newline at end of file diff --git a/facebook/.gitignore b/facebook/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/facebook/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/facebook/build.gradle b/facebook/build.gradle deleted file mode 100644 index 7ab6e83..0000000 --- a/facebook/build.gradle +++ /dev/null @@ -1,9 +0,0 @@ -apply plugin: 'java' - -dependencies { - compile fileTree(include: ['*.jar'], dir: 'libs') - compile project(':library') -} - -sourceCompatibility = "1.7" -targetCompatibility = "1.7" diff --git a/facebook/facebook.iml b/facebook/facebook.iml deleted file mode 100644 index 4b0be58..0000000 --- a/facebook/facebook.iml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/facebook/src/main/java/com/leetcode/facebook/AddAndSearchWord.java b/facebook/src/main/java/com/leetcode/facebook/AddAndSearchWord.java deleted file mode 100644 index 92cb5fc..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/AddAndSearchWord.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/18. - */ - -public class AddAndSearchWord { - - TriNode root; - - public AddAndSearchWord() { - root = new TriNode(); - } - - /** - * Adds a word into the data structure. - */ - public void addWord(String word) { - TriNode node = root; - for (char c : word.toCharArray()) { - if (node.nodes[c - 'a'] == null) { - node.nodes[c - 'a'] = new TriNode(); - } - node = node.nodes[c - 'a']; - } - node.word = word; - } - - /** - * Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. - */ - public boolean search(String word) { - return search(root, word); - } - - private boolean search(TriNode node, String word) { - if (node == null) { - return false; - } - - for (int i = 0; i < word.length(); i++) { - char c = word.charAt(i); - - if (c != '.') { - if (node.nodes[c - 'a'] == null) { - return false; - } - node = node.nodes[c - 'a']; - } else { - String s = word.substring(i + 1); - for (char cc = 'a'; cc <= 'z'; cc++) { - if (search(node.nodes[cc - 'a'], s)) { - return true; - } - } - return false; - } - } - - return node.word != null; - } - - class TriNode { - TriNode[] nodes = new TriNode[26]; - String word; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/AddBinary.java b/facebook/src/main/java/com/leetcode/facebook/AddBinary.java deleted file mode 100644 index e8e6085..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/AddBinary.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/17. - */ - -public class AddBinary { - - public String addBinary(String a, String b) { - StringBuilder sb = new StringBuilder(); - - int flag = 0; - for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0 || flag > 0; i--, j--) { - int a1 = i >= 0 ? a.charAt(i) - '0' : 0; - int a2 = j >= 0 ? b.charAt(j) - '0' : 0; - int sum = a1 + a2 + flag; - sb.insert(0, sum & 1); - flag = sum >> 1; - } - - return sb.toString(); - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/BinarySearchTreeIterator.java b/facebook/src/main/java/com/leetcode/facebook/BinarySearchTreeIterator.java deleted file mode 100644 index a0e8bca..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/BinarySearchTreeIterator.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.leetcode.facebook; - -import com.leetcode.library.TreeNode; - -import java.util.Stack; - -/** - * Created by liwentian on 17/8/18. - */ - -public class BinarySearchTreeIterator { - - Stack stack; - - TreeNode node; - - public BinarySearchTreeIterator(TreeNode root) { - stack = new Stack<>(); - node = root; - } - - /** @return whether we have a next smallest number */ - public boolean hasNext() { - return !stack.isEmpty() || node != null; - } - - /** @return the next smallest number */ - public int next() { - while (hasNext()) { - if (node != null) { - stack.push(node); - node = node.left; - } else { - node = stack.pop(); - int val = node.val; - node = node.right; - return val; - } - } - throw new IllegalStateException(); - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/BinaryTreePaths.java b/facebook/src/main/java/com/leetcode/facebook/BinaryTreePaths.java deleted file mode 100644 index 3a4ccc3..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/BinaryTreePaths.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.leetcode.facebook; - -import com.leetcode.library.TreeNode; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 17/8/18. - */ - -public class BinaryTreePaths { - - public List binaryTreePaths(TreeNode root) { - List list = new LinkedList<>(); - helper(root, list, ""); - return list; - } - - private void helper(TreeNode root, List list, String s) { - if (root == null) { - return; - } - - s += (s.isEmpty() ? "" : "->") + root.val; - - if (root.left == null && root.right == null) { - list.add(s); - return; - } - - helper(root.left, list, s); - helper(root.right, list, s); - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/DecodeWays.java b/facebook/src/main/java/com/leetcode/facebook/DecodeWays.java deleted file mode 100644 index e3bbd17..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/DecodeWays.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.leetcode.facebook; - -import java.util.Arrays; - -/** - * Created by liwentian on 17/8/17. - */ - -public class DecodeWays { - - public int numDecodings(String s) { - if (s.length() == 0) { - return 0; - } - int[] f = new int[s.length()]; - Arrays.fill(f, -1); - return helper(s.toCharArray(), f, 0); - } - - private int helper(char[] s, int[] f, int i) { - if (i >= s.length) { - return 1; - } - - if (s[i] == '0') { - return 0; - } - - if (f[i] >= 0) { - return f[i]; - } - - int sum = helper(s, f, i + 1); - - if (i + 1 < s.length && (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '6'))) { - sum += helper(s, f, i + 2); - } - - f[i] = sum; - - return sum; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/FindTheCelebrity.java b/facebook/src/main/java/com/leetcode/facebook/FindTheCelebrity.java deleted file mode 100644 index 0709861..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/FindTheCelebrity.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/17. - */ - -public class FindTheCelebrity { - - public int findCelebrity(int n) { - int id = 0; - for (int i = 1; i < n; i++) { - if (knows(id, i)) { - id = i; - } - } - for (int i = 0; i < n; i++) { - if (i == id) { - continue; - } - if (knows(id, i) || !knows(i, id)) { - return -1; - } - } - return id; - } - - boolean knows(int a, int b) { - return false; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/FirstBadVersion.java b/facebook/src/main/java/com/leetcode/facebook/FirstBadVersion.java deleted file mode 100644 index 9dffc1f..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/FirstBadVersion.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/17. - */ - -public class FirstBadVersion { - - public int firstBadVersion(int n) { - int left = 1, right = n; - - while (left <= right) { - int mid = left + ((right - left) >> 1); - - if (isBadVersion(mid)) { - right = mid - 1; - } else { - left = mid + 1; - } - } - - return left; - } - - boolean isBadVersion(int version) { - return false; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/FlattenNestedListIterator.java b/facebook/src/main/java/com/leetcode/facebook/FlattenNestedListIterator.java deleted file mode 100644 index 54b87c3..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/FlattenNestedListIterator.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.leetcode.facebook; - -import com.leetcode.library.NestedInteger; - -import java.util.Iterator; -import java.util.List; -import java.util.Stack; - -/** - * Created by liwentian on 17/8/18. - */ - -public class FlattenNestedListIterator implements Iterator { - - private Stack stack; - - public FlattenNestedListIterator(List nestedList) { - stack = new Stack(); - push(nestedList); - } - - private void push(List nestedList) { - for (int i = nestedList.size() - 1; i >= 0; i--) { - NestedInteger nest = nestedList.get(i); - if (nest.isInteger()) { - stack.push(nest); - } else { - push(nest.getList()); - } - } - } - - @Override - public Integer next() { - return stack.pop().getInteger(); - } - - @Override - public boolean hasNext() { - return !stack.isEmpty(); - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/ImplementTrie.java b/facebook/src/main/java/com/leetcode/facebook/ImplementTrie.java deleted file mode 100644 index 5f451af..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/ImplementTrie.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/18. - * https://leetcode.com/articles/implement-trie-prefix-tree/ - */ - -public class ImplementTrie { - - class TriNode { - TriNode[] nodes = new TriNode[26]; - String word; - } - - TriNode root; - - /** Initialize your data structure here. */ - public ImplementTrie() { - root = new TriNode(); - } - - /** Inserts a word into the trie. */ - public void insert(String word) { - TriNode node = root; - for (char c : word.toCharArray()) { - if (node.nodes[c - 'a'] == null) { - node.nodes[c - 'a'] = new TriNode(); - } - node = node.nodes[c - 'a']; - } - node.word = word; - } - - /** Returns if the word is in the trie. */ - public boolean search(String word) { - TriNode node = root; - for (char c : word.toCharArray()) { - if (node.nodes[c - 'a'] == null) { - return false; - } - node = node.nodes[c - 'a']; - } - return word.equals(node.word); - } - - /** Returns if there is any word in the trie that starts with the given prefix. */ - public boolean startsWith(String prefix) { - TriNode node = root; - for (char c : prefix.toCharArray()) { - if (node.nodes[c - 'a'] == null) { - return false; - } - node = node.nodes[c - 'a']; - } - return true; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/InorderSuccessorInBST.java b/facebook/src/main/java/com/leetcode/facebook/InorderSuccessorInBST.java deleted file mode 100644 index 1d6584f..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/InorderSuccessorInBST.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.leetcode.facebook; - -import com.leetcode.library.TreeNode; - -/** - * Created by liwentian on 17/8/18. - */ - -public class InorderSuccessorInBST { - - public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { - TreeNode node = null; - while (root != null) { - if (p.val >= root.val) { - root = root.right; - } else if (p.val < root.val) { - node = root; - root = root.left; - } - } - return node; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/IntegerToEnglishWords.java b/facebook/src/main/java/com/leetcode/facebook/IntegerToEnglishWords.java deleted file mode 100644 index 35e4364..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/IntegerToEnglishWords.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/18. - */ - -public class IntegerToEnglishWords { - - private final String[] LESS_20 = { - "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", - "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" - }; - - private final String[] LESS_100 = { - "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" - }; - - private final String[] THOUSANDS = { - "", "Thousand", "Million", "Billion" - }; - - public String numberToWords(int num) { - if (num == 0) { - return "Zero"; - } - - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < THOUSANDS.length && num > 0; i++) { - if (num % 1000 > 0) { - sb.insert(0, helper(num % 1000).trim() + " " + THOUSANDS[i] + " "); - } - - num /= 1000; - } - - return sb.toString().trim(); - } - - private String helper(int num) { - if (num < 20) { - return LESS_20[num]; - } else if (num < 100) { - return LESS_100[num / 10] + " " + helper(num % 10); - } else { - return LESS_20[num / 100] + " Hundred " + helper(num % 100); - } - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/MaximumSizeSubarraySumEqualsk.java b/facebook/src/main/java/com/leetcode/facebook/MaximumSizeSubarraySumEqualsk.java deleted file mode 100644 index 0b2a04a..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/MaximumSizeSubarraySumEqualsk.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.leetcode.facebook; - -import java.util.HashMap; - -/** - * Created by liwentian on 17/8/17. - */ - -public class MaximumSizeSubarraySumEqualsk { - - public int maxSubArrayLen(int[] nums, int k) { - HashMap map = new HashMap<>(); - int maxLen = 0; - - map.put(0, -1); - - for (int i = 0, sum = 0; i < nums.length; i++) { - sum += nums[i]; - if (!map.containsKey(sum)) { - map.put(sum, i); - } - - int idx = map.getOrDefault(sum - k, -2); - if (idx >= -1 && i - idx > maxLen) { - maxLen = i - idx; - } - } - - return maxLen; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/MinimalRuntimeScheduler.java b/facebook/src/main/java/com/leetcode/facebook/MinimalRuntimeScheduler.java deleted file mode 100644 index 4b6145c..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/MinimalRuntimeScheduler.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by dingjikerbo on 17/1/6. - */ - -/** - * https://discuss.leetcode.com/topic/112/minimal-run-time-scheduler - * 与358 [Rearrange String k Distance Apart]比较类似 - */ -public class MinimalRuntimeScheduler { - - -} diff --git a/facebook/src/main/java/com/leetcode/facebook/MoveZeroes.java b/facebook/src/main/java/com/leetcode/facebook/MoveZeroes.java deleted file mode 100644 index 68a6fde..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/MoveZeroes.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/17. - */ - -public class MoveZeroes { - - public void moveZeroes(int[] nums) { - for (int i = 0, j = 0; j < nums.length; j++) { - if (nums[j] != 0) { - swap(nums, i++, j); - } - } - } - - private void swap(int[] nums, int i, int j) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/ReadNCharactersGivenRead4.java b/facebook/src/main/java/com/leetcode/facebook/ReadNCharactersGivenRead4.java deleted file mode 100644 index e4cba8d..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/ReadNCharactersGivenRead4.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/17. - */ - -public class ReadNCharactersGivenRead4 { - - public int read(char[] buf, int n) { - char[] tmp = new char[4]; - - int i = 0; - for ( ; i < n; i++) { - int size = read4(tmp); - for (int j = 0; j < size && i < n; ) { - buf[i++] = tmp[j++]; - } - if (size < 4) { - break; - } - } - - return i; - } - - int read4(char[] buf) { - return 0; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/ReadNCharactersGivenRead4II.java b/facebook/src/main/java/com/leetcode/facebook/ReadNCharactersGivenRead4II.java deleted file mode 100644 index 3cc8557..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/ReadNCharactersGivenRead4II.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/17. - */ - -public class ReadNCharactersGivenRead4II { - - int idx = 0, size = 0; - char[] tmp = new char[4]; - - public int read(char[] buf, int n) { - int i = 0; - - for ( ; i < n; ) { - if (idx >= size) { - size = read4(tmp); - idx = 0; - } - - for ( ; idx < size && i < n; ) { - buf[i++] = tmp[idx++]; - } - - if (size < 4) { - break; - } - } - - return i; - } - - int read4(char[] buf) { - return 0; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/RegularExpressionMatching.java b/facebook/src/main/java/com/leetcode/facebook/RegularExpressionMatching.java deleted file mode 100644 index 6105c83..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/RegularExpressionMatching.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/18. - */ - -public class RegularExpressionMatching { - - public boolean isMatch(String s, String p) { - if (p.isEmpty()) { - return s.isEmpty(); - } else if (p.length() == 1) { - return s.length() == 1 && isEquals(s, p); - } else if (p.charAt(1) != '*') { - return s.length() > 0 && isEquals(s, p) && isMatch(s.substring(1), p.substring(1)); - } else { - if (s.length() > 0 && isEquals(s, p)) { - return isMatch(s, p.substring(2)) || isMatch(s.substring(1), p); - } else { - return isMatch(s, p.substring(2)); - } - } - } - - private boolean isEquals(String s, String p) { - return s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/RemoveInvalidParentheses.java b/facebook/src/main/java/com/leetcode/facebook/RemoveInvalidParentheses.java deleted file mode 100644 index 816d18a..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/RemoveInvalidParentheses.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.leetcode.facebook; - -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 17/8/17. - */ - -public class RemoveInvalidParentheses { - - public List removeInvalidParentheses(String s) { - HashSet set = new HashSet<>(); - - int nL = 0, nR = 0; - for (char c : s.toCharArray()) { - if (c == '(') { - nL++; - } else if (c == ')') { - if (nL > 0) { - nL--; - } else { - nR++; - } - } - } - - dfs(s, "", set, 0, nL, nR, 0); - return new LinkedList<>(set); - } - - private void dfs(String s, String t, HashSet set, int i, int nL, int nR, int count) { - if (nL < 0 || nR < 0 || count < 0) { - return; - } - if (i == s.length()) { - if (nL == 0 && nR == 0 && count == 0) { - set.add(t); - } - return; - } - char c = s.charAt(i); - if (c == '(') { - dfs(s, t, set, i + 1, nL - 1, nR, count); - dfs(s, t + "(", set, i + 1, nL, nR, count + 1); - } else if (c == ')') { - dfs(s, t, set, i + 1, nL, nR - 1, count); - dfs(s, t + ")", set, i + 1, nL, nR, count - 1); - } else { - dfs(s, t + c, set, i + 1, nL, nR, count); - } - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/SortColors.java b/facebook/src/main/java/com/leetcode/facebook/SortColors.java deleted file mode 100644 index aff54f6..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/SortColors.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/18. - */ - -public class SortColors { - - public void sortColors(int[] nums) { - int zero = -1, two = nums.length; - for (int i = 0; i < two; ) { - if (nums[i] == 0) { - swap(nums, ++zero, i); - } else if (nums[i] == 2) { - swap(nums, --two, i); - } else { - i++; - } - } - } - - private void swap(int[] nums, int i, int j) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/SparseMatrixMultiplication.java b/facebook/src/main/java/com/leetcode/facebook/SparseMatrixMultiplication.java deleted file mode 100644 index 4a609f5..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/SparseMatrixMultiplication.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/17. - */ - -public class SparseMatrixMultiplication { - - public int[][] multiply(int[][] A, int[][] B) { - int[][] C = new int[A.length][B[0].length]; - - for (int i = 0; i < A.length; i++) { - for (int k = 0; k < A[0].length; k++) { - if (A[i][k] != 0) { - for (int j = 0; j < B[0].length; j++) { - C[i][j] += A[i][k] * B[k][j]; - } - } - } - } - - return C; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/ValidPalindrome.java b/facebook/src/main/java/com/leetcode/facebook/ValidPalindrome.java deleted file mode 100644 index 6a381c6..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/ValidPalindrome.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/18. - */ - -public class ValidPalindrome { - - public boolean isPalindrome(String s) { - if (s.isEmpty()) { - return true; - } - - for (int i = 0, j = s.length() - 1; i < j; ) { - if (!Character.isLetterOrDigit(s.charAt(i))) { - i++; - } else if (!Character.isLetterOrDigit(s.charAt(j))) { - j--; - } else if (Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))) { - i++; - j--; - } else { - return false; - } - } - - return true; - } -} diff --git a/facebook/src/main/java/com/leetcode/facebook/WildcardMatching.java b/facebook/src/main/java/com/leetcode/facebook/WildcardMatching.java deleted file mode 100644 index 3d7305e..0000000 --- a/facebook/src/main/java/com/leetcode/facebook/WildcardMatching.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.leetcode.facebook; - -/** - * Created by liwentian on 17/8/18. - */ - -public class WildcardMatching { - - public boolean isMatch(String s, String p) { - int is = 0, ip = 0, ks = -1, kp = -1; - - while (is < s.length()) { - if (ip < p.length() && (s.charAt(is) == p.charAt(ip) || p.charAt(ip) == '?')) { - is++; - ip++; - } else if (ip < p.length() && p.charAt(ip) == '*') { - ks = is; - kp = ip++; - } else if (ks != -1) { - is = ++ks; - ip = kp + 1; - } else { - return false; - } - } - - for ( ; ip < p.length() && p.charAt(ip) == '*'; ip++); - - return ip == p.length(); - } -} diff --git a/google/.gitignore b/google/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/google/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/google/RECORDS.md b/google/RECORDS.md deleted file mode 100644 index 265e96f..0000000 --- a/google/RECORDS.md +++ /dev/null @@ -1,22 +0,0 @@ -2017-9-4 -140. Word Break II - - - -2017-9-3 - -310. Minimum Height Trees -399. Evaluate Division -261. Graph Valid Tree -323. Number of Connected Components in an Undirected Graph -10. Regular Expression Matching -17. Letter Combinations of a Phone Number -22. Generate Parentheses -139. Word Break - -2017-9-2 -329. Longest Increasing Path in a Matrix -133. Clone Graph -269. Alien Dictionary -207. Course Schedule -210. Course Schedule II \ No newline at end of file diff --git a/google/build.gradle b/google/build.gradle deleted file mode 100644 index 5bb4b31..0000000 --- a/google/build.gradle +++ /dev/null @@ -1,9 +0,0 @@ -apply plugin: 'java' - -dependencies { - compile fileTree(include: ['*.jar'], dir: 'libs') - compile project(':library') -} - -sourceCompatibility = "1.8" -targetCompatibility = "1.8" diff --git a/google/google.iml b/google/google.iml deleted file mode 100644 index 9652e06..0000000 --- a/google/google.iml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/google/src/main/java/com/leetcode/google/AlienDictionary.java b/google/src/main/java/com/leetcode/google/AlienDictionary.java deleted file mode 100644 index f250a4b..0000000 --- a/google/src/main/java/com/leetcode/google/AlienDictionary.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.leetcode.google; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Set; - -/** - * Created by liwentian on 2017/9/2. - */ - -public class AlienDictionary { - - public String alienOrder(String[] words) { - HashMap> map = new HashMap<>(); - - int[] indegrees = new int[26]; - Arrays.fill(indegrees, -1); - - int count = 0; - for (String word : words) { - for (char c : word.toCharArray()) { - if (indegrees[c - 'a'] != 0) { - indegrees[c - 'a'] = 0; - count++; - } - } - } - - for (int i = 0; i < words.length - 1; i++) { - String prev = words[i], next = words[i + 1]; - - for (int j = 0; j < prev.length() && j < next.length(); j++) { - char c1 = prev.charAt(j), c2 = next.charAt(j); - - if (c1 != c2) { - Set set = map.get(c1); - if (set == null) { - set = new HashSet<>(); - map.put(c1, set); - } - if (set.add(c2)) { - indegrees[c2 - 'a']++; - } - break; - } else { - if (j + 1 < prev.length() && j + 1 >= next.length()) { - return ""; - } - } - } - } - - Queue queue = new LinkedList<>(); - for (char c = 'a'; c <= 'z'; c++) { - if (indegrees[c - 'a'] == 0) { - queue.add(c); - } - } - - StringBuilder sb = new StringBuilder(); - - while (!queue.isEmpty()) { - char c = queue.poll(); - sb.append(c); - - Set set = map.get(c); - if (set != null) { - for (char cc : set) { - if (--indegrees[cc - 'a'] == 0) { - queue.add(cc); - } - } - } - } - - if (sb.length() != count) { - return ""; - } - - return sb.toString(); - } -} diff --git a/google/src/main/java/com/leetcode/google/BinaryTreeLongestConsecutiveSequence.java b/google/src/main/java/com/leetcode/google/BinaryTreeLongestConsecutiveSequence.java deleted file mode 100644 index dc9af48..0000000 --- a/google/src/main/java/com/leetcode/google/BinaryTreeLongestConsecutiveSequence.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.leetcode.google; - -import com.leetcode.library.TreeNode; - -/** - * Created by liwentian on 17/8/26. - */ - -public class BinaryTreeLongestConsecutiveSequence { - - private int mMaxLen; - - public int longestConsecutive(TreeNode root) { - helper(root, 1); - return mMaxLen; - } - - private void helper(TreeNode node, int len) { - if (node == null) { - return; - } - - mMaxLen = Math.max(len, mMaxLen); - - if (node.left != null) { - helper(node.left, 1 + (node.left.val == node.val + 1 ? len : 0)); - } - - if (node.right != null) { - helper(node.right, 1 + (node.right.val == node.val + 1 ? len : 0)); - } - } -} diff --git a/google/src/main/java/com/leetcode/google/BombEnemy.java b/google/src/main/java/com/leetcode/google/BombEnemy.java deleted file mode 100644 index 0282fd7..0000000 --- a/google/src/main/java/com/leetcode/google/BombEnemy.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/26. - */ - -public class BombEnemy { - - public int maxKilledEnemies(char[][] grid) { - if (grid.length == 0) { - return 0; - } - int m = grid.length, n = grid[0].length; - - int rowHits = 0, result = 0; - int[] colHits = new int[n]; - - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (grid[i][j] == 'W') { - continue; - } - - if (j == 0 || grid[i][j - 1] == 'W') { - rowHits = 0; - for (int k = j; k < n && grid[i][k] != 'W'; k++) { - if (grid[i][k] == 'E') { - rowHits++; - } - } - } - - if (i == 0 || grid[i - 1][j] == 'W') { - colHits[j] = 0; - for (int k = i; k < m && grid[k][j] != 'W'; k++) { - if (grid[k][j] == 'E') { - colHits[j]++; - } - } - } - - if (grid[i][j] == '0') { - result = Math.max(result, rowHits + colHits[j]); - } - } - } - - return result; - } -} diff --git a/google/src/main/java/com/leetcode/google/CloneGraph.java b/google/src/main/java/com/leetcode/google/CloneGraph.java deleted file mode 100644 index 023489c..0000000 --- a/google/src/main/java/com/leetcode/google/CloneGraph.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.leetcode.google; - -import com.leetcode.library.UndirectedGraphNode; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Queue; - -/** - * Created by liwentian on 2017/9/2. - */ - -public class CloneGraph { - -// public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { -// return dfs(node, new HashMap<>()); -// } -// -// private UndirectedGraphNode dfs(UndirectedGraphNode node, HashMap map) { -// if (node == null) { -// return null; -// } -// if (map.containsKey(node)) { -// return map.get(node); -// } -// -// UndirectedGraphNode copy = new UndirectedGraphNode(node.label); -// map.put(node, copy); -// -// for (UndirectedGraphNode child : node.neighbors) { -// UndirectedGraphNode childCopy = dfs(child, map); -// copy.neighbors.add(childCopy); -// } -// -// return copy; -// } - - public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { - if (node == null) { - return null; - } - - HashMap map = new HashMap<>(); - - UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); - map.put(node, newNode); - - Queue queue = new LinkedList<>(); - queue.add(node); - - while (!queue.isEmpty()) { - UndirectedGraphNode node1 = queue.poll(); - UndirectedGraphNode cloned = map.get(node1); - - for (UndirectedGraphNode p : node1.neighbors) { - if (!map.containsKey(p)) { - map.put(p, new UndirectedGraphNode(p.label)); - queue.add(p); - } - cloned.neighbors.add(map.get(p)); - } - } - - return newNode; - } -} diff --git a/google/src/main/java/com/leetcode/google/CourseSchedule.java b/google/src/main/java/com/leetcode/google/CourseSchedule.java deleted file mode 100644 index edf4d7c..0000000 --- a/google/src/main/java/com/leetcode/google/CourseSchedule.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.leetcode.google; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.Set; - -/** - * Created by liwentian on 2017/9/2. - */ - -public class CourseSchedule { - - public boolean canFinish(int numCourses, int[][] prerequisites) { - HashMap> map = new HashMap<>(); - int[] indegrees = new int[numCourses]; - - for (int[] prerequisite : prerequisites) { - int from = prerequisite[0], to = prerequisite[1]; - Set set = map.get(from); - if (set == null) { - set = new HashSet<>(); - map.put(from, set); - } - if (set.add(to)) { - indegrees[to]++; - } - } - Queue queue = new LinkedList<>(); - for (int i = 0; i < numCourses; i++) { - if (indegrees[i] == 0) { - queue.add(i); - } - } - List list = new LinkedList<>(); - while (!queue.isEmpty()) { - int n = queue.poll(); - list.add(n); - - Set set = map.get(n); - if (set != null) { - for (Integer k : set) { - if (--indegrees[k] == 0) { - queue.offer(k); - } - } - } - } - - return list.size() == numCourses; - } -} diff --git a/google/src/main/java/com/leetcode/google/CourseScheduleII.java b/google/src/main/java/com/leetcode/google/CourseScheduleII.java deleted file mode 100644 index 9eea38a..0000000 --- a/google/src/main/java/com/leetcode/google/CourseScheduleII.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.leetcode.google; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.Set; - -/** - * Created by liwentian on 2017/9/2. - */ - -public class CourseScheduleII { - - public int[] findOrder(int numCourses, int[][] prerequisites) { - int[] indegree = new int[numCourses]; - HashMap> map = new HashMap<>(); - for (int[] f : prerequisites) { - int from = f[1], to = f[0]; - Set set = map.get(from); - if (set == null) { - set = new HashSet<>(); - map.put(from, set); - } - /** - * 这里要防止同一条边计了多次 - */ - if (set.add(to)) { - indegree[to]++; - } - } - Queue queue = new LinkedList<>(); - - int[] result = new int[numCourses]; - int idx = 0; - - for (int i = 0; i < indegree.length; i++) { - if (indegree[i] == 0) { - queue.add(i); - } - } - while (!queue.isEmpty()) { - Integer n = queue.poll(); - result[idx++] = n; - Set set = map.get(n); - if (set != null) { - for (Integer k : set) { - if (--indegree[k] == 0) { - queue.add(k); - } - } - } - } - return idx == result.length ? result : new int[0]; - } -} diff --git a/google/src/main/java/com/leetcode/google/DecodeString.java b/google/src/main/java/com/leetcode/google/DecodeString.java deleted file mode 100644 index feb97e7..0000000 --- a/google/src/main/java/com/leetcode/google/DecodeString.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.leetcode.google; - -import java.util.Deque; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Stack; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class DecodeString { - - public String decodeString(String s) { - StringBuilder sb = new StringBuilder(); - - for (char c : s.toCharArray()) { - if (c != ']') { - sb.append(c); - } else { - String t = popString(sb); - for (int i = popCount(sb); i > 0; i--) { - sb.append(t); - } - } - } - - return sb.toString(); - } - - private String popString(StringBuilder sb) { - StringBuilder ss = new StringBuilder(); - - int i = sb.length() - 1; - for ( ; sb.charAt(i) != '['; i--) { - ss.append(sb.charAt(i)); - } - sb.setLength(i); - - return ss.reverse().toString(); - } - - private int popCount(StringBuilder sb) { - int i = sb.length() - 1, cnt = 0, t = 1; - for ( ; i >= 0 && Character.isDigit(sb.charAt(i)); i--, t *= 10) { - cnt += t * (sb.charAt(i) - '0'); - } - sb.setLength(i + 1); - return cnt; - } -} diff --git a/google/src/main/java/com/leetcode/google/EncodeAndDecodeStrings.java b/google/src/main/java/com/leetcode/google/EncodeAndDecodeStrings.java deleted file mode 100644 index 38d5131..0000000 --- a/google/src/main/java/com/leetcode/google/EncodeAndDecodeStrings.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class EncodeAndDecodeStrings { - - // Encodes a list of strings to a single string. - public String encode(List strs) { - StringBuilder sb = new StringBuilder(); - for (String s : strs) { - sb.append(s.length()).append("/").append(s); - } - return sb.toString(); - } - - // Decodes a single string to a list of strings. - public List decode(String s) { - List list = new LinkedList<>(); - for (int i = 0; i < s.length(); ) { - int index = s.indexOf("/", i); - int size = Integer.parseInt(s.substring(i, index)); - i = index + 1 + size; - list.add(s.substring(index + 1, i)); - } - return list; - } -} diff --git a/google/src/main/java/com/leetcode/google/EvaluateDivision.java b/google/src/main/java/com/leetcode/google/EvaluateDivision.java deleted file mode 100644 index 9604f2a..0000000 --- a/google/src/main/java/com/leetcode/google/EvaluateDivision.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.leetcode.google; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class EvaluateDivision { - - public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { - HashMap> valueMap = new HashMap<>(); - - for (int i = 0; i < equations.length; i++) { - String[] equation = equations[i]; - HashMap map = valueMap.get(equation[0]); - if (map == null) { - map = new HashMap<>(); - valueMap.put(equation[0], map); - } - map.put(equation[1], values[i]); - - map = valueMap.get(equation[1]); - if (map == null) { - map = new HashMap<>(); - valueMap.put(equation[1], map); - } - map.put(equation[0], 1 / values[i]); - } - - double[] result = new double[queries.length]; - for (int i = 0; i < queries.length; i++) { - double res = dfs(valueMap, queries[i][0], queries[i][1], new HashSet(), 1.0); - if (res == 0.0) { - result[i] = -1.0; - } else { - result[i] = res; - } - } - return result; - } - - private double dfs(HashMap> map, String start, String end, HashSet set, double value) { - if (set.contains(start)) { - return 0.0; - } - if (!map.containsKey(start) || !map.containsKey(end)) { - return 0.0; - } - if (start.equals(end)) { - return value; - } - set.add(start); - - double res = 0.0; - HashMap valueMap = map.get(start); - for (Map.Entry entry : valueMap.entrySet()) { - res = dfs(map, entry.getKey(), end, set, value * entry.getValue()); - if (res > 0) { - break; - } - } - set.remove(start); - return res; - } -} diff --git a/google/src/main/java/com/leetcode/google/GeneralizedAbbreviation.java b/google/src/main/java/com/leetcode/google/GeneralizedAbbreviation.java deleted file mode 100644 index a87aa88..0000000 --- a/google/src/main/java/com/leetcode/google/GeneralizedAbbreviation.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/1. - */ - -public class GeneralizedAbbreviation { - - public List generateAbbreviations(String word) { - List list = new LinkedList<>(); - helper(word, 0, list, "", 0); - return list; - } - - private void helper(String word, int idx, List list, String cur, int count) { - if (idx == word.length()) { - if (count > 0) { - cur += count; - } - list.add(cur); - return; - } - - helper(word, idx + 1, list, cur, count + 1); - helper(word, idx + 1, list, cur + (count > 0 ? count : "") + word.charAt(idx), 0); - } -} diff --git a/google/src/main/java/com/leetcode/google/GenerateParentheses.java b/google/src/main/java/com/leetcode/google/GenerateParentheses.java deleted file mode 100644 index f6891d2..0000000 --- a/google/src/main/java/com/leetcode/google/GenerateParentheses.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class GenerateParentheses { - - public List generateParenthesis(int n) { - List result = new LinkedList(); - dfs(result, n, "", 0, 0); - return result; - } - - private void dfs(List result, int n, String str, int left, int right) { - if (left == n && right == n) { - result.add(str); - return; - } - if (left > n || right > n || left < right) { - return; - } - dfs(result, n, str + "(", left + 1, right); - dfs(result, n, str + ")", left, right + 1); - } -} diff --git a/google/src/main/java/com/leetcode/google/GraphValidTree.java b/google/src/main/java/com/leetcode/google/GraphValidTree.java deleted file mode 100644 index a64204a..0000000 --- a/google/src/main/java/com/leetcode/google/GraphValidTree.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.leetcode.google; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class GraphValidTree { - - public boolean validTree(int n, int[][] edges) { - List[] graph = new ArrayList[n]; - for (int i = 0; i < n; i++) { - graph[i] = new ArrayList<>(); - } - for (int i = 0; i < edges.length; i++) { - graph[edges[i][0]].add(edges[i][1]); - graph[edges[i][1]].add(edges[i][0]); - } - boolean[] visited = new boolean[n]; - - if (!dfs(graph, visited, 0, -1)) { - return false; - } - - for (int i = 0; i < n; i++) { - if (!visited[i]) { - return false; - } - } - - return true; - } - - private boolean dfs(List[] graph, boolean[] visited, int start, int parent) { - visited[start] = true; - - for (int i = 0; i < graph[start].size(); i++) { - int to = graph[start].get(i); - if (to == parent) { - continue; - } - if (visited[to]) { - return false; - } - if (!dfs(graph, visited, to, start)) { - return false; - } - } - - return true; - } - -} diff --git a/google/src/main/java/com/leetcode/google/LetterCombinationsOfAPhoneNumber.java b/google/src/main/java/com/leetcode/google/LetterCombinationsOfAPhoneNumber.java deleted file mode 100644 index c6f7249..0000000 --- a/google/src/main/java/com/leetcode/google/LetterCombinationsOfAPhoneNumber.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class LetterCombinationsOfAPhoneNumber { - - final String[] NUMS = { - "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" - }; - - public List letterCombinations(String digits) { - List result = new LinkedList<>(); - if (digits.isEmpty()) { - return result; - } - dfs(digits, result, 0, ""); - return result; - } - - private void dfs(String digits, List result, int idx, String cur) { - if (idx == digits.length()) { - result.add(cur); - return; - } - - int n = digits.charAt(idx) - '0'; - for (char c : NUMS[n].toCharArray()) { - dfs(digits, result, idx + 1, cur + c); - } - } -} diff --git a/google/src/main/java/com/leetcode/google/LoggerRateLimiter.java b/google/src/main/java/com/leetcode/google/LoggerRateLimiter.java deleted file mode 100644 index 6f11ed7..0000000 --- a/google/src/main/java/com/leetcode/google/LoggerRateLimiter.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.leetcode.google; - -import java.util.Deque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class LoggerRateLimiter { - - private HashMap mMap; - - /** Initialize your data structure here. */ - public LoggerRateLimiter() { - mMap = new HashMap<>(); - } - - /** Returns true if the message should be printed in the given timestamp, otherwise returns false. - If this method returns false, the message will not be printed. - The timestamp is in seconds granularity. */ - public boolean shouldPrintMessage(int timestamp, String message) { - int time = mMap.getOrDefault(message, -100); - if (timestamp - time >= 10) { - mMap.put(message, timestamp); - return true; - } else { - return false; - } - } -} diff --git a/google/src/main/java/com/leetcode/google/LongestAbsoluteFilePath.java b/google/src/main/java/com/leetcode/google/LongestAbsoluteFilePath.java deleted file mode 100644 index a2efead..0000000 --- a/google/src/main/java/com/leetcode/google/LongestAbsoluteFilePath.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.leetcode.google; - -import java.util.Stack; - -/** - * Created by liwentian on 17/8/22. - */ - -public class LongestAbsoluteFilePath { - - public int lengthLongestPath(String input) { - Stack stack = new Stack(); - String[] lines = input.split("\n"); - - int max = 0; - for (String line : lines) { - int level = line.lastIndexOf('\t') + 1; - - while (stack.size() > level) { - stack.pop(); - } - - int parent = stack.isEmpty() ? 0 : stack.peek(); - - int len = parent + line.length() - level + 1; - - stack.push(len); - - if (line.contains(".")) { - max = Math.max(max, len - 1); - } - } - - return max; - } -} diff --git a/google/src/main/java/com/leetcode/google/LongestIncreasingPathInAMatrix.java b/google/src/main/java/com/leetcode/google/LongestIncreasingPathInAMatrix.java deleted file mode 100644 index 86a7f9e..0000000 --- a/google/src/main/java/com/leetcode/google/LongestIncreasingPathInAMatrix.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/9/1. - */ - -public class LongestIncreasingPathInAMatrix { - - public int longestIncreasingPath(int[][] matrix) { - if (matrix.length == 0) { - return 0; - } - int row = matrix.length, col = matrix[0].length; - int max = 0; - int[][] cache = new int[row][col]; - for (int i = 0; i < row; i++) { - for (int j = 0; j < col; j++) { - int len = dfs(matrix, i, j, cache); - max = Math.max(max, len); - } - } - return max; - } - - private int dfs(int[][] matrix, int i, int j, int[][] cache) { - if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length) { - return 0; - } - - if (cache[i][j] > 0) { - return cache[i][j]; - } - - int max = 1; - - int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1}; - - for (int k = 0; k < dx.length; k++) { - int x = i + dx[k], y = j + dy[k]; - if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || matrix[x][y] <= matrix[i][j]) { - continue; - } - max = Math.max(max, dfs(matrix, x, y, cache) + 1); - } - - cache[i][j] = max; - return max; - } -} diff --git a/google/src/main/java/com/leetcode/google/LongestSubstringWithAtMostKDistinctCharacters.java b/google/src/main/java/com/leetcode/google/LongestSubstringWithAtMostKDistinctCharacters.java deleted file mode 100644 index 4f5dd35..0000000 --- a/google/src/main/java/com/leetcode/google/LongestSubstringWithAtMostKDistinctCharacters.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/22. - */ - -public class LongestSubstringWithAtMostKDistinctCharacters { - - public int lengthOfLongestSubstringTwoDistinct(String s, int k) { - if (k == 0) { - return 0; - } - - int[] count = new int[256]; - int distinct = 0, longest = 0; - - for (int i = 0, j = 0; j < s.length(); j++) { - if (count[s.charAt(j)]++ == 0) { - distinct++; - } - - for ( ; i < j && distinct > k; ) { - if (--count[s.charAt(i++)] == 0) { - --distinct; - } - } - - longest = Math.max(longest, j - i + 1); - } - - return longest; - } -} diff --git a/google/src/main/java/com/leetcode/google/LongestSubstringWithAtMostTwoDistinctCharacters.java b/google/src/main/java/com/leetcode/google/LongestSubstringWithAtMostTwoDistinctCharacters.java deleted file mode 100644 index e6d611c..0000000 --- a/google/src/main/java/com/leetcode/google/LongestSubstringWithAtMostTwoDistinctCharacters.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/22. - */ - -public class LongestSubstringWithAtMostTwoDistinctCharacters { - - public int lengthOfLongestSubstringTwoDistinct(String s) { - int[] count = new int[256]; - int distinct = 0, longest = 0; - - for (int i = 0, j = 0; j < s.length(); j++) { - if (count[s.charAt(j)]++ == 0) { - distinct++; - } - - for ( ; i < j && distinct > 2; ) { - if (--count[s.charAt(i++)] == 0) { - --distinct; - } - } - - longest = Math.max(longest, j - i + 1); - } - - return longest; - } -} diff --git a/google/src/main/java/com/leetcode/google/Main.java b/google/src/main/java/com/leetcode/google/Main.java deleted file mode 100644 index 6ba733a..0000000 --- a/google/src/main/java/com/leetcode/google/Main.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/11/29. - */ - -public class Main { - - public static void Main(String[] args) { - } -} diff --git a/google/src/main/java/com/leetcode/google/MedianOfTwoSortedArrays.java b/google/src/main/java/com/leetcode/google/MedianOfTwoSortedArrays.java deleted file mode 100644 index f5389ee..0000000 --- a/google/src/main/java/com/leetcode/google/MedianOfTwoSortedArrays.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.leetcode.google; - -/** - * Created by dingjikerbo on 2017/8/20. - */ - -public class MedianOfTwoSortedArrays { - - public double findMedianSortedArrays(int[] nums1, int[] nums2) { - int len = nums1.length + nums2.length; - if (len % 2 != 0) { - return findKth(nums1, 0, nums1.length - 1, nums2, 0, nums2.length - 1, 1 + len / 2); - } else { - return (findKth(nums1, 0, nums1.length - 1, nums2, 0, nums2.length - 1, len / 2) + - findKth(nums1, 0, nums1.length - 1, nums2, 0, nums2.length - 1, len / 2 + 1)) / 2f; - } - } - - private double findKth(int[] nums1, int start1, int end1, int[] nums2, int start2, int end2, int k) { - int len1 = end1 - start1 + 1; - int len2 = end2 - start2 + 1; - - if (len1 > len2) { - return findKth(nums2, start2, end2, nums1, start1, end1, k); - } else if (len1 == 0) { - return nums2[start2 + k - 1]; - } else if (k == 1) { - return Math.min(nums1[start1], nums2[start2]); - } else { - int ia = Math.min(k / 2, len1), ib = k - ia; - if (nums1[start1 + ia - 1] > nums2[start2 + ib - 1]) { - return findKth(nums1, start1, end1, nums2, start2 + ib, end2, k - ib); - } else if (nums1[start1 + ia - 1] < nums2[start2 + ib - 1]) { - return findKth(nums1, start1 + ia, end1, nums2, start2, end2, k - ia); - } else { - return nums1[start1 + ia - 1]; - } - } - } -} diff --git a/google/src/main/java/com/leetcode/google/MinimumHeightTrees.java b/google/src/main/java/com/leetcode/google/MinimumHeightTrees.java deleted file mode 100644 index 92170fe..0000000 --- a/google/src/main/java/com/leetcode/google/MinimumHeightTrees.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.leetcode.google; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class MinimumHeightTrees { - - public List findMinHeightTrees(int n, int[][] edges) { - if (n == 1) { - return Arrays.asList(0); - } - Set[] sets = new HashSet[n]; - for (int i = 0; i < n; i++) { - sets[i] = new HashSet<>(); - } - for (int[] edge : edges) { - sets[edge[0]].add(edge[1]); - sets[edge[1]].add(edge[0]); - } - List leaves = new LinkedList<>(); - for (int i = 0; i < n; i++) { - if (sets[i].size() == 1) { - leaves.add(i); - } - } - while (n > 2) { - n -= leaves.size(); - List newLeaves = new LinkedList<>(); - for (Integer k : leaves) { - int m = sets[k].iterator().next(); - sets[k].clear(); - sets[m].remove(k); - if (sets[m].size() == 1) { - newLeaves.add(m); - } - } - leaves = newLeaves; - } - return leaves; - } -} diff --git a/google/src/main/java/com/leetcode/google/MissingRanges.java b/google/src/main/java/com/leetcode/google/MissingRanges.java deleted file mode 100644 index da87e03..0000000 --- a/google/src/main/java/com/leetcode/google/MissingRanges.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/8/29. - */ - -public class MissingRanges { - - public List findMissingRanges(int[] nums, int lower, int upper) { - List list = new LinkedList<>(); - - long cur = lower; - for (int i = 0; i < nums.length; i++) { - if (nums[i] > cur) { - list.add(get(cur, nums[i] - 1)); - cur = (long) nums[i] + 1; - } else if (nums[i] == cur) { - cur++; - } - } - - if (cur <= upper) { - list.add(get(cur, upper)); - } - - return list; - } - - private String get(long cur, long end) { - if (end > cur) { - return cur + "->" + end; - } else { - return cur + ""; - } - } -} diff --git a/google/src/main/java/com/leetcode/google/MovingAverageFromDataStream.java b/google/src/main/java/com/leetcode/google/MovingAverageFromDataStream.java deleted file mode 100644 index 75462df..0000000 --- a/google/src/main/java/com/leetcode/google/MovingAverageFromDataStream.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.Queue; - -/** - * Created by liwentian on 2017/8/29. - */ - -public class MovingAverageFromDataStream { - - private int mSize; - - private Queue mQueue; - - private double mSum; - - public MovingAverageFromDataStream(int size) { - mSize = size; - mQueue = new LinkedList<>(); - } - - public double next(int val) { - mQueue.add(val); - mSum += val; - - if (mQueue.size() > mSize) { - mSum -= mQueue.poll(); - } - - return mSum / mQueue.size(); - } -} diff --git a/google/src/main/java/com/leetcode/google/NumMatrixII.java b/google/src/main/java/com/leetcode/google/NumMatrixII.java deleted file mode 100644 index 3f06adc..0000000 --- a/google/src/main/java/com/leetcode/google/NumMatrixII.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/26. - */ - -public class NumMatrixII { - - private int m, n; - - private int[][] tree; - private int[][] nums; - - public NumMatrixII(int[][] matrix) { - if (matrix.length == 0 || matrix[0].length == 0) { - return; - } - - m = matrix.length; - n = matrix[0].length; - nums = new int[m][n]; - tree = new int[m + 1][n + 1]; - - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - update(i, j, matrix[i][j]); - } - } - } - - public void update(int row, int col, int val) { - if (m == 0 || n == 0) { - return; - } - int delta = val - nums[row][col]; - nums[row][col] = val; - - for (int i = row + 1; i <= m; i += i & (-i)) { - for (int j = col + 1; j <= n; j += j & (-j)) { - tree[i][j] += delta; - } - } - } - - private int sum(int row, int col) { - int sum = 0; - for (int i = row + 1; i > 0; i -= i & (-i)) { - for (int j = col + 1; j > 0; j -= j & (-j)) { - sum += tree[i][j]; - } - } - return sum; - } - - public int sumRegion(int row1, int col1, int row2, int col2) { - if (m == 0 || n == 0) { - return 0; - } - return sum(row2, col2) - sum(row2, col1 - 1) - sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1); - } -} diff --git a/google/src/main/java/com/leetcode/google/NumberOfConnectedComponentsInAnUndirectedGraph.java b/google/src/main/java/com/leetcode/google/NumberOfConnectedComponentsInAnUndirectedGraph.java deleted file mode 100644 index 29949e1..0000000 --- a/google/src/main/java/com/leetcode/google/NumberOfConnectedComponentsInAnUndirectedGraph.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.leetcode.google; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class NumberOfConnectedComponentsInAnUndirectedGraph { - - public int countComponents(int n, int[][] edges) { - List[] graph = new ArrayList[n]; - for (int i = 0; i < n; i++) { - graph[i] = new ArrayList<>(); - } - for (int[] edge : edges) { - graph[edge[0]].add(edge[1]); - graph[edge[1]].add(edge[0]); - } - boolean[] visited = new boolean[n]; - int count = 0; - for (int i = 0; i < n; i++) { - if (!visited[i]) { - dfs(graph, i, visited); - count++; - } - } - return count; - } - - private void dfs(List[] graph, int i, boolean[] visited) { - if (visited[i]) { - return; - } - visited[i] = true; - for (Integer k : graph[i]) { - dfs(graph, k, visited); - } - } - -} diff --git a/google/src/main/java/com/leetcode/google/NumberOfIslands.java b/google/src/main/java/com/leetcode/google/NumberOfIslands.java deleted file mode 100644 index 212c513..0000000 --- a/google/src/main/java/com/leetcode/google/NumberOfIslands.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class NumberOfIslands { - - public int numIslands(char[][] grid) { - int num = 0; - for (int i = 0; i < grid.length; i++) { - for (int j = 0; j < grid[0].length; j++) { - if (grid[i][j] == '1') { - dfs(grid, i, j); - num++; - } - } - } - return num; - } - - private void dfs(char[][] grid, int i, int j) { - if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) { - return; - } - if (grid[i][j] != '1') { - return; - } - grid[i][j] = 'X'; - dfs(grid, i - 1, j); - dfs(grid, i + 1, j); - dfs(grid, i, j + 1); - dfs(grid, i, j - 1); - } -} diff --git a/google/src/main/java/com/leetcode/google/NumberOfIslandsII.java b/google/src/main/java/com/leetcode/google/NumberOfIslandsII.java deleted file mode 100644 index b7d3025..0000000 --- a/google/src/main/java/com/leetcode/google/NumberOfIslandsII.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.leetcode.google; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class NumberOfIslandsII { - - private int[] mRoot; - - private int mCount; - - public List numIslands2(int m, int n, int[][] positions) { - mRoot = new int[m * n]; - - Arrays.fill(mRoot, -1); - - int[] dx = new int[]{1, -1, 0, 0}; - int[] dy = new int[]{0, 0, -1, 1}; - - List list = new LinkedList<>(); - - for (int[] pos : positions) { - int k = pos[0] * n + pos[1]; - - mRoot[k] = k; - - mCount++; - - for (int i = 0; i < dx.length; i++) { - for (int j = 0; j < dy.length; j++) { - int x = pos[0] + dx[i], y = pos[1] + dy[i], z = x * n + y; - if (x < 0 || x >= m || y < 0 || y >= n || mRoot[z] == -1) { - continue; - } - union(k, z); - } - } - - list.add(mCount); - } - - return list; - } - - private void union(int z, int z0) { - int z1 = find(z); - int z2 = find(z0); - if (z1 != z2) { - mRoot[z1] = z2; - mCount--; - } - } - - private int find(int z) { - while (mRoot[z] != z) { - z = mRoot[z]; - } - return z; - } -} diff --git a/google/src/main/java/com/leetcode/google/PathSumIII.java b/google/src/main/java/com/leetcode/google/PathSumIII.java deleted file mode 100644 index 1807bc9..0000000 --- a/google/src/main/java/com/leetcode/google/PathSumIII.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.leetcode.google; - -import com.leetcode.library.TreeNode; - -/** - * Created by liwentian on 2017/11/29. - */ - -public class PathSumIII { - - public int pathSum(TreeNode root, int sum) { - int[] count = new int[1]; - helperSum(root, sum, count); - return count[0]; - } - - private void helperSum(TreeNode root, int sum, int[] count) { - if (root == null) { - return; - } - helper(root, sum, count); - helperSum(root.left, sum, count); - helperSum(root.right, sum, count); - } - - private void helper(TreeNode root, int sum, int[] count) { - if (root == null) { - return; - } - if (root.val == sum) { - count[0]++; - } - helper(root.left, sum - root.val, count); - helper(root.right, sum - root.val, count); - } -} diff --git a/google/src/main/java/com/leetcode/google/PerfectRectangle.java b/google/src/main/java/com/leetcode/google/PerfectRectangle.java deleted file mode 100644 index 9d310d0..0000000 --- a/google/src/main/java/com/leetcode/google/PerfectRectangle.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.leetcode.google; - -import java.util.HashMap; -import java.util.HashSet; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class PerfectRectangle { - - public boolean isRectangleCover(int[][] rectangles) { - - int x1 = Integer.MAX_VALUE, y1 = Integer.MAX_VALUE; - int x2 = 0, y2 = 0; - - HashSet set = new HashSet<>(); - - int area = 0; - - for (int[] rect : rectangles) { - int left = rect[0]; - int bottom = rect[1]; - int right = rect[2]; - int top = rect[3]; - - area += (right - left) * (top - bottom); - - x1 = Math.min(left, x1); - y1 = Math.min(bottom, y1); - x2 = Math.max(right, x2); - y2 = Math.max(top, y2); - - String s1 = left + "." + bottom; - String s2 = left + "." + top; - String s3 = right + "." + bottom; - String s4 = right + "." + top; - - if (!set.add(s1)) { - set.remove(s1); - } - - if (!set.add(s2)) { - set.remove(s2); - } - - if (!set.add(s3)) { - set.remove(s3); - } - - if (!set.add(s4)) { - set.remove(s4); - } - } - - String s1 = x1 + "." + y1; - String s2 = x1 + "." + y2; - String s3 = x2 + "." + y1; - String s4 = x2 + "." + y2; - - if (!set.contains(s1) || !set.contains(s2) || !set.contains(s3) || !set.contains(s4) || set.size() != 4) { - return false; - } - - return area == (x2 - x1) * (y2 - y1); - } -} diff --git a/google/src/main/java/com/leetcode/google/PerfectSquares.java b/google/src/main/java/com/leetcode/google/PerfectSquares.java deleted file mode 100644 index a51eac1..0000000 --- a/google/src/main/java/com/leetcode/google/PerfectSquares.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class PerfectSquares { - - public int numSquares(int n) { - int[] dp = new int[n + 1]; - - for (int i = 1; i <= n; i++) { - int min = Integer.MAX_VALUE; - for (int j = 1; i - j * j >= 0; j++) { - min = Math.min(dp[i - j * j] + 1, min); - } - dp[i] = min; - } - - return dp[n]; - - } -} diff --git a/google/src/main/java/com/leetcode/google/PlusOne.java b/google/src/main/java/com/leetcode/google/PlusOne.java deleted file mode 100644 index acac9ea..0000000 --- a/google/src/main/java/com/leetcode/google/PlusOne.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class PlusOne { - - public int[] plusOne(int[] digits) { - int[] res = new int[digits.length + 1]; - - int flag = 1; - for (int i = digits.length - 1; i >= 0 || flag > 0; i--) { - int s = flag + (i >= 0 ? digits[i] : 0); - res[i + 1] = s % 10; - flag = s / 10; - } - - if (res[0] != 0) { - return res; - } - - int[] ret = new int[digits.length]; - System.arraycopy(res, 1, ret, 0, ret.length); - return ret; - } -} diff --git a/google/src/main/java/com/leetcode/google/QueueReconstructionByHeight.java b/google/src/main/java/com/leetcode/google/QueueReconstructionByHeight.java deleted file mode 100644 index 3b63290..0000000 --- a/google/src/main/java/com/leetcode/google/QueueReconstructionByHeight.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.leetcode.google; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/1. - */ - -public class QueueReconstructionByHeight { - - public int[][] reconstructQueue(int[][] people) { - Arrays.sort(people,new Comparator(){ - @Override - public int compare(int[] o1, int[] o2){ - return o1[0]!=o2[0]?-o1[0]+o2[0]:o1[1]-o2[1]; - } - }); - List res = new LinkedList<>(); - for(int[] cur : people){ - res.add(cur[1],cur); - } - return res.toArray(new int[people.length][]); - } -} diff --git a/google/src/main/java/com/leetcode/google/RangeSumQuery2DImmutable.java b/google/src/main/java/com/leetcode/google/RangeSumQuery2DImmutable.java deleted file mode 100644 index 942428a..0000000 --- a/google/src/main/java/com/leetcode/google/RangeSumQuery2DImmutable.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/24. - */ - -public class RangeSumQuery2DImmutable { - - private int[][] dp; - - public RangeSumQuery2DImmutable(int[][] matrix) { - if (matrix.length == 0) { - return; - } - dp = new int[matrix.length + 1][matrix[0].length + 1]; - for (int i = 1; i <= matrix.length; i++) { - for (int j = 1; j <= matrix[0].length; j++) { - dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1] + matrix[i - 1][j - 1]; - } - } - } - - public int sumRegion(int row1, int col1, int row2, int col2) { - return dp[row2 + 1][col2 + 1] - dp[row2 + 1][col1] - dp[row1][col2 + 1] + dp[row1][col1]; - } -} diff --git a/google/src/main/java/com/leetcode/google/RangeSumQueryImmutable.java b/google/src/main/java/com/leetcode/google/RangeSumQueryImmutable.java deleted file mode 100644 index babb9a0..0000000 --- a/google/src/main/java/com/leetcode/google/RangeSumQueryImmutable.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/23. - */ - -public class RangeSumQueryImmutable { - - private int[] sums; - - public RangeSumQueryImmutable(int[] nums) { - sums = new int[nums.length]; - for (int sum = 0, i = 0; i < nums.length; i++) { - sum += nums[i]; - sums[i] = sum; - } - } - - public int sumRange(int i, int j) { - int sum1 = i > 0 ? sums[i - 1] : 0; - return sums[j] - sum1; - } -} diff --git a/google/src/main/java/com/leetcode/google/RangeSumQueryMutable.java b/google/src/main/java/com/leetcode/google/RangeSumQueryMutable.java deleted file mode 100644 index eac5523..0000000 --- a/google/src/main/java/com/leetcode/google/RangeSumQueryMutable.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/23. - */ - -public class RangeSumQueryMutable { - - private SegmentTreeNode mRoot; - - public RangeSumQueryMutable(int[] nums) { - mRoot = buildTree(nums, 0, nums.length - 1); - } - - private SegmentTreeNode buildTree(int[] nums, int start, int end) { - if (start > end) { - return null; - } - - SegmentTreeNode root = new SegmentTreeNode(); - root.start = start; - root.end = end; - - if (start == end) { - root.sum = nums[start]; - return root; - } - - int mid = start + ((end - start) >> 1); - root.left = buildTree(nums, start, mid); - root.right = buildTree(nums, mid + 1, end); - root.sum = root.left.sum + root.right.sum; - return root; - } - - public void update(int i, int val) { - update(mRoot, i, val); - } - - private void update(SegmentTreeNode node, int i, int val) { - int start = node.start, end = node.end; - if (start == end) { - node.sum = val; - return; - } - - int mid = start + ((end - start) >> 1); - if (i <= mid) { - update(node.left, i, val); - } else { - update(node.right, i, val); - } - node.sum = node.left.sum + node.right.sum; - } - - public int sumRange(int i, int j) { - return sumRange(mRoot, i, j); - } - - private int sumRange(SegmentTreeNode node, int i, int j) { - int start = node.start, end = node.end; - if (i == start && j == end) { - return node.sum; - } - int mid = start + ((end - start) >> 1); - if (j <= mid) { - return sumRange(node.left, i, j); - } else if (i > mid) { - return sumRange(node.right, i, j); - } else { - return sumRange(node.left, i, mid) + sumRange(node.right, mid + 1, j); - } - } - - private class SegmentTreeNode { - SegmentTreeNode left, right; - - int sum; - - int start, end; - } -} diff --git a/google/src/main/java/com/leetcode/google/ReconstructItinerary.java b/google/src/main/java/com/leetcode/google/ReconstructItinerary.java deleted file mode 100644 index 6e3818a..0000000 --- a/google/src/main/java/com/leetcode/google/ReconstructItinerary.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.leetcode.google; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Stack; -import java.util.function.BiConsumer; -import java.util.function.Function; - -/** - * Created by liwentian on 2017/9/2. - */ -/** - * 这题有两个前提 - * 1, 必须从JFK开始 - * 2, 解一定存在 - */ -/** - * 这题有两种解法: - * 1, 常规是DFS暴力解法,面试能写出这种就行了 - * 2, 欧拉解法 - */ -public class ReconstructItinerary { - - /** - * 常规DFS暴力列出所有可能的路径,可以一次走遍所有的边 - */ - public List> findItinerary(String[][] tickets) { - HashMap> map = new HashMap<>(); - for (String[] ticket : tickets) { - map.computeIfAbsent(ticket[0], k -> new ArrayList<>()).add(ticket[1]); - } - List> result = new LinkedList<>(); - dfs("JFK", result, map, new LinkedList<>(Arrays.asList("JFK")), tickets.length); - return result; - } - - void dfs(String airport, List> result, HashMap> map, LinkedList route, int n) { - if (route.size() == n + 1) { - result.add(new ArrayList<>(route)); - return; - } - if (!map.containsKey(airport) || map.get(airport).isEmpty()) { - return; - } - ArrayList list = map.get(airport); - for (int i = 0; i < list.size(); i++) { - String target = list.remove(i); - - route.add(target); - dfs(target, result, map, route, n); - route.removeLast(); - - list.add(i, target); - } - } - - /** - * 题目要求是列出字母顺序最小的 - */ - public List findItinerary2(String[][] tickets) { - HashMap> map = new HashMap<>(); - for (String[] ticket : tickets) { - map.computeIfAbsent(ticket[0], k -> new ArrayList<>()).add(ticket[1]); - } - for (List list : map.values()) { - Collections.sort(list); - } - LinkedList result = new LinkedList<>(Arrays.asList("JFK")); - dfs("JFK", map, result, tickets.length); - return result; - } - - boolean dfs(String airport, HashMap> map, LinkedList route, int n) { - if (route.size() == n + 1) { - return true; - } - if (!map.containsKey(airport) || map.get(airport).isEmpty()) { - return false; - } - ArrayList list = map.get(airport); - for (int i = 0; i < list.size(); i++) { - String target = list.remove(i); - - route.add(target); - if (dfs(target, map, route, n)) { - return true; - } - route.removeLast(); - - list.add(i, target); - } - return false; - } - - /** - * 欧拉递归解法如下 - */ - public List findItinerary3(String[][] tickets) { - for (String[] ticket : tickets) - targets.computeIfAbsent(ticket[0], k -> new PriorityQueue()).add(ticket[1]); - visit("JFK"); - return route; - } - - Map> targets = new HashMap<>(); - List route = new LinkedList(); - - void visit(String airport) { - while (targets.containsKey(airport) && !targets.get(airport).isEmpty()) - visit(targets.get(airport).poll()); - route.add(0, airport); - } - - /** - * 欧拉迭代写法 - */ - public List findItinerary4(String[][] tickets) { - for (String[] ticket : tickets) - targets.computeIfAbsent(ticket[0], k -> new PriorityQueue()).add(ticket[1]); - - Map> targets = new HashMap<>(); - List route = new LinkedList(); - - Stack stack = new Stack<>(); - stack.push("JFK"); - - while (!stack.isEmpty()) { - String s = stack.peek(); - while (targets.containsKey(s) && !targets.get(s).isEmpty()) - stack.push(targets.get(s).poll()); - route.add(0, stack.pop()); - } - - return route; - } -} \ No newline at end of file diff --git a/google/src/main/java/com/leetcode/google/RecoverBinarySearchTree.java b/google/src/main/java/com/leetcode/google/RecoverBinarySearchTree.java deleted file mode 100644 index f4dc05b..0000000 --- a/google/src/main/java/com/leetcode/google/RecoverBinarySearchTree.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.leetcode.google; - -import com.leetcode.library.TreeNode; - -import java.util.Stack; - -/** - * Created by liwentian on 2017/11/29. - */ - -public class RecoverBinarySearchTree { - - public void recoverTree(TreeNode root) { - Stack stack = new Stack<>(); - TreeNode prev = null, first = null, second = null; - - while (!stack.isEmpty() || root != null) { - if (root != null) { - stack.push(root); - root = root.left; - } else { - root = stack.pop(); - - if (prev != null) { - if (first == null && prev.val > root.val) { - first = prev; - } - if (first != null && prev.val > root.val) { - second = root; - } - } - prev = root; - root = root.right; - } - } - - int t = first.val; - first.val = second.val; - second.val = t; - } -} diff --git a/google/src/main/java/com/leetcode/google/RegularExpressionMatching.java b/google/src/main/java/com/leetcode/google/RegularExpressionMatching.java deleted file mode 100644 index d278bcb..0000000 --- a/google/src/main/java/com/leetcode/google/RegularExpressionMatching.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class RegularExpressionMatching { - - public boolean isMatch(String s, String p) { - if (p.isEmpty()) { - return s.isEmpty(); - } - if (p.length() == 1) { - return s.length() == 1 && equals(s, p); - } - if (p.charAt(1) != '*') { - return s.length() > 0 && equals(s, p) && isMatch(s.substring(1), p.substring(1)); - } - if (s.isEmpty() || !equals(s, p)) { - return isMatch(s, p.substring(2)); - } else { - return isMatch(s, p.substring(2)) || isMatch(s.substring(1), p); - } - } - - private boolean equals(String s, String p) { - return p.charAt(0) == '.' || s.charAt(0) == p.charAt(0); - } -} diff --git a/google/src/main/java/com/leetcode/google/ReverseVowelsOfaString.java b/google/src/main/java/com/leetcode/google/ReverseVowelsOfaString.java deleted file mode 100644 index ea96213..0000000 --- a/google/src/main/java/com/leetcode/google/ReverseVowelsOfaString.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class ReverseVowelsOfaString { - - - - public String reverseVowels(String s) { - boolean[] flag = new boolean[256]; - for (char c : "aeiouAEIOU".toCharArray()) { - flag[c] = true; - } - - StringBuilder sb = new StringBuilder(s); - for (int i = 0, j = sb.length() - 1; i < j; ) { - if (!flag[sb.charAt(i)]) { - i++; - } else if (!flag[sb.charAt(j)]) { - j--; - } else { - char c = sb.charAt(i); - sb.setCharAt(i, sb.charAt(j)); - sb.setCharAt(j, c); - i++; - j--; - } - } - - return sb.toString(); - } - -} diff --git a/google/src/main/java/com/leetcode/google/SentenceScreenFitting.java b/google/src/main/java/com/leetcode/google/SentenceScreenFitting.java deleted file mode 100644 index 89fcb42..0000000 --- a/google/src/main/java/com/leetcode/google/SentenceScreenFitting.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 17/8/26. - */ - -public class SentenceScreenFitting { - - public int wordsTyping(String[] sentence, int rows, int cols) { - String s = String.join(" ", sentence) + " "; - - int start = 0, len = s.length(); - - for (int i = 0; i < rows; i++) { - start += cols; - - if (s.charAt(start % len) == ' ') { - start++; - } else { - for ( ; start > 0 && s.charAt((start - 1) % len) != ' '; start--); - } - } - - return start / len; - } -} diff --git a/google/src/main/java/com/leetcode/google/ShortestDistanceFromAllBuildings.java b/google/src/main/java/com/leetcode/google/ShortestDistanceFromAllBuildings.java deleted file mode 100644 index 6c2f3d4..0000000 --- a/google/src/main/java/com/leetcode/google/ShortestDistanceFromAllBuildings.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.Queue; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class ShortestDistanceFromAllBuildings { - - public int shortestDistance(int[][] grid) { - if (grid.length == 0) { - return -1; - } - int row = grid.length, col = grid[0].length; - - int[][] dis = new int[row][col]; - int[][] building = new int[row][col]; - int buildings = 0; - - for (int i = 0; i < row; i++) { - for (int j = 0; j < col; j++) { - if (grid[i][j] != 1) { - continue; - } - - buildings++; - bfs(grid, dis, building, i, j); - } - } - - int shortest = Integer.MAX_VALUE; - for (int i = 0; i < row; i++) { - for (int j = 0; j < col; j++) { - if (grid[i][j] == 0 && building[i][j] == buildings) { - shortest = Math.min(shortest, dis[i][j]); - } - } - } - return shortest == Integer.MAX_VALUE ? -1 : shortest; - } - - private void bfs(int[][] grid, int[][] dis, int[][] building, int i, int j) { - Queue queue = new LinkedList<>(); - queue.add(new int[] {i, j}); - - Queue next = new LinkedList<>(); - - boolean[][] visited = new boolean[grid.length][grid[0].length]; - - int level = 0; - - while (!queue.isEmpty()) { - int[] pos = queue.poll(); - int x0 = pos[0], y0 = pos[1]; - - dis[x0][y0] += level; - building[x0][y0]++; - - int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1}; - - for (int m = 0; m < dx.length; m++) { - int x = x0 + dx[m], y = y0 + dy[m]; - - if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) { - continue; - } - - if (grid[x][y] == 0 && !visited[x][y]) { - visited[x][y] = true; - next.offer(new int[]{x, y}); - } - } - - if (queue.isEmpty()) { - queue.addAll(next); - next.clear(); - level++; - } - } - } -} diff --git a/google/src/main/java/com/leetcode/google/StrobogrammaticNumber.java b/google/src/main/java/com/leetcode/google/StrobogrammaticNumber.java deleted file mode 100644 index b50369b..0000000 --- a/google/src/main/java/com/leetcode/google/StrobogrammaticNumber.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class StrobogrammaticNumber { - - public boolean isStrobogrammatic(String num) { - for (int i = 0, j = num.length() - 1; i <= j; i++, j--) { - if (!"11 88 00 696".contains(num.charAt(i) + "" + num.charAt(j))) { - return false; - } - } - return true; - } -} diff --git a/google/src/main/java/com/leetcode/google/StrobogrammaticNumberII.java b/google/src/main/java/com/leetcode/google/StrobogrammaticNumberII.java deleted file mode 100644 index 448e6e0..0000000 --- a/google/src/main/java/com/leetcode/google/StrobogrammaticNumberII.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.leetcode.google; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class StrobogrammaticNumberII { - - - public List findStrobogrammatic(int n) { - return helper(n, n); - } - - private List helper(int k, int n) { - if (k == 0) { - return Arrays.asList(""); - } else if (k == 1) { - return Arrays.asList("0", "1", "8"); - } - List result = new LinkedList<>(); - for (String s : helper(k - 2, n)) { - if (k != n) { - result.add("0" + s + "0"); - } - - result.add("1" + s + "1"); - result.add("8" + s + "8"); - result.add("6" + s + "9"); - result.add("9" + s + "6"); - } - return result; - } -} diff --git a/google/src/main/java/com/leetcode/google/TheSkylineProblem.java b/google/src/main/java/com/leetcode/google/TheSkylineProblem.java deleted file mode 100644 index d4d71aa..0000000 --- a/google/src/main/java/com/leetcode/google/TheSkylineProblem.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.leetcode.google; - -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.PriorityQueue; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class TheSkylineProblem { - - public List getSkyline(int[][] buildings) { - List list = new LinkedList<>(); - for (int[] building : buildings) { - list.add(new int[] {building[0], -building[2]}); - list.add(new int[] {building[1], building[2]}); - } - - Collections.sort(list, new Comparator() { - @Override - public int compare(int[] o1, int[] o2) { - return o1[0] != o2[0] ? o1[0] - o2[0] : o1[1] - o2[1]; - } - }); - - List result = new LinkedList<>(); - - PriorityQueue queue = new PriorityQueue<>(Comparator.reverseOrder()); - queue.add(0); - - int prev = 0; - for (int[] pos : list) { - if (pos[1] < 0) { - queue.add(-pos[1]); - } else { - queue.remove(pos[1]); - } - - int cur = queue.peek(); - if (cur != prev) { - result.add(new int[] {pos[0], cur}); - prev = cur; - } - } - - return result; - } -} diff --git a/google/src/main/java/com/leetcode/google/ThreeSumSmaller.java b/google/src/main/java/com/leetcode/google/ThreeSumSmaller.java deleted file mode 100644 index 5dfb0f1..0000000 --- a/google/src/main/java/com/leetcode/google/ThreeSumSmaller.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leetcode.google; - -import java.util.Arrays; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class ThreeSumSmaller { - // -4 -1 -1 0 1 2 ,target=-5 - public int threeSumSmaller(int[] nums, int target) { - Arrays.sort(nums); - - int count = 0; - for (int i = 0; i < nums.length - 2; i++) { - for (int j = i + 1, k = nums.length - 1; j < k; ) { - if (nums[i] + nums[j] + nums[k] < target) { - count += k - j; - j++; - } else { - k--; - } - } - } - - return count; - } -} diff --git a/google/src/main/java/com/leetcode/google/UTFValidation.java b/google/src/main/java/com/leetcode/google/UTFValidation.java deleted file mode 100644 index 18dff7f..0000000 --- a/google/src/main/java/com/leetcode/google/UTFValidation.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/8/31. - */ - -public class UTFValidation { - - public boolean validUtf8(int[] data) { - for (int i = 0; i < data.length; ) { - int n = data[i], size; - - if (n >>> 7 == 0) { - size = 1; - } else if (n >>> 5 == 0x6) { - size = 2; - } else if (n >>> 4 == 0xe) { - size = 3; - } else if (n >>> 3 == 0x1e) { - size = 4; - } else { - return false; - } - - if (i + size > data.length) { - return false; - } - - for (i++, size--; size > 0; size--, i++) { - if (data[i] >>> 6 != 2) { - return false; - } - } - } - return true; - } -} diff --git a/google/src/main/java/com/leetcode/google/UniqueWordAbbreviation.java b/google/src/main/java/com/leetcode/google/UniqueWordAbbreviation.java deleted file mode 100644 index aef97a9..0000000 --- a/google/src/main/java/com/leetcode/google/UniqueWordAbbreviation.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.leetcode.google; - -import java.util.HashMap; -import java.util.HashSet; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class UniqueWordAbbreviation { - - private HashMap> mMap; - - public UniqueWordAbbreviation(String[] dictionary) { - mMap = new HashMap<>(); - for (String s : dictionary) { - String t = abbr(s); - HashSet set = mMap.get(t); - if (set == null) { - set = new HashSet<>(); - mMap.put(t, set); - } - set.add(s); - } - } - - private String abbr(String s) { - return s.length() > 2 ? s.charAt(0) + String.valueOf(s.length() - 2) + s.charAt(s.length() - 1) : s; - } - - public boolean isUnique(String word) { - String t = abbr(word); - HashSet set = mMap.get(t); - return set == null || (set.size() == 1 && set.contains(word)); - } -} diff --git a/google/src/main/java/com/leetcode/google/ValidWordSquare.java b/google/src/main/java/com/leetcode/google/ValidWordSquare.java deleted file mode 100644 index a2ecca7..0000000 --- a/google/src/main/java/com/leetcode/google/ValidWordSquare.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leetcode.google; - -import java.util.List; - -/** - * Created by liwentian on 17/8/26. - */ - -public class ValidWordSquare { - - public boolean validWordSquare(List words) { - for (int i = 0; i < words.size(); i++) { - String word = words.get(i); - if (word.length() > words.size()) { - return false; - } - for (int j = 0; j < word.length(); j++) { - String s = words.get(j); - if (i >= s.length() || word.charAt(j) != s.charAt(i)) { - return false; - } - } - } - return true; - } -} diff --git a/google/src/main/java/com/leetcode/google/WallsAndGates.java b/google/src/main/java/com/leetcode/google/WallsAndGates.java deleted file mode 100644 index 8dd6280..0000000 --- a/google/src/main/java/com/leetcode/google/WallsAndGates.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.leetcode.google; - -import java.util.LinkedList; -import java.util.Queue; - -/** - * Created by liwentian on 2017/9/1. - */ - -public class WallsAndGates { - - public void wallsAndGates(int[][] rooms) { - Queue queue = new LinkedList<>(); - Queue next = new LinkedList<>(); - for (int i = 0; i < rooms.length; i++) { - for (int j = 0; j < rooms[0].length; j++) { - if (rooms[i][j] == 0) { - queue.add(new int[] {i, j}); - } - } - } - - int level = 0; - - while (!queue.isEmpty()) { - int[] pos = queue.poll(); - int x = pos[0], y = pos[1]; - - if (rooms[x][y] == Integer.MAX_VALUE) { - rooms[x][y] = level; - } - - int[] dx = {-1, 1, 0, 0}, dy = {0, 0, -1, 1}; - for (int m = 0; m < dx.length; m++) { - int x0 = x + dx[m], y0 = y + dy[m]; - if (x0 < 0 || x0 >= rooms.length || y0 < 0 || y0 >= rooms[0].length) { - continue; - } - if (rooms[x0][y0] != Integer.MAX_VALUE) { - continue; - } - next.add(new int[] {x0, y0}); - } - - if (queue.isEmpty()) { - queue.addAll(next); - next.clear(); - level++; - } - } - } -} diff --git a/google/src/main/java/com/leetcode/google/WiggleSort.java b/google/src/main/java/com/leetcode/google/WiggleSort.java deleted file mode 100644 index 0e8c6fc..0000000 --- a/google/src/main/java/com/leetcode/google/WiggleSort.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leetcode.google; - -/** - * Created by liwentian on 2017/8/30. - */ - -public class WiggleSort { - - public void wiggleSort(int[] nums) { - for (int i = 0; i + 1 < nums.length; i++) { - if ((i & 1) == 0) { - if (nums[i] > nums[i + 1]) { - swap(nums, i, i + 1); - } - } else { - if (nums[i] < nums[i + 1]) { - swap(nums, i, i + 1); - } - } - } - } - - private void swap(int[] nums, int i, int j) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } -} diff --git a/google/src/main/java/com/leetcode/google/WordBreakII.java b/google/src/main/java/com/leetcode/google/WordBreakII.java deleted file mode 100644 index bbdca35..0000000 --- a/google/src/main/java/com/leetcode/google/WordBreakII.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.leetcode.google; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/3. - */ - -public class WordBreakII { - - public List wordBreak(String s, List wordDict) { - HashMap> cache = new HashMap<>(); - cache.put("", Arrays.asList("")); - return dfs(s, new HashSet(wordDict), cache); - } - - private List dfs(String s, HashSet wordDict, HashMap> cache) { - if (cache.containsKey(s)) { - return cache.get(s); - } - List result = new LinkedList<>(); - for (int i = 0; i < s.length(); i++) { - String t = s.substring(i); - if (wordDict.contains(t)) { - List list = dfs(s.substring(0, i), wordDict, cache); - if (list != null) { - for (String ss : list) { - result.add((ss.length() > 0 ? ss + " " : "") + t); - } - } - } - } - cache.put(s, result); - return result; - } - - -} diff --git a/google/src/main/java/com/leetcode/google/WordSquares.java b/google/src/main/java/com/leetcode/google/WordSquares.java deleted file mode 100644 index 0a66374..0000000 --- a/google/src/main/java/com/leetcode/google/WordSquares.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.leetcode.google; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * Created by liwentian on 17/8/26. - */ - -public class WordSquares { - - public List> wordSquares(String[] words) { - List> result = new LinkedList<>(); - if (words.length == 0) { - return result; - } - HashMap> map = new HashMap<>(); - for (String word : words) { - for (int i = -1; i < word.length(); i++) { - String s = word.substring(0, i + 1); - Set set = map.get(s); - if (set == null) { - set = new HashSet<>(); - map.put(s, set); - } - set.add(word); - } - } - - helper(result, words[0].length(), map, new LinkedList()); - return result; - } - - private void helper(List> result, int len, HashMap> map, List list) { - if (list.size() == len) { - result.add(new LinkedList<>(list)); - return; - } - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { - sb.append(list.get(i).charAt(list.size())); - } - String prefix = sb.toString(); - Set set = map.get(prefix); - - if (set == null) { - return; - } - - for (String s : set) { - list.add(s); - helper(result, len, map, list); - list.remove(list.size() - 1); - } - } -} diff --git a/google/src/main/java/com/leetcode/google/ZigzagIterator.java b/google/src/main/java/com/leetcode/google/ZigzagIterator.java deleted file mode 100644 index 3fb86af..0000000 --- a/google/src/main/java/com/leetcode/google/ZigzagIterator.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.leetcode.google; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * Created by liwentian on 17/8/26. - */ - -public class ZigzagIterator { - - private List> mIterators = new ArrayList<>(); - - private int mCurIdx; - - public ZigzagIterator(List v1, List v2) { - init(v1, v2); - } - - private void init(List... lists) { - for (List list : lists) { - if (!list.isEmpty()) { - mIterators.add(list.iterator()); - } - } - } - - public int next() { - return mIterators.get(mCurIdx++).next(); - } - - public boolean hasNext() { - while (!mIterators.isEmpty()) { - mCurIdx %= mIterators.size(); - - Iterator cur = mIterators.get(mCurIdx); - - if (cur.hasNext()) { - return true; - } - mIterators.remove(mCurIdx); - } - return false; - } -} diff --git a/gradle.properties b/gradle.properties deleted file mode 100644 index aac7c9b..0000000 --- a/gradle.properties +++ /dev/null @@ -1,17 +0,0 @@ -# Project-wide Gradle settings. - -# IDE (e.g. Android Studio) users: -# Gradle settings configured through the IDE *will override* -# any settings specified in this file. - -# For more details on how to configure your build environment visit -# http://www.gradle.org/docs/current/userguide/build_environment.html - -# Specifies the JVM arguments used for the daemon process. -# The setting is particularly useful for tweaking memory settings. -org.gradle.jvmargs=-Xmx1536m - -# When configured, Gradle will run in incubating parallel mode. -# This option should only be used with decoupled projects. More details, visit -# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects -# org.gradle.parallel=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 13372ae..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index c7a4e33..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Mon Mar 20 10:01:35 CST 2017 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.3.1-all.zip diff --git a/gradlew b/gradlew deleted file mode 100644 index 9d82f78..0000000 --- a/gradlew +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 8a0b282..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/leetcode.iml b/leetcode.iml deleted file mode 100644 index ce86a2c..0000000 --- a/leetcode.iml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/leetcode/common/common.iml b/leetcode/common/common.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/leetcode/common/common.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/library/src/main/java/com/leetcode/library/CommonUtils.java b/leetcode/common/src/CommonUtils.java similarity index 77% rename from library/src/main/java/com/leetcode/library/CommonUtils.java rename to leetcode/common/src/CommonUtils.java index f40173c..4e25df5 100644 --- a/library/src/main/java/com/leetcode/library/CommonUtils.java +++ b/leetcode/common/src/CommonUtils.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by dingjikerbo on 2016/12/12. - */ - public class CommonUtils { diff --git a/library/src/main/java/com/leetcode/library/Interval.java b/leetcode/common/src/Interval.java similarity index 76% rename from library/src/main/java/com/leetcode/library/Interval.java rename to leetcode/common/src/Interval.java index b1e3dd6..749239e 100644 --- a/library/src/main/java/com/leetcode/library/Interval.java +++ b/leetcode/common/src/Interval.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by dingjikerbo on 16/11/20. - */ - /** * Definition for an interval. */ diff --git a/library/src/main/java/com/leetcode/library/ListNode.java b/leetcode/common/src/ListNode.java similarity index 83% rename from library/src/main/java/com/leetcode/library/ListNode.java rename to leetcode/common/src/ListNode.java index 7902529..02be290 100644 --- a/library/src/main/java/com/leetcode/library/ListNode.java +++ b/leetcode/common/src/ListNode.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - public class ListNode { public int val; diff --git a/library/src/main/java/com/leetcode/library/NestedInteger.java b/leetcode/common/src/NestedInteger.java similarity index 87% rename from library/src/main/java/com/leetcode/library/NestedInteger.java rename to leetcode/common/src/NestedInteger.java index ce8f1d3..39cb29e 100644 --- a/library/src/main/java/com/leetcode/library/NestedInteger.java +++ b/leetcode/common/src/NestedInteger.java @@ -1,11 +1,5 @@ -package com.leetcode.library; - import java.util.List; -/** - * Created by dingjikerbo on 2016/11/22. - */ - public interface NestedInteger { // @return true if this NestedInteger holds a single integer, rather than a nested list. diff --git a/library/src/main/java/com/leetcode/library/Point.java b/leetcode/common/src/Point.java similarity index 87% rename from library/src/main/java/com/leetcode/library/Point.java rename to leetcode/common/src/Point.java index aeda913..991a20a 100644 --- a/library/src/main/java/com/leetcode/library/Point.java +++ b/leetcode/common/src/Point.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by dingjikerbo on 16/12/7. - */ - class Point { int x; int y; diff --git a/library/src/main/java/com/leetcode/library/RandomListNode.java b/leetcode/common/src/RandomListNode.java similarity index 68% rename from library/src/main/java/com/leetcode/library/RandomListNode.java rename to leetcode/common/src/RandomListNode.java index e3eb267..8816baa 100644 --- a/library/src/main/java/com/leetcode/library/RandomListNode.java +++ b/leetcode/common/src/RandomListNode.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by liwentian on 17/8/9. - */ - public class RandomListNode { public int label; public RandomListNode next, random; diff --git a/library/src/main/java/com/leetcode/library/TreeLinkNode.java b/leetcode/common/src/TreeLinkNode.java similarity index 72% rename from library/src/main/java/com/leetcode/library/TreeLinkNode.java rename to leetcode/common/src/TreeLinkNode.java index d1122b3..0b21dca 100644 --- a/library/src/main/java/com/leetcode/library/TreeLinkNode.java +++ b/leetcode/common/src/TreeLinkNode.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by dingjikerbo on 16/11/23. - */ - /** * Definition for binary tree with next pointer. */ diff --git a/library/src/main/java/com/leetcode/library/TreeNode.java b/leetcode/common/src/TreeNode.java similarity index 93% rename from library/src/main/java/com/leetcode/library/TreeNode.java rename to leetcode/common/src/TreeNode.java index e028f26..6a1f777 100644 --- a/library/src/main/java/com/leetcode/library/TreeNode.java +++ b/leetcode/common/src/TreeNode.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - public class TreeNode { public int val; diff --git a/library/src/main/java/com/leetcode/library/TrieNode.java b/leetcode/common/src/TrieNode.java similarity index 64% rename from library/src/main/java/com/leetcode/library/TrieNode.java rename to leetcode/common/src/TrieNode.java index 5053139..58a80df 100644 --- a/library/src/main/java/com/leetcode/library/TrieNode.java +++ b/leetcode/common/src/TrieNode.java @@ -1,9 +1,3 @@ -package com.leetcode.library; - -/** - * Created by dingjikerbo on 2016/11/22. - */ - public class TrieNode { public TrieNode[] nodes; diff --git a/library/src/main/java/com/leetcode/library/UndirectedGraphNode.java b/leetcode/common/src/UndirectedGraphNode.java similarity index 78% rename from library/src/main/java/com/leetcode/library/UndirectedGraphNode.java rename to leetcode/common/src/UndirectedGraphNode.java index 068b8c6..5193303 100644 --- a/library/src/main/java/com/leetcode/library/UndirectedGraphNode.java +++ b/leetcode/common/src/UndirectedGraphNode.java @@ -1,12 +1,6 @@ -package com.leetcode.library; - import java.util.ArrayList; import java.util.List; -/** - * Created by dingjikerbo on 16/12/19. - */ - public class UndirectedGraphNode { public int label; diff --git a/leetcode/common/src/Utils.java b/leetcode/common/src/Utils.java new file mode 100644 index 0000000..fdedf69 --- /dev/null +++ b/leetcode/common/src/Utils.java @@ -0,0 +1,10 @@ +public class Utils { + + public static int max(int... val) { + int max = Integer.MIN_VALUE; + for (int k : val) { + max = Math.max(max, k); + } + return max; + } +} diff --git a/leetcode/leetcode.iml b/leetcode/leetcode.iml new file mode 100644 index 0000000..da061d4 --- /dev/null +++ b/leetcode/leetcode.iml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/leetcode/solution/solution.iml b/leetcode/solution/solution.iml new file mode 100644 index 0000000..99e828d --- /dev/null +++ b/leetcode/solution/solution.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/leetcode/solution/src/AddBinary.java b/leetcode/solution/src/AddBinary.java new file mode 100644 index 0000000..b755a6c --- /dev/null +++ b/leetcode/solution/src/AddBinary.java @@ -0,0 +1,14 @@ +public class AddBinary { + + public String addBinary(String a, String b) { + StringBuilder sb = new StringBuilder(); + for (int i = a.length() - 1, j = b.length() - 1, flag = 0; i >= 0 || j >= 0 || flag > 0; i--, j--) { + int k1 = i >= 0 ? a.charAt(i) - '0' : 0; + int k2 = j >= 0 ? b.charAt(j) - '0' : 0; + int sum = k1 + k2 + flag; + sb.append(sum % 2); + flag = sum / 2; + } + return sb.reverse().toString(); + } +} diff --git a/solution/src/main/java/com/inuker/solution/AddTwoNumber.java b/leetcode/solution/src/AddTwoNumber.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/AddTwoNumber.java rename to leetcode/solution/src/AddTwoNumber.java index 42c3576..9469ff4 100644 --- a/solution/src/main/java/com/inuker/solution/AddTwoNumber.java +++ b/leetcode/solution/src/AddTwoNumber.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - public class AddTwoNumber { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { diff --git a/solution/src/main/java/com/inuker/solution/AddTwoNumbersII.java b/leetcode/solution/src/AddTwoNumbersII.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/AddTwoNumbersII.java rename to leetcode/solution/src/AddTwoNumbersII.java index 7331e93..08ca684 100644 --- a/solution/src/main/java/com/inuker/solution/AddTwoNumbersII.java +++ b/leetcode/solution/src/AddTwoNumbersII.java @@ -1,13 +1,5 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - import java.util.Stack; -/** - * Created by liwentian on 2017/9/11. - */ - public class AddTwoNumbersII { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { diff --git a/solution/src/main/java/com/inuker/solution/AlienDictionary.java b/leetcode/solution/src/AlienDictionary.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/AlienDictionary.java rename to leetcode/solution/src/AlienDictionary.java index 8c45184..6fd8f05 100644 --- a/solution/src/main/java/com/inuker/solution/AlienDictionary.java +++ b/leetcode/solution/src/AlienDictionary.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Set; +import java.util.*; /** - * Created by dingjikerbo on 16/12/17. *

* TestCases * "z", "z" => "z" diff --git a/solution/src/main/java/com/inuker/solution/AndroidUnlockPatterns.java b/leetcode/solution/src/AndroidUnlockPatterns.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/AndroidUnlockPatterns.java rename to leetcode/solution/src/AndroidUnlockPatterns.java index e3790fb..6912537 100644 --- a/solution/src/main/java/com/inuker/solution/AndroidUnlockPatterns.java +++ b/leetcode/solution/src/AndroidUnlockPatterns.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/6. - */ - /** * https://leetcode.com/articles/android-unlock-patterns/ */ diff --git a/solution/src/main/java/com/inuker/solution/AverageOfLevelsInBinaryTree.java b/leetcode/solution/src/AverageOfLevelsInBinaryTree.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/AverageOfLevelsInBinaryTree.java rename to leetcode/solution/src/AverageOfLevelsInBinaryTree.java index ff9b246..1324566 100644 --- a/solution/src/main/java/com/inuker/solution/AverageOfLevelsInBinaryTree.java +++ b/leetcode/solution/src/AverageOfLevelsInBinaryTree.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * Created by dingjikerbo on 2017/7/22. - */ - public class AverageOfLevelsInBinaryTree { public List averageOfLevels(TreeNode root) { diff --git a/solution/src/main/java/com/inuker/solution/BSTIterator.java b/leetcode/solution/src/BSTIterator.java similarity index 55% rename from solution/src/main/java/com/inuker/solution/BSTIterator.java rename to leetcode/solution/src/BSTIterator.java index a3dc689..1b6519d 100644 --- a/solution/src/main/java/com/inuker/solution/BSTIterator.java +++ b/leetcode/solution/src/BSTIterator.java @@ -1,25 +1,13 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.Stack; -/** - * Created by dingjikerbo on 16/11/21. - */ - public class BSTIterator { private Stack mStack; private TreeNode mCurNode; public BSTIterator(TreeNode root) { - mStack = new Stack(); + mStack = new Stack<>(); mCurNode = root; - -// for (mCurNode = root; mCurNode != null; mCurNode = mCurNode.left) { -// mStack.push(mCurNode); -// } } /** @@ -49,19 +37,4 @@ public int next() { return result; } - - /** 这样写也好,不过要注意在构造函数中初始化如上注释部分 - public int next() { - if (mCurNode == null) { - mCurNode = mStack.pop(); - } - - int val = mCurNode.val; - - for (mCurNode = mCurNode.right; mCurNode != null; mCurNode = mCurNode.left) { - mStack.push(mCurNode); - } - - return val; - }*/ } diff --git a/leetcode/solution/src/BackspaceStringCompare.java b/leetcode/solution/src/BackspaceStringCompare.java new file mode 100644 index 0000000..8d00fe6 --- /dev/null +++ b/leetcode/solution/src/BackspaceStringCompare.java @@ -0,0 +1,35 @@ +import java.util.Stack; + +public class BackspaceStringCompare { + + public boolean backspaceCompare(String S, String T) { + Stack stack1 = new Stack<>(); + Stack stack2 = new Stack<>(); + for (int i = 0; i < S.length(); i++) { + helper(stack1, S, i); + } + for (int i = 0; i < T.length(); i++) { + helper(stack2, T, i); + } + while (!stack1.isEmpty() && !stack2.isEmpty()) { + if (!stack1.pop().equals(stack2.pop())) { + return false; + } + } + return stack1.isEmpty() && stack2.isEmpty(); + } + + private void helper(Stack stack, String s, int i) { + if (i >= s.length()) { + return; + } + char c = s.charAt(i); + if (c == '#') { + if (!stack.isEmpty()) { + stack.pop(); + } + } else { + stack.push(c); + } + } +} diff --git a/solution/src/main/java/com/inuker/solution/BalancedBinaryTree.java b/leetcode/solution/src/BalancedBinaryTree.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/BalancedBinaryTree.java rename to leetcode/solution/src/BalancedBinaryTree.java index 525fe8a..0e88812 100644 --- a/solution/src/main/java/com/inuker/solution/BalancedBinaryTree.java +++ b/leetcode/solution/src/BalancedBinaryTree.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/28. - */ - -import com.leetcode.library.TreeNode; - /** * 平衡二叉树条件是左边是平衡,右边是平衡,且两边高度差相差不超过1 * 树的高度是所有子树的最大高度 diff --git a/solution/src/main/java/com/inuker/solution/BasicCalculator.java b/leetcode/solution/src/BasicCalculator.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/BasicCalculator.java rename to leetcode/solution/src/BasicCalculator.java index 51194d3..a246d72 100644 --- a/solution/src/main/java/com/inuker/solution/BasicCalculator.java +++ b/leetcode/solution/src/BasicCalculator.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Stack; -/** - * Created by liwentian on 2017/9/12. - */ - public class BasicCalculator { public int calculate(String s) { diff --git a/solution/src/main/java/com/inuker/solution/BeautifulArrangement.java b/leetcode/solution/src/BeautifulArrangement.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/BeautifulArrangement.java rename to leetcode/solution/src/BeautifulArrangement.java index de49e8b..8c7ebb0 100644 --- a/solution/src/main/java/com/inuker/solution/BeautifulArrangement.java +++ b/leetcode/solution/src/BeautifulArrangement.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/6. - */ - /** * https://leetcode.com/articles/beautiful-arrangement/ */ diff --git a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStock.java b/leetcode/solution/src/BestTimeBuySellStock.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/BestTimeBuySellStock.java rename to leetcode/solution/src/BestTimeBuySellStock.java index 19fd88f..8661ea7 100644 --- a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStock.java +++ b/leetcode/solution/src/BestTimeBuySellStock.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - /** * https://leetcode.com/articles/best-time-buy-and-sell-stock/ */ diff --git a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockII.java b/leetcode/solution/src/BestTimeBuySellStockII.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/BestTimeBuySellStockII.java rename to leetcode/solution/src/BestTimeBuySellStockII.java index c26588f..4428037 100644 --- a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockII.java +++ b/leetcode/solution/src/BestTimeBuySellStockII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - /** * https://leetcode.com/articles/best-time-buy-and-sell-stock-ii/ */ diff --git a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIII.java b/leetcode/solution/src/BestTimeBuySellStockIII.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIII.java rename to leetcode/solution/src/BestTimeBuySellStockIII.java index 7505fe0..f97d430 100644 --- a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIII.java +++ b/leetcode/solution/src/BestTimeBuySellStockIII.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - -/** - */ public class BestTimeBuySellStockIII { public int maxProfit(int[] prices) { diff --git a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIV.java b/leetcode/solution/src/BestTimeBuySellStockIV.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIV.java rename to leetcode/solution/src/BestTimeBuySellStockIV.java index 62733db..72e784e 100644 --- a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockIV.java +++ b/leetcode/solution/src/BestTimeBuySellStockIV.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - -/** - */ public class BestTimeBuySellStockIV { public int maxProfit(int k, int[] prices) { diff --git a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockWithCoolDown.java b/leetcode/solution/src/BestTimeBuySellStockWithCoolDown.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/BestTimeBuySellStockWithCoolDown.java rename to leetcode/solution/src/BestTimeBuySellStockWithCoolDown.java index ad799c9..e0acc92 100644 --- a/solution/src/main/java/com/inuker/solution/BestTimeBuySellStockWithCoolDown.java +++ b/leetcode/solution/src/BestTimeBuySellStockWithCoolDown.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - -/** - */ public class BestTimeBuySellStockWithCoolDown { public int maxProfit(int[] prices) { diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeInorderTraversal.java b/leetcode/solution/src/BinaryTreeInorderTraversal.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/BinaryTreeInorderTraversal.java rename to leetcode/solution/src/BinaryTreeInorderTraversal.java index 4b65895..f7cc6c1 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeInorderTraversal.java +++ b/leetcode/solution/src/BinaryTreeInorderTraversal.java @@ -1,14 +1,10 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; /** - * Created by dingjikerbo on 16/12/1. + * https://leetcode.com/articles/binary-tree-inorder-traversal/ */ public class BinaryTreeInorderTraversal { diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversal.java b/leetcode/solution/src/BinaryTreeLevelOrderTraversal.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversal.java rename to leetcode/solution/src/BinaryTreeLevelOrderTraversal.java index 4b8e235..f132a20 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversal.java +++ b/leetcode/solution/src/BinaryTreeLevelOrderTraversal.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * Created by dingjikerbo on 2016/11/17. - */ - public class BinaryTreeLevelOrderTraversal { // 耗时2ms diff --git a/amazon/src/main/java/com/leetcode/amazon/BinaryTreeLevelOrderTraversal.java b/leetcode/solution/src/BinaryTreeLevelOrderTraversalII.java similarity index 66% rename from amazon/src/main/java/com/leetcode/amazon/BinaryTreeLevelOrderTraversal.java rename to leetcode/solution/src/BinaryTreeLevelOrderTraversalII.java index 470d700..f14eb4c 100644 --- a/amazon/src/main/java/com/leetcode/amazon/BinaryTreeLevelOrderTraversal.java +++ b/leetcode/solution/src/BinaryTreeLevelOrderTraversalII.java @@ -1,18 +1,12 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * Created by liwentian on 17/8/12. - */ - -public class BinaryTreeLevelOrderTraversal { +public class BinaryTreeLevelOrderTraversalII { - public List> levelOrder(TreeNode root) { + // 耗时2ms,和I一样,只不过加到result时添加到头 + public List> levelOrderBottom(TreeNode root) { List> result = new LinkedList<>(); if (root == null) { @@ -22,36 +16,33 @@ public List> levelOrder(TreeNode root) { Queue queue = new LinkedList<>(); Queue next = new LinkedList<>(); - queue.add(root); - List list = null; + queue.offer(root); + while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (list == null) { - list = new LinkedList<>(); + list = new ArrayList<>(); } list.add(node.val); if (node.left != null) { - next.add(node.left); + next.offer(node.left); } - if (node.right != null) { - next.add(node.right); + next.offer(node.right); } if (queue.isEmpty()) { - result.add(list); - list = null; - queue.addAll(next); next.clear(); + result.add(0, list); + list = null; } } - return result; } } diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeLongestConsecutiveSequence.java b/leetcode/solution/src/BinaryTreeLongestConsecutiveSequence.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/BinaryTreeLongestConsecutiveSequence.java rename to leetcode/solution/src/BinaryTreeLongestConsecutiveSequence.java index a766b34..611244b 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeLongestConsecutiveSequence.java +++ b/leetcode/solution/src/BinaryTreeLongestConsecutiveSequence.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/2. - */ - -import com.leetcode.library.TreeNode; - /** * https://leetcode.com/articles/binary-tree-longest-consecutive-sequence/ */ diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeMaximumPathSum.java b/leetcode/solution/src/BinaryTreeMaximumPathSum.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/BinaryTreeMaximumPathSum.java rename to leetcode/solution/src/BinaryTreeMaximumPathSum.java index e67097c..d7159b2 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeMaximumPathSum.java +++ b/leetcode/solution/src/BinaryTreeMaximumPathSum.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/28. - */ - -import com.leetcode.library.TreeNode; - /** * 单边的或者双边的,或只包含根节点的 */ diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreePaths.java b/leetcode/solution/src/BinaryTreePaths.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/BinaryTreePaths.java rename to leetcode/solution/src/BinaryTreePaths.java index 1a919b5..a09e484 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreePaths.java +++ b/leetcode/solution/src/BinaryTreePaths.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/11/20. - */ - public class BinaryTreePaths { // 耗时2ms diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreePostorderTraversal.java b/leetcode/solution/src/BinaryTreePostorderTraversal.java similarity index 50% rename from solution/src/main/java/com/inuker/solution/BinaryTreePostorderTraversal.java rename to leetcode/solution/src/BinaryTreePostorderTraversal.java index 019889b..fe59430 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreePostorderTraversal.java +++ b/leetcode/solution/src/BinaryTreePostorderTraversal.java @@ -1,15 +1,4 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 16/12/1. - */ +import java.util.*; public class BinaryTreePostorderTraversal { @@ -33,4 +22,28 @@ public List postorderTraversal(TreeNode root) { } return results; } + + // root为null表示栈顶的左子树都访问完了,该看右子树了 + public List postorderTraversal2(TreeNode root) { + List result = new ArrayList<>(); + Stack stack = new Stack<>(); + + for (TreeNode last = null; !stack.isEmpty() || root != null; ) { + if (root != null) { + stack.push(root); + root = root.left; + } else { + TreeNode peek = stack.peek(); + if (peek.right != null && last != peek.right) { + root = peek.right; // 只有这里要设置root + } else { + result.add(peek.val); + last = stack.pop(); + // 此时root仍为null + } + } + } + + return result; + } } diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreePreorderTraversal.java b/leetcode/solution/src/BinaryTreePreorderTraversal.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/BinaryTreePreorderTraversal.java rename to leetcode/solution/src/BinaryTreePreorderTraversal.java index e88e4be..891c8e3 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreePreorderTraversal.java +++ b/leetcode/solution/src/BinaryTreePreorderTraversal.java @@ -1,16 +1,8 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; -/** - * Created by dingjikerbo on 16/12/1. - */ - public class BinaryTreePreorderTraversal { public List preorderTraversal(TreeNode root) { diff --git a/leetcode/solution/src/BinaryTreePruning.java b/leetcode/solution/src/BinaryTreePruning.java new file mode 100644 index 0000000..4853336 --- /dev/null +++ b/leetcode/solution/src/BinaryTreePruning.java @@ -0,0 +1,21 @@ +public class BinaryTreePruning { + + public TreeNode pruneTree(TreeNode root) { + return helper(root) ? root : null; + } + + private boolean helper(TreeNode root) { + if (root == null) { + return false; + } + boolean left = helper(root.left); + boolean right = helper(root.right); + if (!left) { + root.left = null; + } + if (!right) { + root.right = null; + } + return root.val == 1 || left || right; + } +} diff --git a/amazon/src/main/java/com/leetcode/amazon/BinaryTreeRightSideView.java b/leetcode/solution/src/BinaryTreeRightSideView.java similarity index 72% rename from amazon/src/main/java/com/leetcode/amazon/BinaryTreeRightSideView.java rename to leetcode/solution/src/BinaryTreeRightSideView.java index 62ff01d..4a8dcc8 100644 --- a/amazon/src/main/java/com/leetcode/amazon/BinaryTreeRightSideView.java +++ b/leetcode/solution/src/BinaryTreeRightSideView.java @@ -1,31 +1,28 @@ -package com.leetcode.amazon; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * Created by liwentian on 17/8/12. - */ - public class BinaryTreeRightSideView { public List rightSideView(TreeNode root) { - List list = new LinkedList<>(); + List result = new LinkedList<>(); if (root == null) { - return list; + return result; } Queue queue = new LinkedList<>(); Queue next = new LinkedList<>(); - queue.add(root); + + TreeNode last = null; + + queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); + last = node; + if (node.left != null) { next.offer(node.left); } @@ -35,13 +32,12 @@ public List rightSideView(TreeNode root) { } if (queue.isEmpty()) { - list.add(node.val); - queue.addAll(next); next.clear(); + result.add(last.val); } } - return list; + return result; } } diff --git a/leetcode/solution/src/BinaryTreeTilt.java b/leetcode/solution/src/BinaryTreeTilt.java new file mode 100644 index 0000000..43a56f1 --- /dev/null +++ b/leetcode/solution/src/BinaryTreeTilt.java @@ -0,0 +1,23 @@ +public class BinaryTreeTilt { + + int tilt = 0; + + /** + * 这题意思是遍历所有结点,对每个节点计算tilt,然后求和 + * 对于给定root,其tilt为左子树所有节点的和与右子树所有结点的和的差的绝对值 + */ + public int findTilt(TreeNode root) { + helper(root); + return tilt; + } + + private int helper(TreeNode root) { + if (root == null) { + return 0; + } + int left = helper(root.left); + int right = helper(root.right); + tilt += Math.abs(left - right); + return left + right + root.val; + } +} diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeUpsideDown.java b/leetcode/solution/src/BinaryTreeUpsideDown.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/BinaryTreeUpsideDown.java rename to leetcode/solution/src/BinaryTreeUpsideDown.java index 6dedc73..808936d 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeUpsideDown.java +++ b/leetcode/solution/src/BinaryTreeUpsideDown.java @@ -1,16 +1,9 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/12/2. - */ - public class BinaryTreeUpsideDown { /** * 将root的左子树看作一个整体,root.left就作为倒置后的root和root.right的新parent * 注意若root的左子树为空,则无法倒置了,什么也不做 + * 注意最后要给root的左右清零 */ public TreeNode upsideDownBinaryTree(TreeNode root) { if(root == null || root.left == null) { diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeVerticalOrderTraversal.java b/leetcode/solution/src/BinaryTreeVerticalOrderTraversal.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/BinaryTreeVerticalOrderTraversal.java rename to leetcode/solution/src/BinaryTreeVerticalOrderTraversal.java index 7440106..79365f5 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeVerticalOrderTraversal.java +++ b/leetcode/solution/src/BinaryTreeVerticalOrderTraversal.java @@ -1,16 +1,8 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * Created by dingjikerbo on 2016/11/19. - */ - public class BinaryTreeVerticalOrderTraversal { private int minKey = 0, maxKey = 0; diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeZigzagLevelOrderTraversal.java b/leetcode/solution/src/BinaryTreeZigzagLevelOrderTraversal.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/BinaryTreeZigzagLevelOrderTraversal.java rename to leetcode/solution/src/BinaryTreeZigzagLevelOrderTraversal.java index 5175477..8641f80 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeZigzagLevelOrderTraversal.java +++ b/leetcode/solution/src/BinaryTreeZigzagLevelOrderTraversal.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/2. - */ - public class BinaryTreeZigzagLevelOrderTraversal { public List> zigzagLevelOrder(TreeNode root) { diff --git a/solution/src/main/java/com/inuker/solution/BinaryWatch.java b/leetcode/solution/src/BinaryWatch.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/BinaryWatch.java rename to leetcode/solution/src/BinaryWatch.java index 4c08f08..d23e246 100644 --- a/solution/src/main/java/com/inuker/solution/BinaryWatch.java +++ b/leetcode/solution/src/BinaryWatch.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by liwentian on 2016/12/29. - */ - public class BinaryWatch { public List readBinaryWatch(int num) { diff --git a/solution/src/main/java/com/inuker/solution/BombEnemy.java b/leetcode/solution/src/BombEnemy.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/BombEnemy.java rename to leetcode/solution/src/BombEnemy.java index 2c66aef..0f75d72 100644 --- a/solution/src/main/java/com/inuker/solution/BombEnemy.java +++ b/leetcode/solution/src/BombEnemy.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/11. - */ - public class BombEnemy { public int maxKilledEnemies(char[][] grid) { diff --git a/solution/src/main/java/com/inuker/solution/BulbSwitcher.java b/leetcode/solution/src/BulbSwitcher.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/BulbSwitcher.java rename to leetcode/solution/src/BulbSwitcher.java index 499c847..ba9d281 100644 --- a/solution/src/main/java/com/inuker/solution/BulbSwitcher.java +++ b/leetcode/solution/src/BulbSwitcher.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/8. - */ - public class BulbSwitcher { /** * https://discuss.leetcode.com/topic/39558/share-my-o-1-solution-with-explanation/2 diff --git a/leetcode/solution/src/BullsAndCows.java b/leetcode/solution/src/BullsAndCows.java new file mode 100644 index 0000000..4e1c7b1 --- /dev/null +++ b/leetcode/solution/src/BullsAndCows.java @@ -0,0 +1,44 @@ +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +public class BullsAndCows { + + public String getHint(String secret, String guess) { + HashMap> map1 = new HashMap<>(); + HashMap> map2 = new HashMap<>(); + for (int i = 0; i < secret.length(); i++) { + Set set = map1.getOrDefault(secret.charAt(i), new HashSet<>()); + set.add(i); + map1.put(secret.charAt(i), set); + } + for (int i = 0; i < guess.length(); i++) { + Set set = map2.getOrDefault(guess.charAt(i), new HashSet<>()); + set.add(i); + map2.put(guess.charAt(i), set); + } + int bulls = 0, cows = 0; + for (Character c : map2.keySet()) { + Set set1 = map1.get(c); + + if (set1 == null) { + continue; + } + + Set set2 = map2.get(c); + + int count = 0; + + for (Integer index : set2) { + if (set1.contains(index)) { + count++; + } + } + + bulls += count; + cows += Math.min(set1.size(), set2.size()) - count; + } + + return String.format("%dA%dB", bulls, cows); + } +} diff --git a/solution/src/main/java/com/inuker/solution/BurstBalloons.java b/leetcode/solution/src/BurstBalloons.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/BurstBalloons.java rename to leetcode/solution/src/BurstBalloons.java index dc1f2e8..c05a99a 100644 --- a/solution/src/main/java/com/inuker/solution/BurstBalloons.java +++ b/leetcode/solution/src/BurstBalloons.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/21. - */ - /** * 这题用的闭区间DP,dp[start][end]表示区间start,end内所有气球爆掉的最大coin * 假设最后爆第i个气球,start <= i <= end,则对应的coin为 diff --git a/solution/src/main/java/com/inuker/solution/CanArrangeWords.java b/leetcode/solution/src/CanArrangeWords.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/CanArrangeWords.java rename to leetcode/solution/src/CanArrangeWords.java index f14128c..a48632a 100644 --- a/solution/src/main/java/com/inuker/solution/CanArrangeWords.java +++ b/leetcode/solution/src/CanArrangeWords.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.HashSet; -/** - * Created by dingjikerbo on 2017/9/29. - */ - /** * 单词接龙,前一个单词的尾巴和后一个单词的头相同就算接上了 * 如果要返回接龙的结果,可以给HashSet改成List diff --git a/leetcode/solution/src/Candy.java b/leetcode/solution/src/Candy.java new file mode 100644 index 0000000..2540129 --- /dev/null +++ b/leetcode/solution/src/Candy.java @@ -0,0 +1,50 @@ +import java.util.Arrays; + +public class Candy { + + public int candy(int[] ratings) { + int[] left = new int[ratings.length]; + int[] right = new int[ratings.length]; + + Arrays.fill(left, 1); + Arrays.fill(right, 1); + + for (int i = 1; i < ratings.length; i++) { + if (ratings[i] > ratings[i - 1]) { + left[i] = left[i - 1] + 1; + } + } + for (int i = ratings.length - 2; i >= 0; i--) { + if (ratings[i] > ratings[i + 1]) { + right[i] = right[i + 1] + 1; + } + } + int sum = 0; + for (int i = 0; i < ratings.length; i++) { + sum += Math.max(left[i], right[i]); + } + return sum; + } + + /** + * 在上面的基础上优化了一下,去掉了一个数组 + */ + public int candy2(int[] ratings) { + int[] candys = new int[ratings.length]; + + Arrays.fill(candys, 1); + + for (int i = 1; i < ratings.length; i++) { + if (ratings[i] > ratings[i - 1]) { + candys[i] = candys[i - 1] + 1; + } + } + int sum = candys[ratings.length - 1], prev = 1; + for (int i = ratings.length - 2; i >= 0; i--) { + int cur = ratings[i] > ratings[i + 1] ? prev + 1 : 1; + sum += Math.max(cur, candys[i]); + prev = cur; + } + return sum; + } +} diff --git a/solution/src/main/java/com/inuker/solution/CloneGraph.java b/leetcode/solution/src/CloneGraph.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/CloneGraph.java rename to leetcode/solution/src/CloneGraph.java index bb03431..087d010 100644 --- a/solution/src/main/java/com/inuker/solution/CloneGraph.java +++ b/leetcode/solution/src/CloneGraph.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.UndirectedGraphNode; - import java.util.HashMap; import java.util.LinkedList; import java.util.Map; -/** - * Created by dingjikerbo on 2016/12/21. - */ - public class CloneGraph { /** diff --git a/solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValue.java b/leetcode/solution/src/ClosestBinarySearchTreeValue.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValue.java rename to leetcode/solution/src/ClosestBinarySearchTreeValue.java index 4335590..3a2adf6 100644 --- a/solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValue.java +++ b/leetcode/solution/src/ClosestBinarySearchTreeValue.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/12/2. - */ - public class ClosestBinarySearchTreeValue { public int closestValue(TreeNode root, double target) { diff --git a/solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValueII.java b/leetcode/solution/src/ClosestBinarySearchTreeValueII.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValueII.java rename to leetcode/solution/src/ClosestBinarySearchTreeValueII.java index 2c9c360..41edbf3 100644 --- a/solution/src/main/java/com/inuker/solution/ClosestBinarySearchTreeValueII.java +++ b/leetcode/solution/src/ClosestBinarySearchTreeValueII.java @@ -1,16 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; -/** - * Created by dingjikerbo on 2016/12/2. - */ - /** * 有三种解法: * 2,中序遍历两遍二叉树,不过每次都会中途退出,构成双栈,一个是大于target,一个是小于target,然后依次出栈满k为止,复杂度O(n + k) diff --git a/solution/src/main/java/com/inuker/solution/Codec.java b/leetcode/solution/src/Codec.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/Codec.java rename to leetcode/solution/src/Codec.java index d1d7d90..377fdb4 100644 --- a/solution/src/main/java/com/inuker/solution/Codec.java +++ b/leetcode/solution/src/Codec.java @@ -1,16 +1,4 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.Arrays; -import java.util.Deque; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Stack; - -/** - * Created by dingjikerbo on 2016/11/16. - */ +import java.util.*; /** * 类似题 @@ -62,7 +50,7 @@ private TreeNode helper(Queue queue) { return root; } - /** 下面是非递归版的DFS */ + /** 下面是非递归版的,前序遍历 */ public String serialize2(TreeNode root) { StringBuilder sb = new StringBuilder(); if (root == null) { @@ -86,7 +74,10 @@ public String serialize2(TreeNode root) { return sb.toString(); } - // Decodes your encoded data to tree. + /** + * 前序访问一遍所有结点 + * 在设置node时,从queue中取出值 + */ public TreeNode deserialize2(String data) { String[] texts = data.split(SEP); Queue queue = new LinkedList(Arrays.asList(texts)); diff --git a/leetcode/solution/src/CoinChange.java b/leetcode/solution/src/CoinChange.java new file mode 100644 index 0000000..66423ce --- /dev/null +++ b/leetcode/solution/src/CoinChange.java @@ -0,0 +1,20 @@ +import java.util.Arrays; + +public class CoinChange { + + public int coinChange(int[] coins, int amount) { + Arrays.sort(coins); + int[] dp = new int[amount + 1]; + Arrays.fill(dp, -1); + dp[0] = 0; + for (int i = 1; i <= amount; i++) { + for (int coin: coins) { + if (i - coin >= 0 && dp[i - coin] >= 0) { + int k = dp[i - coin] + 1; + dp[i] = dp[i] > 0 ? Math.min(dp[i], k) : k; + } + } + } + return dp[amount]; + } +} diff --git a/solution/src/main/java/com/inuker/solution/CombinationSum.java b/leetcode/solution/src/CombinationSum.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/CombinationSum.java rename to leetcode/solution/src/CombinationSum.java index e5e881d..824a65a 100644 --- a/solution/src/main/java/com/inuker/solution/CombinationSum.java +++ b/leetcode/solution/src/CombinationSum.java @@ -1,13 +1,6 @@ -package com.inuker.solution; - -import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/11/22. - */ - public class CombinationSum { // 耗时23ms diff --git a/solution/src/main/java/com/inuker/solution/CombinationSumII.java b/leetcode/solution/src/CombinationSumII.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/CombinationSumII.java rename to leetcode/solution/src/CombinationSumII.java index eb22a9e..2ab9acd 100644 --- a/solution/src/main/java/com/inuker/solution/CombinationSumII.java +++ b/leetcode/solution/src/CombinationSumII.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/11/22. - */ - public class CombinationSumII { // 耗时29ms diff --git a/solution/src/main/java/com/inuker/solution/CombinationSumIII.java b/leetcode/solution/src/CombinationSumIII.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/CombinationSumIII.java rename to leetcode/solution/src/CombinationSumIII.java index 4e4eccc..c64c203 100644 --- a/solution/src/main/java/com/inuker/solution/CombinationSumIII.java +++ b/leetcode/solution/src/CombinationSumIII.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/11/22. - */ - /** * 这题不允许重复数字 */ diff --git a/solution/src/main/java/com/inuker/solution/CombinationSumIV.java b/leetcode/solution/src/CombinationSumIV.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/CombinationSumIV.java rename to leetcode/solution/src/CombinationSumIV.java index 8f45652..3920298 100644 --- a/solution/src/main/java/com/inuker/solution/CombinationSumIV.java +++ b/leetcode/solution/src/CombinationSumIV.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 16/11/22. - */ - public class CombinationSumIV { /** diff --git a/solution/src/main/java/com/inuker/solution/Combinations.java b/leetcode/solution/src/Combinations.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/Combinations.java rename to leetcode/solution/src/Combinations.java index f2673a0..f4091d3 100644 --- a/solution/src/main/java/com/inuker/solution/Combinations.java +++ b/leetcode/solution/src/Combinations.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class Combinations { public List> combine(int n, int k) { diff --git a/solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromInorderAndPostorderTraversal.java b/leetcode/solution/src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromInorderAndPostorderTraversal.java rename to leetcode/solution/src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java index f841314..7610466 100644 --- a/solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromInorderAndPostorderTraversal.java +++ b/leetcode/solution/src/ConstructBinaryTreeFromInorderAndPostorderTraversal.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/12/2. - */ - public class ConstructBinaryTreeFromInorderAndPostorderTraversal { public TreeNode buildTree(int[] inorder, int[] postorder) { diff --git a/leetcode/solution/src/ConstructBinaryTreeFromPreorderAndPostorderTraversal.java b/leetcode/solution/src/ConstructBinaryTreeFromPreorderAndPostorderTraversal.java new file mode 100644 index 0000000..93a2492 --- /dev/null +++ b/leetcode/solution/src/ConstructBinaryTreeFromPreorderAndPostorderTraversal.java @@ -0,0 +1,29 @@ +import java.util.HashMap; + +public class ConstructBinaryTreeFromPreorderAndPostorderTraversal { + + /** + * 这里先记录一下post每个数对应的索引,免得每次去找 + * 不过找找也没关系,因为每个元素不会重复找 + */ + public TreeNode constructFromPrePost(int[] pre, int[] post) { + HashMap map = new HashMap<>(); + for (int i = 0; i < post.length; i++) { + map.put(post[i], i); + } + return helper(pre, 0, pre.length - 1, post, 0, post.length - 1, map); + } + + private TreeNode helper(int[] pre, int prestart, int preend, int[] post, int poststart, int postend, HashMap map) { + if (prestart > preend || poststart > postend) { + return null; + } + TreeNode root = new TreeNode(pre[prestart]); + if (prestart + 1 <= preend) { + int len = map.get(pre[prestart + 1]) - poststart + 1; + root.left = helper(pre, prestart + 1, prestart + len, post, poststart, poststart + len - 1, map); + root.right = helper(pre, prestart + len + 1, preend, post, poststart + len, postend - 1, map); + } + return root; + } +} diff --git a/solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromPreorderInorderTraversal.java b/leetcode/solution/src/ConstructBinaryTreeFromPreorderInorderTraversal.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromPreorderInorderTraversal.java rename to leetcode/solution/src/ConstructBinaryTreeFromPreorderInorderTraversal.java index d3fb909..58477f7 100644 --- a/solution/src/main/java/com/inuker/solution/ConstructBinaryTreeFromPreorderInorderTraversal.java +++ b/leetcode/solution/src/ConstructBinaryTreeFromPreorderInorderTraversal.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/11/30. - */ - public class ConstructBinaryTreeFromPreorderInorderTraversal { public TreeNode buildTree(int[] preorder, int[] inorder) { diff --git a/leetcode/solution/src/ConstructStringFromBinaryTree.java b/leetcode/solution/src/ConstructStringFromBinaryTree.java new file mode 100644 index 0000000..0aed8b5 --- /dev/null +++ b/leetcode/solution/src/ConstructStringFromBinaryTree.java @@ -0,0 +1,29 @@ +/** + * https://leetcode.com/articles/construct-string-from-binary-tree/ + */ + +/** + * 这题不难,主要是搞清楚题目意思 + * 即返回root + (左子树) + (右子树) + * 不过要注意几个特殊情况,如果左右子树都为null,则只返回root + * 如果左子树为null,右子树非null,则返回root + () + (右子树) + * 如果左子树非null,右子树为null,则返回root + (左子树) + */ +public class ConstructStringFromBinaryTree { + + /** + * 左子树如果为空'()'是不能省略的 + * 右子树如果为空可以省略 + */ + public String tree2str(TreeNode t) { + if (t == null) { + return ""; + } + if (t.left == null && t.right == null) { + return t.val + ""; + } + String left = "(" + tree2str(t.left) + ")"; + String right = t.right != null ? "(" + tree2str(t.right) + ")" : ""; + return t.val + left + right; + } +} diff --git a/solution/src/main/java/com/inuker/solution/ContainerWithMostWater.java b/leetcode/solution/src/ContainerWithMostWater.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/ContainerWithMostWater.java rename to leetcode/solution/src/ContainerWithMostWater.java index dce553d..75232b4 100644 --- a/solution/src/main/java/com/inuker/solution/ContainerWithMostWater.java +++ b/leetcode/solution/src/ContainerWithMostWater.java @@ -1,14 +1,9 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/5/2. - */ - /** * 题目的意思是选定两块板子组成一个桶,使得装水量最大。注意其余的板子都忽略。 * 一种O(n)的方法是对于区间[left, right],假如height[left] < height[right],则我们可以认定[left, right - 1],[left, right - 2] ... * 都不会比[left, right]装的水更多。原因是木桶的短板没变,所以水平面不会变,但是宽度减小了。 * 所以我们要继续尝试的方向是从较短的一方推进,寄希望于其之后的板子能高一点 + * 如果两边一样高,那随便推进哪一边都行,因为假如之后还能装更多水,一定不会包含这两边任意一块。如果包含了,水量不会超过当前。 */ public class ContainerWithMostWater { diff --git a/solution/src/main/java/com/inuker/solution/ContainsDuplicate.java b/leetcode/solution/src/ContainsDuplicate.java similarity index 76% rename from solution/src/main/java/com/inuker/solution/ContainsDuplicate.java rename to leetcode/solution/src/ContainsDuplicate.java index c642c0c..3a56afa 100644 --- a/solution/src/main/java/com/inuker/solution/ContainsDuplicate.java +++ b/leetcode/solution/src/ContainsDuplicate.java @@ -1,13 +1,5 @@ -package com.inuker.solution; - -import java.util.HashMap; import java.util.HashSet; import java.util.Set; -import java.util.TreeSet; - -/** - * Created by dingjikerbo on 16/12/8. - */ /** * https://leetcode.com/articles/contains-duplicate/ diff --git a/solution/src/main/java/com/inuker/solution/ContainsDuplicateII.java b/leetcode/solution/src/ContainsDuplicateII.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/ContainsDuplicateII.java rename to leetcode/solution/src/ContainsDuplicateII.java index a2225ef..0e0ac92 100644 --- a/solution/src/main/java/com/inuker/solution/ContainsDuplicateII.java +++ b/leetcode/solution/src/ContainsDuplicateII.java @@ -1,12 +1,5 @@ -package com.inuker.solution; - import java.util.HashMap; import java.util.HashSet; -import java.util.Set; - -/** - * Created by dingjikerbo on 16/12/8. - */ /** * https://leetcode.com/articles/contains-duplicate-ii/ diff --git a/solution/src/main/java/com/inuker/solution/ContainsDuplicateIII.java b/leetcode/solution/src/ContainsDuplicateIII.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/ContainsDuplicateIII.java rename to leetcode/solution/src/ContainsDuplicateIII.java index e7ca4b8..a4d844c 100644 --- a/solution/src/main/java/com/inuker/solution/ContainsDuplicateIII.java +++ b/leetcode/solution/src/ContainsDuplicateIII.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.HashMap; import java.util.Map; import java.util.TreeSet; -/** - * Created by dingjikerbo on 16/12/8. - */ - /** * https://leetcode.com/articles/contains-duplicate-iii/ */ @@ -16,8 +10,7 @@ public class ContainsDuplicateIII { /** * 这题要注意溢出问题,干脆都用long * 时间复杂度O(nlg(min(n,k)) - * for循环走到当前的nums[i]说明之前的都不行,因此只要判断当前 - * nums[i]的加入是否可以即可,因此只要判断nums[i]相邻的上下两个数是否在t范围内 + * 这里相当于维护了一个window,每次新遍历到一个数,都查看上下相邻的数是否满足条件 */ public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { TreeSet set = new TreeSet<>(); diff --git a/leetcode/solution/src/ConvertBSTToGreaterTree.java b/leetcode/solution/src/ConvertBSTToGreaterTree.java new file mode 100644 index 0000000..f9fe841 --- /dev/null +++ b/leetcode/solution/src/ConvertBSTToGreaterTree.java @@ -0,0 +1,26 @@ +import java.util.Stack; + +/** + * https://leetcode.com/articles/convert-bst-to-greater-tree/ + */ +public class ConvertBSTToGreaterTree { + + public TreeNode convertBST(TreeNode root) { + Stack stack = new Stack<>(); + int sum = 0; + TreeNode node = root; + while (!stack.isEmpty() || node != null) { + if (node != null) { + stack.push(node); + node = node.right; + } else { + node = stack.pop(); + int s = sum; + sum += node.val; + node.val += s; + node = node.left; + } + } + return root; + } +} diff --git a/solution/src/main/java/com/inuker/solution/ConvertSortedArrayToBinarySearchTree.java b/leetcode/solution/src/ConvertSortedArrayToBinarySearchTree.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/ConvertSortedArrayToBinarySearchTree.java rename to leetcode/solution/src/ConvertSortedArrayToBinarySearchTree.java index 6e9d784..a81ae81 100644 --- a/solution/src/main/java/com/inuker/solution/ConvertSortedArrayToBinarySearchTree.java +++ b/leetcode/solution/src/ConvertSortedArrayToBinarySearchTree.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/11/28. - */ - public class ConvertSortedArrayToBinarySearchTree { public TreeNode sortedArrayToBST(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/ConvertSortedListToBinarySearchTree.java b/leetcode/solution/src/ConvertSortedListToBinarySearchTree.java similarity index 80% rename from solution/src/main/java/com/inuker/solution/ConvertSortedListToBinarySearchTree.java rename to leetcode/solution/src/ConvertSortedListToBinarySearchTree.java index eea3e9d..6723b13 100644 --- a/solution/src/main/java/com/inuker/solution/ConvertSortedListToBinarySearchTree.java +++ b/leetcode/solution/src/ConvertSortedListToBinarySearchTree.java @@ -1,12 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; -import com.leetcode.library.TreeNode; - -/** - * Created by liwentian on 2017/9/11. - */ - public class ConvertSortedListToBinarySearchTree { public TreeNode sortedListToBST(ListNode head) { diff --git a/leetcode/solution/src/CopyListWithRandomPointer.java b/leetcode/solution/src/CopyListWithRandomPointer.java new file mode 100644 index 0000000..19c0f75 --- /dev/null +++ b/leetcode/solution/src/CopyListWithRandomPointer.java @@ -0,0 +1,32 @@ +/** + * 易错的地方在于random要判空 + */ +public class CopyListWithRandomPointer { + + + public RandomListNode copyRandomList(RandomListNode head) { + for (RandomListNode p = head; p != null; ) { + RandomListNode next = p.next; + RandomListNode temp = new RandomListNode(p.label); + temp.next = p.next; + p.next = temp; + p = next; + } + for (RandomListNode p = head; p != null; ) { + if (p.random != null) { + p.next.random = p.random.next; + } + p = p.next.next; + } + RandomListNode dummy = new RandomListNode(0), cur = dummy; + for (RandomListNode p = head; p != null; ) { + cur.next = p.next; + cur = cur.next; + p.next = p.next.next; + p = p.next; + } + return dummy.next; + } +} + + diff --git a/solution/src/main/java/com/inuker/solution/CountAndSay.java b/leetcode/solution/src/CountAndSay.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/CountAndSay.java rename to leetcode/solution/src/CountAndSay.java index 2e9c9af..ec3f9b2 100644 --- a/solution/src/main/java/com/inuker/solution/CountAndSay.java +++ b/leetcode/solution/src/CountAndSay.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/22. - */ - public class CountAndSay { public String countAndSay(int n) { diff --git a/solution/src/main/java/com/inuker/solution/CountCompleteTreeNodes.java b/leetcode/solution/src/CountCompleteTreeNodes.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/CountCompleteTreeNodes.java rename to leetcode/solution/src/CountCompleteTreeNodes.java index 5650df6..0dfa900 100644 --- a/solution/src/main/java/com/inuker/solution/CountCompleteTreeNodes.java +++ b/leetcode/solution/src/CountCompleteTreeNodes.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/11/29. - */ - public class CountCompleteTreeNodes { /** 适合通用的二叉树,但是对于完全二叉树会超时 @@ -34,7 +26,7 @@ public int countNodes(TreeNode root) { return count; }*/ - // 119ms,最差复杂度是O(n),最好是O(lgn) + // 119ms,最差复杂度是O((lgn)^2),最好是O(lgn) public int countNodes(TreeNode root) { int left = 0, right = 0; for (TreeNode node = root; node != null; node = node.left, left++); diff --git a/solution/src/main/java/com/inuker/solution/CountNumberWithUniqueDigits.java b/leetcode/solution/src/CountNumberWithUniqueDigits.java similarity index 80% rename from solution/src/main/java/com/inuker/solution/CountNumberWithUniqueDigits.java rename to leetcode/solution/src/CountNumberWithUniqueDigits.java index 4fab953..50283e3 100644 --- a/solution/src/main/java/com/inuker/solution/CountNumberWithUniqueDigits.java +++ b/leetcode/solution/src/CountNumberWithUniqueDigits.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2016/12/29. - */ - public class CountNumberWithUniqueDigits { public int countNumbersWithUniqueDigits(int n) { diff --git a/solution/src/main/java/com/inuker/solution/CountOfSmallerNumbersAfterSelf.java b/leetcode/solution/src/CountOfSmallerNumbersAfterSelf.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/CountOfSmallerNumbersAfterSelf.java rename to leetcode/solution/src/CountOfSmallerNumbersAfterSelf.java index 4fab12b..4aa9c80 100644 --- a/solution/src/main/java/com/inuker/solution/CountOfSmallerNumbersAfterSelf.java +++ b/leetcode/solution/src/CountOfSmallerNumbersAfterSelf.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/21. - */ - /** * 这题理解了好久才搞明白 * 建立一棵二叉树,从数组末尾开始遍历,这里每个树的节点要记录sum和dup diff --git a/solution/src/main/java/com/inuker/solution/CountPrimes.java b/leetcode/solution/src/CountPrimes.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/CountPrimes.java rename to leetcode/solution/src/CountPrimes.java index d14a019..e0ddfd0 100644 --- a/solution/src/main/java/com/inuker/solution/CountPrimes.java +++ b/leetcode/solution/src/CountPrimes.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import java.util.Arrays; - -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * 如果一个数是另一个数的倍数,那这个数肯定不是素数。 * 利用这个性质,我们可以建立一个素数数组,从2开始将素数的倍数都标注为不是素数。 diff --git a/leetcode/solution/src/CountReversePairs.java b/leetcode/solution/src/CountReversePairs.java new file mode 100644 index 0000000..d3f38a1 --- /dev/null +++ b/leetcode/solution/src/CountReversePairs.java @@ -0,0 +1,17 @@ +public class CountReversePairs { + + /** + * 数组arr,[0,m)和[m,arr.length)两个区间都是递增的 + * 如果[0,m)区间的数比[m, arr.len)区间大,则能构成一个reverse pair + * 问有多少个reverse pair + */ + int reversePairs(int[] arr, int m) { + int pairs = 0; + for (int i = m - 1, j = arr.length - 1; j >= m; j--) { + for ( ; i >= 0 && arr[i] > arr[j]; i--); + pairs += m - 1 - i; + } + return pairs; + } +} + diff --git a/solution/src/main/java/com/inuker/solution/CountUnivalueSubtrees.java b/leetcode/solution/src/CountUnivalueSubtrees.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/CountUnivalueSubtrees.java rename to leetcode/solution/src/CountUnivalueSubtrees.java index c7933ff..be56ecc 100644 --- a/solution/src/main/java/com/inuker/solution/CountUnivalueSubtrees.java +++ b/leetcode/solution/src/CountUnivalueSubtrees.java @@ -1,13 +1,8 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/12/1. - */ - public class CountUnivalueSubtrees { + /** + * 先分别判断左右子树是不是unival,如果是再判断带上root后是不是unival + */ public int countUnivalSubtrees(TreeNode root) { int[] count = new int[1]; helper(root, count); diff --git a/solution/src/main/java/com/inuker/solution/CourseSchedule.java b/leetcode/solution/src/CourseSchedule.java similarity index 81% rename from solution/src/main/java/com/inuker/solution/CourseSchedule.java rename to leetcode/solution/src/CourseSchedule.java index 21bd7da..12a928d 100644 --- a/solution/src/main/java/com/inuker/solution/CourseSchedule.java +++ b/leetcode/solution/src/CourseSchedule.java @@ -1,15 +1,4 @@ -package com.inuker.solution; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.Set; - -/** - * Created by dingjikerbo on 2016/12/17. - */ +import java.util.*; public class CourseSchedule { diff --git a/solution/src/main/java/com/inuker/solution/CourseScheduleII.java b/leetcode/solution/src/CourseScheduleII.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/CourseScheduleII.java rename to leetcode/solution/src/CourseScheduleII.java index 203bc7e..95fc851 100644 --- a/solution/src/main/java/com/inuker/solution/CourseScheduleII.java +++ b/leetcode/solution/src/CourseScheduleII.java @@ -1,15 +1,8 @@ -package com.inuker.solution; - -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class CourseScheduleII { public int[] findOrder(int numCourses, int[][] prerequisites) { diff --git a/solution/src/main/java/com/inuker/solution/DecodeString.java b/leetcode/solution/src/DecodeString.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/DecodeString.java rename to leetcode/solution/src/DecodeString.java index a316137..48315d9 100644 --- a/solution/src/main/java/com/inuker/solution/DecodeString.java +++ b/leetcode/solution/src/DecodeString.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import java.util.Stack; - -/** - * Created by dingjikerbo on 2016/12/11. - */ - public class DecodeString { /** diff --git a/leetcode/solution/src/DecodeWays.java b/leetcode/solution/src/DecodeWays.java new file mode 100644 index 0000000..f204f7f --- /dev/null +++ b/leetcode/solution/src/DecodeWays.java @@ -0,0 +1,24 @@ +/** + * TestCases + * "" + * "1" + * "1787897759966261825913315262377298132516969578441236833255596967132573482281598412163216914566534565" + * "7893749912342187894921836847319981199844151766195952528631828655978178193192959793156142441128167383" + */ +public class DecodeWays { + + // DP,耗时1ms + public int numDecodings(String s) { + int len = s.length(); + int[] dp = new int[len]; + for (int i = 0; i < len; i++) { + if (s.charAt(i) != '0') { + dp[i] = i > 0 ? dp[i - 1] : 1; + } + if (i > 0 && (s.charAt(i - 1) == '1' || (s.charAt(i - 1) == '2' && s.charAt(i) <= '6'))) { + dp[i] += i > 1 ? dp[i - 2] : 1; + } + } + return dp[len - 1]; + } +} diff --git a/solution/src/main/java/com/inuker/solution/DeleteNodeInALinkedList.java b/leetcode/solution/src/DeleteNodeInALinkedList.java similarity index 66% rename from solution/src/main/java/com/inuker/solution/DeleteNodeInALinkedList.java rename to leetcode/solution/src/DeleteNodeInALinkedList.java index 9648546..d7d9aa0 100644 --- a/solution/src/main/java/com/inuker/solution/DeleteNodeInALinkedList.java +++ b/leetcode/solution/src/DeleteNodeInALinkedList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/11. - */ - -import com.leetcode.library.ListNode; - /** * https://leetcode.com/articles/delete-node-linked-list/ */ diff --git a/solution/src/main/java/com/inuker/solution/DeleteNodeInBST.java b/leetcode/solution/src/DeleteNodeInBST.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/DeleteNodeInBST.java rename to leetcode/solution/src/DeleteNodeInBST.java index f40bd3a..b33cc58 100644 --- a/solution/src/main/java/com/inuker/solution/DeleteNodeInBST.java +++ b/leetcode/solution/src/DeleteNodeInBST.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 17/1/2. - */ - public class DeleteNodeInBST { public TreeNode deleteNode(TreeNode root, int key) { diff --git a/leetcode/solution/src/DiameterOfBinaryTree.java b/leetcode/solution/src/DiameterOfBinaryTree.java new file mode 100644 index 0000000..3974e27 --- /dev/null +++ b/leetcode/solution/src/DiameterOfBinaryTree.java @@ -0,0 +1,31 @@ +public class DiameterOfBinaryTree { + + /** + * 这题和 124. Binary Tree Maximum Path Sum比较像 + */ + public int diameterOfBinaryTree(TreeNode root) { + if (root == null) { + return 0; + } + return dfs(root, new int[1]) - 1; + } + + /** + * len表示带上root的最大深度 + */ + private int dfs(TreeNode root, int[] len) { + if (root == null) { + return 0; + } + + int[] lt = new int[1]; + int[] rt = new int[1]; + + int left = dfs(root.left, lt); + int right = dfs(root.right, rt); + + len[0] = Math.max(lt[0], rt[0]) + 1; + + return Math.max(Math.max(left, right), lt[0] + rt[0] + 1); + } +} diff --git a/solution/src/main/java/com/inuker/solution/DifferenceWaysToAddParentheses.java b/leetcode/solution/src/DifferenceWaysToAddParentheses.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/DifferenceWaysToAddParentheses.java rename to leetcode/solution/src/DifferenceWaysToAddParentheses.java index 4ae23c5..a176668 100644 --- a/solution/src/main/java/com/inuker/solution/DifferenceWaysToAddParentheses.java +++ b/leetcode/solution/src/DifferenceWaysToAddParentheses.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class DifferenceWaysToAddParentheses { public List diffWaysToCompute(String input) { diff --git a/solution/src/main/java/com/inuker/solution/DivideTwoIntegers.java b/leetcode/solution/src/DivideTwoIntegers.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/DivideTwoIntegers.java rename to leetcode/solution/src/DivideTwoIntegers.java index fa64bc0..855a504 100644 --- a/solution/src/main/java/com/inuker/solution/DivideTwoIntegers.java +++ b/leetcode/solution/src/DivideTwoIntegers.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/1/12. - */ - public class DivideTwoIntegers { /** diff --git a/solution/src/main/java/com/inuker/solution/EditDistance.java b/leetcode/solution/src/EditDistance.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/EditDistance.java rename to leetcode/solution/src/EditDistance.java index 6aec8e1..95d8798 100644 --- a/solution/src/main/java/com/inuker/solution/EditDistance.java +++ b/leetcode/solution/src/EditDistance.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/15. - */ - /** * 这题非常重要的是对f的初始化,千万不能漏 * 所有DP问题都要注意初始化边界条件 diff --git a/solution/src/main/java/com/inuker/solution/EncodeAndDecodeStrings.java b/leetcode/solution/src/EncodeAndDecodeStrings.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/EncodeAndDecodeStrings.java rename to leetcode/solution/src/EncodeAndDecodeStrings.java index 9b88a71..f5b1bd2 100644 --- a/solution/src/main/java/com/inuker/solution/EncodeAndDecodeStrings.java +++ b/leetcode/solution/src/EncodeAndDecodeStrings.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/11. - */ - public class EncodeAndDecodeStrings { /** diff --git a/solution/src/main/java/com/inuker/solution/EncodeAndDecodeTinyURL.java b/leetcode/solution/src/EncodeAndDecodeTinyURL.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/EncodeAndDecodeTinyURL.java rename to leetcode/solution/src/EncodeAndDecodeTinyURL.java index 64e5d99..386e4fa 100644 --- a/solution/src/main/java/com/inuker/solution/EncodeAndDecodeTinyURL.java +++ b/leetcode/solution/src/EncodeAndDecodeTinyURL.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.HashMap; import java.util.Random; -/** - * Created by dingjikerbo on 2017/8/20. - */ - /** * https://leetcode.com/articles/encode-and-decode-tinyurl/ */ diff --git a/leetcode/solution/src/EvaluateDivision.java b/leetcode/solution/src/EvaluateDivision.java new file mode 100644 index 0000000..674b27b --- /dev/null +++ b/leetcode/solution/src/EvaluateDivision.java @@ -0,0 +1,67 @@ +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +/** + * 1, 首先给除的结果都存起来,建立有向图 + * 2,用DFS遍历路径 + */ +public class EvaluateDivision { + + public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { + HashMap> table = new HashMap<>(); + for (int i = 0; i < equations.length; i++) { + add(table, equations[i], values[i]); + } + double[] result = new double[queries.length]; + HashSet visited = new HashSet<>(); + for (int i = 0; i < queries.length; i++) { + visited.clear(); + result[i] = calc(table, visited, queries[i][0], queries[i][1]); + } + return result; + } + + private double calc(HashMap> table, HashSet visited, String a, String b) { + HashMap map = table.get(a); + if (map == null) { + return -1.0; + } + if (a.equals(b)) { + return 1.0; + } + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + Double value = entry.getValue(); + + if (visited.contains(key)) { + continue; + } + + visited.add(key); + + double t = calc(table, visited, key, b); + if (t != -1.0) { + return value * t; + } + + visited.remove(key); + } + return -1.0; + } + + private void add(HashMap> table, String[] equation, double value) { + HashMap map0 = table.get(equation[0]); + HashMap map1 = table.get(equation[1]); + if (map0 == null) { + map0 = new HashMap<>(); + table.put(equation[0], map0); + } + if (map1 == null) { + map1 = new HashMap<>(); + table.put(equation[1], map1); + } + map0.put(equation[1], value); + map1.put(equation[0], 1 / value); + } +} diff --git a/solution/src/main/java/com/inuker/solution/EvaluateReversePolishNotation.java b/leetcode/solution/src/EvaluateReversePolishNotation.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/EvaluateReversePolishNotation.java rename to leetcode/solution/src/EvaluateReversePolishNotation.java index bd85961..0099e69 100644 --- a/solution/src/main/java/com/inuker/solution/EvaluateReversePolishNotation.java +++ b/leetcode/solution/src/EvaluateReversePolishNotation.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Stack; -/** - * Created by liwentian on 2017/9/12. - */ - public class EvaluateReversePolishNotation { public int evalRPN(String[] tokens) { diff --git a/solution/src/main/java/com/inuker/solution/ExcelSheetColumnNumber.java b/leetcode/solution/src/ExcelSheetColumnNumber.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/ExcelSheetColumnNumber.java rename to leetcode/solution/src/ExcelSheetColumnNumber.java index 26fb5cd..4d8a79f 100644 --- a/solution/src/main/java/com/inuker/solution/ExcelSheetColumnNumber.java +++ b/leetcode/solution/src/ExcelSheetColumnNumber.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class ExcelSheetColumnNumber { public List binaryTreePaths(TreeNode root) { diff --git a/solution/src/main/java/com/inuker/solution/ExcelSheetColumnTitle.java b/leetcode/solution/src/ExcelSheetColumnTitle.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/ExcelSheetColumnTitle.java rename to leetcode/solution/src/ExcelSheetColumnTitle.java index a5ea8eb..88fcd30 100644 --- a/solution/src/main/java/com/inuker/solution/ExcelSheetColumnTitle.java +++ b/leetcode/solution/src/ExcelSheetColumnTitle.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class ExcelSheetColumnTitle { /** diff --git a/solution/src/main/java/com/inuker/solution/ExpressionAddOperators.java b/leetcode/solution/src/ExpressionAddOperators.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/ExpressionAddOperators.java rename to leetcode/solution/src/ExpressionAddOperators.java index 58e79c1..da1008c 100644 --- a/solution/src/main/java/com/inuker/solution/ExpressionAddOperators.java +++ b/leetcode/solution/src/ExpressionAddOperators.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/11/21. - */ - public class ExpressionAddOperators { /** diff --git a/solution/src/main/java/com/inuker/solution/FactorCombinations.java b/leetcode/solution/src/FactorCombinations.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/FactorCombinations.java rename to leetcode/solution/src/FactorCombinations.java index c6ac34c..b16a400 100644 --- a/solution/src/main/java/com/inuker/solution/FactorCombinations.java +++ b/leetcode/solution/src/FactorCombinations.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by liwentian on 2017/9/6. - */ - public class FactorCombinations { public List> getFactors(int n) { diff --git a/solution/src/main/java/com/inuker/solution/FactorialTrailingZeroes.java b/leetcode/solution/src/FactorialTrailingZeroes.java similarity index 69% rename from solution/src/main/java/com/inuker/solution/FactorialTrailingZeroes.java rename to leetcode/solution/src/FactorialTrailingZeroes.java index d0beb44..a816916 100644 --- a/solution/src/main/java/com/inuker/solution/FactorialTrailingZeroes.java +++ b/leetcode/solution/src/FactorialTrailingZeroes.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/7. - */ - public class FactorialTrailingZeroes { public int trailingZeroes(int n) { diff --git a/solution/src/main/java/com/inuker/solution/FindAllAnagramsInString.java b/leetcode/solution/src/FindAllAnagramsInString.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/FindAllAnagramsInString.java rename to leetcode/solution/src/FindAllAnagramsInString.java index 63c7aa4..98a9d5b 100644 --- a/solution/src/main/java/com/inuker/solution/FindAllAnagramsInString.java +++ b/leetcode/solution/src/FindAllAnagramsInString.java @@ -1,14 +1,7 @@ -package com.inuker.solution; - import java.util.ArrayList; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/11/17. - */ - public class FindAllAnagramsInString { // 耗时16ms,复杂度O(n) diff --git a/solution/src/main/java/com/inuker/solution/FindAllDuplicatesInAnArray.java b/leetcode/solution/src/FindAllDuplicatesInAnArray.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/FindAllDuplicatesInAnArray.java rename to leetcode/solution/src/FindAllDuplicatesInAnArray.java index 85961b4..5233bf3 100644 --- a/solution/src/main/java/com/inuker/solution/FindAllDuplicatesInAnArray.java +++ b/leetcode/solution/src/FindAllDuplicatesInAnArray.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by liwentian on 2017/9/10. - */ - public class FindAllDuplicatesInAnArray { public List findDuplicates(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/FindAllNumbersDisappearedInAnArray.java b/leetcode/solution/src/FindAllNumbersDisappearedInAnArray.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/FindAllNumbersDisappearedInAnArray.java rename to leetcode/solution/src/FindAllNumbersDisappearedInAnArray.java index 0269e8d..159043c 100644 --- a/solution/src/main/java/com/inuker/solution/FindAllNumbersDisappearedInAnArray.java +++ b/leetcode/solution/src/FindAllNumbersDisappearedInAnArray.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by liwentian on 2017/9/10. - */ - public class FindAllNumbersDisappearedInAnArray { //4,3,2,7,8,2,3,1 diff --git a/solution/src/main/java/com/inuker/solution/FindBottomLeftTreeValue.java b/leetcode/solution/src/FindBottomLeftTreeValue.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/FindBottomLeftTreeValue.java rename to leetcode/solution/src/FindBottomLeftTreeValue.java index dc12267..a177a75 100644 --- a/solution/src/main/java/com/inuker/solution/FindBottomLeftTreeValue.java +++ b/leetcode/solution/src/FindBottomLeftTreeValue.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.Queue; -/** - * Created by liwentian on 17/8/3. - */ - public class FindBottomLeftTreeValue { public int findBottomLeftValue(TreeNode root) { diff --git a/solution/src/main/java/com/inuker/solution/FindCelebrity.java b/leetcode/solution/src/FindCelebrity.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/FindCelebrity.java rename to leetcode/solution/src/FindCelebrity.java index 18ebcf7..09e1a45 100644 --- a/solution/src/main/java/com/inuker/solution/FindCelebrity.java +++ b/leetcode/solution/src/FindCelebrity.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/20. - */ - /** * 先用排除法扫一轮,剩下的是唯一的候选人,然后再严格判断 */ diff --git a/solution/src/main/java/com/inuker/solution/FindDuplicateSubtrees.java b/leetcode/solution/src/FindDuplicateSubtrees.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/FindDuplicateSubtrees.java rename to leetcode/solution/src/FindDuplicateSubtrees.java index e353480..7036b91 100644 --- a/solution/src/main/java/com/inuker/solution/FindDuplicateSubtrees.java +++ b/leetcode/solution/src/FindDuplicateSubtrees.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.HashMap; import java.util.LinkedList; import java.util.List; -/** - * Created by liwentian on 17/8/3. - */ - public class FindDuplicateSubtrees { /** diff --git a/solution/src/main/java/com/inuker/solution/FindKPairsWithSmallestSums.java b/leetcode/solution/src/FindKPairsWithSmallestSums.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/FindKPairsWithSmallestSums.java rename to leetcode/solution/src/FindKPairsWithSmallestSums.java index dad9523..0513bd1 100644 --- a/solution/src/main/java/com/inuker/solution/FindKPairsWithSmallestSums.java +++ b/leetcode/solution/src/FindKPairsWithSmallestSums.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; -/** - * Created by liwentian on 2017/9/22. - */ - public class FindKPairsWithSmallestSums { public List kSmallestPairs(int[] nums1, int[] nums2, int k) { diff --git a/solution/src/main/java/com/inuker/solution/FindLargestValueInEachTreeRow.java b/leetcode/solution/src/FindLargestValueInEachTreeRow.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/FindLargestValueInEachTreeRow.java rename to leetcode/solution/src/FindLargestValueInEachTreeRow.java index 4fd1361..2c2bd6f 100644 --- a/solution/src/main/java/com/inuker/solution/FindLargestValueInEachTreeRow.java +++ b/leetcode/solution/src/FindLargestValueInEachTreeRow.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * Created by liwentian on 17/7/25. - */ - public class FindLargestValueInEachTreeRow { public List largestValues(TreeNode root) { diff --git a/solution/src/main/java/com/inuker/solution/FindLeavesOfBinaryTree.java b/leetcode/solution/src/FindLeavesOfBinaryTree.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/FindLeavesOfBinaryTree.java rename to leetcode/solution/src/FindLeavesOfBinaryTree.java index b14a9df..d0fc777 100644 --- a/solution/src/main/java/com/inuker/solution/FindLeavesOfBinaryTree.java +++ b/leetcode/solution/src/FindLeavesOfBinaryTree.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/12/3. - */ - public class FindLeavesOfBinaryTree { public List> findLeaves(TreeNode root) { diff --git a/solution/src/main/java/com/inuker/solution/FindMedianFromDataStream.java b/leetcode/solution/src/FindMedianFromDataStream.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/FindMedianFromDataStream.java rename to leetcode/solution/src/FindMedianFromDataStream.java index 75b5ec5..9169ed3 100644 --- a/solution/src/main/java/com/inuker/solution/FindMedianFromDataStream.java +++ b/leetcode/solution/src/FindMedianFromDataStream.java @@ -1,13 +1,6 @@ -package com.inuker.solution; - -import java.util.Collections; import java.util.Comparator; import java.util.PriorityQueue; -/** - * Created by dingjikerbo on 17/1/2. - */ - public class FindMedianFromDataStream { /** diff --git a/solution/src/main/java/com/inuker/solution/FindMinimumInRotatedSortedArray.java b/leetcode/solution/src/FindMinimumInRotatedSortedArray.java similarity index 65% rename from solution/src/main/java/com/inuker/solution/FindMinimumInRotatedSortedArray.java rename to leetcode/solution/src/FindMinimumInRotatedSortedArray.java index 98145ac..4e452db 100644 --- a/solution/src/main/java/com/inuker/solution/FindMinimumInRotatedSortedArray.java +++ b/leetcode/solution/src/FindMinimumInRotatedSortedArray.java @@ -1,11 +1,14 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class FindMinimumInRotatedSortedArray { + /** + * 由于[left, right]区间内包含了最小值,nums[left]通常是比nums[right]大的 + * 如果nums[left] mMaxCount) { - mMaxElemSize = 1; - mMaxCount = mCurCount; - } - } else { - if (mCurCount == mMaxCount) { - modes[idx++] = mCurVal; - } - } - - helper(node.right); - } } diff --git a/solution/src/main/java/com/inuker/solution/FindPeakElement.java b/leetcode/solution/src/FindPeakElement.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/FindPeakElement.java rename to leetcode/solution/src/FindPeakElement.java index c868529..8b78217 100644 --- a/solution/src/main/java/com/inuker/solution/FindPeakElement.java +++ b/leetcode/solution/src/FindPeakElement.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - /** * https://leetcode.com/articles/find-peak-element/ */ diff --git a/solution/src/main/java/com/inuker/solution/FindRightInterval.java b/leetcode/solution/src/FindRightInterval.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/FindRightInterval.java rename to leetcode/solution/src/FindRightInterval.java index 8f2ee9a..bc914df 100644 --- a/solution/src/main/java/com/inuker/solution/FindRightInterval.java +++ b/leetcode/solution/src/FindRightInterval.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.Interval; - import java.util.Map; import java.util.TreeMap; -/** - * Created by liwentian on 2017/9/22. - */ - public class FindRightInterval { public int[] findRightInterval(Interval[] intervals) { diff --git a/leetcode/solution/src/FindTheClosestPalindrome.java b/leetcode/solution/src/FindTheClosestPalindrome.java new file mode 100644 index 0000000..dc3156f --- /dev/null +++ b/leetcode/solution/src/FindTheClosestPalindrome.java @@ -0,0 +1,28 @@ +public class FindTheClosestPalindrome { + + /** + * 此题只给出暴力法 + * 此种题目太math了,一般不会问 + */ + public String nearestPalindromic(String n) { + long val = Long.parseLong(n); + for (int i = 0; ; i++) { + long k1 = val - i, k2 = val + i; + if (isPalindrome(k1)) { + return String.valueOf(k1); + } + if (isPalindrome(k2)) { + return String.valueOf(k2); + } + } + } + + private boolean isPalindrome(long k) { + long x = k, rev = 0; + for ( ; k > 0; ) { + rev = rev * 10 + k % 10; + k /= 10; + } + return rev == x; + } +} diff --git a/solution/src/main/java/com/inuker/solution/FindTheDuplicateNumber.java b/leetcode/solution/src/FindTheDuplicateNumber.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/FindTheDuplicateNumber.java rename to leetcode/solution/src/FindTheDuplicateNumber.java index 72ad9e1..d6ac374 100644 --- a/solution/src/main/java/com/inuker/solution/FindTheDuplicateNumber.java +++ b/leetcode/solution/src/FindTheDuplicateNumber.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - /** * 题目的意思是有n+1个数,这些数的范围限定在[1,n],其中只有一个重复数,重复的次数不限 */ diff --git a/solution/src/main/java/com/inuker/solution/FirstBadVersion.java b/leetcode/solution/src/FirstBadVersion.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/FirstBadVersion.java rename to leetcode/solution/src/FirstBadVersion.java index d42389e..aca392a 100644 --- a/solution/src/main/java/com/inuker/solution/FirstBadVersion.java +++ b/leetcode/solution/src/FirstBadVersion.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/19. - */ - /** * https://leetcode.com/articles/first-bad-version/ */ diff --git a/solution/src/main/java/com/inuker/solution/FirstMissingPositive.java b/leetcode/solution/src/FirstMissingPositive.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/FirstMissingPositive.java rename to leetcode/solution/src/FirstMissingPositive.java index 4a72ea4..8c04de3 100644 --- a/solution/src/main/java/com/inuker/solution/FirstMissingPositive.java +++ b/leetcode/solution/src/FirstMissingPositive.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/5/11. - */ - /** * 这里要注意的是nums[nums[i] - 1] != nums[i]这个条件,意思是目标坑和当前坑的值不等,此时才能swap * 倘若换成nums[i] - 1 != i是不行的,这表示目标坑和当前坑不是一个坑就swap,会死循环 @@ -12,7 +6,7 @@ public class FirstMissingPositive { public int firstMissingPositive(int[] nums) { for (int i = 0; i < nums.length; i++) { - while (nums[i] >= 1 && nums[i] <= nums.length && nums[nums[i] - 1] != nums[i]) { + while (nums[i] - 1 >= 0 && nums[i] - 1 < nums.length && nums[nums[i] - 1] != nums[i]) { swap(nums, i, nums[i] - 1); } } diff --git a/amazon/src/main/java/com/leetcode/amazon/FirstUniqueCharacterInAString.java b/leetcode/solution/src/FirstUniqueCharacterInAString.java similarity index 83% rename from amazon/src/main/java/com/leetcode/amazon/FirstUniqueCharacterInAString.java rename to leetcode/solution/src/FirstUniqueCharacterInAString.java index 206cba8..c0966a8 100644 --- a/amazon/src/main/java/com/leetcode/amazon/FirstUniqueCharacterInAString.java +++ b/leetcode/solution/src/FirstUniqueCharacterInAString.java @@ -1,11 +1,6 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/10. - */ - public class FirstUniqueCharacterInAString { + // 耗时21ms,O(2n) public int firstUniqChar(String s) { int[] cnt = new int[26]; for (char c : s.toCharArray()) { diff --git a/solution/src/main/java/com/inuker/solution/FizzBuzz.java b/leetcode/solution/src/FizzBuzz.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/FizzBuzz.java rename to leetcode/solution/src/FizzBuzz.java index 34cb0b6..776b9bf 100644 --- a/solution/src/main/java/com/inuker/solution/FizzBuzz.java +++ b/leetcode/solution/src/FizzBuzz.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/12/7. - */ - public class FizzBuzz { public List fizzBuzz(int n) { diff --git a/solution/src/main/java/com/inuker/solution/FlattenBinaryTreeToLinkedList.java b/leetcode/solution/src/FlattenBinaryTreeToLinkedList.java similarity index 72% rename from solution/src/main/java/com/inuker/solution/FlattenBinaryTreeToLinkedList.java rename to leetcode/solution/src/FlattenBinaryTreeToLinkedList.java index 53b2985..60028c4 100644 --- a/solution/src/main/java/com/inuker/solution/FlattenBinaryTreeToLinkedList.java +++ b/leetcode/solution/src/FlattenBinaryTreeToLinkedList.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.ArrayList; import java.util.List; import java.util.Stack; -/** - * Created by dingjikerbo on 16/11/30. - */ - public class FlattenBinaryTreeToLinkedList { /** @@ -40,22 +32,25 @@ public void flatten2(TreeNode root) { helper(root); } + /** + * 这题要注意ltail和rtail都为null的情况 + */ public TreeNode helper(TreeNode root) { if (root == null) { - return null; + return root; } + + TreeNode ltail = helper(root.left); + TreeNode rtail = helper(root.right); + TreeNode right = root.right; - TreeNode leftTail = null, rightTail = null; - if (root.left != null) { - leftTail = helper(root.left); + if (ltail != null) { root.right = root.left; root.left = null; - leftTail.right = right; + ltail.right = right; } - rightTail = helper(right); - - return rightTail != null ? rightTail : leftTail; + return rtail != null ? rtail : ltail != null ? ltail : root; } } diff --git a/solution/src/main/java/com/inuker/solution/FlattenNestedListIterator.java b/leetcode/solution/src/FlattenNestedListIterator.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/FlattenNestedListIterator.java rename to leetcode/solution/src/FlattenNestedListIterator.java index 56c4bff..eb7d611 100644 --- a/solution/src/main/java/com/inuker/solution/FlattenNestedListIterator.java +++ b/leetcode/solution/src/FlattenNestedListIterator.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.NestedInteger; - import java.util.Iterator; import java.util.List; import java.util.Stack; -/** - * Created by dingjikerbo on 2016/11/22. - */ - public abstract class FlattenNestedListIterator implements Iterator { private Stack stack; diff --git a/solution/src/main/java/com/inuker/solution/FlipGame.java b/leetcode/solution/src/FlipGame.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/FlipGame.java rename to leetcode/solution/src/FlipGame.java index 472b455..030671f 100644 --- a/solution/src/main/java/com/inuker/solution/FlipGame.java +++ b/leetcode/solution/src/FlipGame.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by liwentian on 2017/9/6. - */ - public class FlipGame { public List generatePossibleNextMoves(String s) { diff --git a/solution/src/main/java/com/inuker/solution/FlipGameII.java b/leetcode/solution/src/FlipGameII.java similarity index 78% rename from solution/src/main/java/com/inuker/solution/FlipGameII.java rename to leetcode/solution/src/FlipGameII.java index 97f56a7..29ead0e 100644 --- a/solution/src/main/java/com/inuker/solution/FlipGameII.java +++ b/leetcode/solution/src/FlipGameII.java @@ -1,12 +1,3 @@ -package com.inuker.solution; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/6. - */ - public class FlipGameII { public boolean canWin(String s) { diff --git a/solution/src/main/java/com/inuker/solution/FourSum.java b/leetcode/solution/src/FourSum.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/FourSum.java rename to leetcode/solution/src/FourSum.java index 2225598..0f9f8f4 100644 --- a/solution/src/main/java/com/inuker/solution/FourSum.java +++ b/leetcode/solution/src/FourSum.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 17/5/5. - */ - /** * 本题要注意的一个是溢出,一个是查重 */ diff --git a/leetcode/solution/src/FriendCircles.java b/leetcode/solution/src/FriendCircles.java new file mode 100644 index 0000000..56a5144 --- /dev/null +++ b/leetcode/solution/src/FriendCircles.java @@ -0,0 +1,69 @@ +public class FriendCircles { + + public int findCircleNum(int[][] M) { + int num = 0; + for (int i = 0; i < M.length; i++) { + if (M[i][i] == 1) { + dfs(M, i); + num++; + } + } + return num; + } + + /** + * M[i][i] = 0表示第i个人我们已经访问过了 + * 访问过的人无需重复访问 + */ + private void dfs(int[][] M, int i) { + M[i][i] = 0; + for (int j = 0; j < M.length; j++) { + if (M[j][j] != 0 && M[i][j] == 1) { + dfs(M, j); + } + } + } + + public int findCircleNum2(int[][] M) { + int n = M.length; + UnionFind uf = new UnionFind(n); + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (M[i][j] == 1) { + uf.union(i, j); + } + } + } + return uf.count(); + } + + class UnionFind { + int[] path; + int count; + + public UnionFind(int n) { + path = new int[n]; + count = n; + for (int i = 0; i < n; i++) { + path[i] = i; + } + } + + public int find(int i) { + while (i != path[i]) i = path[i]; + return i; + } + + public void union(int i, int j) { + int rootI = find(i); + int rootJ = find(j); + if (rootI == rootJ) return; + path[rootI] = rootJ; + count--; + } + + public int count() { + return count; + } + } +} diff --git a/leetcode/solution/src/FruitIntoBaskets.java b/leetcode/solution/src/FruitIntoBaskets.java new file mode 100644 index 0000000..e193da3 --- /dev/null +++ b/leetcode/solution/src/FruitIntoBaskets.java @@ -0,0 +1,31 @@ +import java.util.HashMap; + +/** + * 这题和sliding window较类似 + * 意思是给定一个数组,找出其中的一个最长的连续子数组,只能有两个不同的数 + */ +public class FruitIntoBaskets { + + + public static int totalFruit(int[] tree) { + int max = 0; + HashMap map = new HashMap<>(); + for (int i = 0, j = 0; j < tree.length; j++) { + int value = tree[j]; + + map.put(value, map.getOrDefault(value, 0) + 1); + + for ( ; map.size() > 2; i++) { + int val = tree[i], cnt = map.get(val); + if (cnt == 1) { + map.remove(val); + } else { + map.put(val, cnt - 1); + } + } + max = Math.max(max, j - i + 1); + } + + return max; + } +} diff --git a/solution/src/main/java/com/inuker/solution/GameOfLife.java b/leetcode/solution/src/GameOfLife.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/GameOfLife.java rename to leetcode/solution/src/GameOfLife.java index ebaca62..3d5744c 100644 --- a/solution/src/main/java/com/inuker/solution/GameOfLife.java +++ b/leetcode/solution/src/GameOfLife.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class GameOfLife { public void gameOfLife(int[][] board) { diff --git a/solution/src/main/java/com/inuker/solution/GeneralizedAbbreviation.java b/leetcode/solution/src/GeneralizedAbbreviation.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/GeneralizedAbbreviation.java rename to leetcode/solution/src/GeneralizedAbbreviation.java index ccc62bc..dca0bfb 100644 --- a/solution/src/main/java/com/inuker/solution/GeneralizedAbbreviation.java +++ b/leetcode/solution/src/GeneralizedAbbreviation.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by liwentian on 2016/12/29. - */ - /** * https://leetcode.com/articles/generalized-abbreviation/ * 思路就是back tracking,对于每个字母,到底是选择留下还是缩写 diff --git a/solution/src/main/java/com/inuker/solution/GenerateParentheses.java b/leetcode/solution/src/GenerateParentheses.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/GenerateParentheses.java rename to leetcode/solution/src/GenerateParentheses.java index a40c139..92acd47 100644 --- a/solution/src/main/java/com/inuker/solution/GenerateParentheses.java +++ b/leetcode/solution/src/GenerateParentheses.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/12/8. - */ - public class GenerateParentheses { // 耗时4ms diff --git a/solution/src/main/java/com/inuker/solution/GraphValidTree.java b/leetcode/solution/src/GraphValidTree.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/GraphValidTree.java rename to leetcode/solution/src/GraphValidTree.java index ab388a9..43912a4 100644 --- a/solution/src/main/java/com/inuker/solution/GraphValidTree.java +++ b/leetcode/solution/src/GraphValidTree.java @@ -1,7 +1,4 @@ -package com.inuker.solution; - /** - * Created by dingjikerbo on 17/1/2. *

* 判断无向图是否带环,可采用UF, DFS, BFS。 * UF实现简单,性能很好 @@ -16,12 +13,7 @@ * 题目中已声明不会有重复的边,类似[0,1]和[1,0]认为是重复的,也不会同时存在 */ -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.Set; +import java.util.*; /** * 这题就是给了一堆边,看这些边构成的无向图会不会有环,另外这些边是不是都连在一起的 diff --git a/solution/src/main/java/com/inuker/solution/GrayCode.java b/leetcode/solution/src/GrayCode.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/GrayCode.java rename to leetcode/solution/src/GrayCode.java index c5a1b6e..8947b74 100644 --- a/solution/src/main/java/com/inuker/solution/GrayCode.java +++ b/leetcode/solution/src/GrayCode.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/29. - */ - /** * 关键公式整数n的格雷码为n ^ (n / 2) */ diff --git a/amazon/src/main/java/com/leetcode/amazon/GroupAnagrams.java b/leetcode/solution/src/GroupAnagrams.java similarity index 89% rename from amazon/src/main/java/com/leetcode/amazon/GroupAnagrams.java rename to leetcode/solution/src/GroupAnagrams.java index 7b068c2..f96d3e4 100644 --- a/amazon/src/main/java/com/leetcode/amazon/GroupAnagrams.java +++ b/leetcode/solution/src/GroupAnagrams.java @@ -1,16 +1,11 @@ -package com.leetcode.amazon; - import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; -/** - * Created by liwentian on 17/8/13. - */ - public class GroupAnagrams { + // 12ms public List> groupAnagrams(String[] strs) { HashMap> map = new HashMap<>(); @@ -31,4 +26,5 @@ public List> groupAnagrams(String[] strs) { return new LinkedList<>(map.values()); } + } diff --git a/solution/src/main/java/com/inuker/solution/GroupShiftedStrings.java b/leetcode/solution/src/GroupShiftedStrings.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/GroupShiftedStrings.java rename to leetcode/solution/src/GroupShiftedStrings.java index 3d2877e..00a3249 100644 --- a/solution/src/main/java/com/inuker/solution/GroupShiftedStrings.java +++ b/leetcode/solution/src/GroupShiftedStrings.java @@ -1,14 +1,4 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Created by liwentian on 2017/12/9. - */ +import java.util.*; public class GroupShiftedStrings { /** diff --git a/solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLower.java b/leetcode/solution/src/GuessNumberHigherOrLower.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLower.java rename to leetcode/solution/src/GuessNumberHigherOrLower.java index 8902f74..da86cd6 100644 --- a/solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLower.java +++ b/leetcode/solution/src/GuessNumberHigherOrLower.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * 可参考官方文档 * https://leetcode.com/articles/guess-number-higher-or-lower/ diff --git a/solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLowerII.java b/leetcode/solution/src/GuessNumberHigherOrLowerII.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLowerII.java rename to leetcode/solution/src/GuessNumberHigherOrLowerII.java index 1757aed..7b0275c 100644 --- a/solution/src/main/java/com/inuker/solution/GuessNumberHigherOrLowerII.java +++ b/leetcode/solution/src/GuessNumberHigherOrLowerII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * 可参考官方文档 * https://leetcode.com/articles/guess-number-higher-or-lower-ii/ diff --git a/leetcode/solution/src/GuessTheWord.java b/leetcode/solution/src/GuessTheWord.java new file mode 100644 index 0000000..2a413fe --- /dev/null +++ b/leetcode/solution/src/GuessTheWord.java @@ -0,0 +1,41 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class GuessTheWord { + + public interface Master { + int guess(String word); + } + + /** + * 这题的意思是有一个word列表,取其中一个作为secret,现在让你来猜哪个是secret,最多猜10次, + * 你每猜一个单词,就告诉你这个单词和secret匹配的字母数。 + * 这里的思路很直接,就是随机取一个单词开始,获得了匹配的字母数后在单词列表中找到可能的候选项 + * 然后再迭代一次,这样猜10次 + */ + public void findSecretWord(String[] wordlist, Master master) { + Random random = new Random(); + for (int i = 0; i < 10; i++) { + String word = wordlist[random.nextInt(wordlist.length)]; + int match = master.guess(word); + List list = new ArrayList<>(); + for (String s : wordlist) { + if (match(s, word) == match) { + list.add(s); + } + } + wordlist = list.toArray(new String[0]); + } + } + + private int match(String s, String t) { + int match = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == t.charAt(i)) { + match++; + } + } + return match; + } +} diff --git a/solution/src/main/java/com/inuker/solution/HIndex.java b/leetcode/solution/src/HIndex.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/HIndex.java rename to leetcode/solution/src/HIndex.java index c519f2d..771e95e 100644 --- a/solution/src/main/java/com/inuker/solution/HIndex.java +++ b/leetcode/solution/src/HIndex.java @@ -1,10 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 16/11/23. - */ /** * https://leetcode.com/articles/h-index/ */ diff --git a/solution/src/main/java/com/inuker/solution/HIndexII.java b/leetcode/solution/src/HIndexII.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/HIndexII.java rename to leetcode/solution/src/HIndexII.java index 994e1a5..e9c5918 100644 --- a/solution/src/main/java/com/inuker/solution/HIndexII.java +++ b/leetcode/solution/src/HIndexII.java @@ -1,8 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ public class HIndexII { diff --git a/solution/src/main/java/com/inuker/solution/HammingDistance.java b/leetcode/solution/src/HammingDistance.java similarity index 70% rename from solution/src/main/java/com/inuker/solution/HammingDistance.java rename to leetcode/solution/src/HammingDistance.java index 1803ee6..eb2900a 100644 --- a/solution/src/main/java/com/inuker/solution/HammingDistance.java +++ b/leetcode/solution/src/HammingDistance.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/1/7. - */ - public class HammingDistance { public int hammingDistance(int x, int y) { diff --git a/solution/src/main/java/com/inuker/solution/HouseRobber.java b/leetcode/solution/src/HouseRobber.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/HouseRobber.java rename to leetcode/solution/src/HouseRobber.java index 58ccaf9..9ae674e 100644 --- a/solution/src/main/java/com/inuker/solution/HouseRobber.java +++ b/leetcode/solution/src/HouseRobber.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/1. - */ - public class HouseRobber { /** diff --git a/solution/src/main/java/com/inuker/solution/HouseRobberII.java b/leetcode/solution/src/HouseRobberII.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/HouseRobberII.java rename to leetcode/solution/src/HouseRobberII.java index 479a6e3..0865864 100644 --- a/solution/src/main/java/com/inuker/solution/HouseRobberII.java +++ b/leetcode/solution/src/HouseRobberII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ - public class HouseRobberII { public int rob(int[] nums) { diff --git a/leetcode/solution/src/HouseRobberIII.java b/leetcode/solution/src/HouseRobberIII.java new file mode 100644 index 0000000..3a2eb8f --- /dev/null +++ b/leetcode/solution/src/HouseRobberIII.java @@ -0,0 +1,48 @@ +public class HouseRobberIII { + + /** + * 效率堪忧,耗时1000ms + */ + public int rob(TreeNode root) { + return rob(root, true); + } + + /** + * @param rob true表示不定,false表示不选root + */ + private int rob(TreeNode root, boolean rob) { + if (root == null) { + return 0; + } + + if (rob) { + return Math.max(root.val + rob(root.left, false) + rob(root.right, false), + rob(root.left, true) + rob(root.right, true)); + } else { + return rob(root.left, true) + rob(root.right, true); + } + } + + /** + * 优化写法如下,耗时1ms + * 这里将两种情况都保存下来并返回给上层,避免了多次重复计算 + * val[0]表示不rob当前节点,val[1]表示rob当前节点 + */ + public int rob2(TreeNode root) { + int[] val = helper(root); + return Math.max(val[0], val[1]); + } + + private int[] helper(TreeNode node) { + if (node == null) { + return new int[]{0,0}; + } + int[] left = helper(node.left); + int[] right = helper(node.right); + int[] value = new int[2]; + value[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); + value[1] = node.val + left[0] + right[0]; + return value; + } + +} diff --git a/solution/src/main/java/com/inuker/solution/IncreasingTripletSubsequence.java b/leetcode/solution/src/IncreasingTripletSubsequence.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/IncreasingTripletSubsequence.java rename to leetcode/solution/src/IncreasingTripletSubsequence.java index f2e6528..8801679 100644 --- a/solution/src/main/java/com/inuker/solution/IncreasingTripletSubsequence.java +++ b/leetcode/solution/src/IncreasingTripletSubsequence.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - // 是longest increasing subsequence的简化版 public class IncreasingTripletSubsequence { diff --git a/solution/src/main/java/com/inuker/solution/InorderSuccessorInBST.java b/leetcode/solution/src/InorderSuccessorInBST.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/InorderSuccessorInBST.java rename to leetcode/solution/src/InorderSuccessorInBST.java index af0cff9..a68bb64 100644 --- a/solution/src/main/java/com/inuker/solution/InorderSuccessorInBST.java +++ b/leetcode/solution/src/InorderSuccessorInBST.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.List; import java.util.Stack; -/** - * Created by dingjikerbo on 16/11/20. - */ - /** * 有两种方法,用栈做普通的中序遍历,这种没有充分利用BST的特点 * 第二种方法比较巧妙,首先遍历到p,然后继续遍历找到p的右子树的最小值 @@ -37,20 +29,38 @@ public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { return null; } + // 耗时2ms,简单的递归写法,更容易理解 /** - * p的下一个节点一定是比p大的,所以这里遍历时当p的值小于当前节点,则当前节点 - * 可作为备选,同时往左走。如果在遍历过程中遇到仍然比p大的,说明更接近p,则更新备选。 - * - * 有两点要注意, - * 1, 首先res初始要为null,一个节点时,或root为null时,或p为最大节点时,res都没机会赋值 - * 2, 当root迭代到等于p时,走哪个分支呢,为什么选root = root.right,假如root.right为空,则之前的res即可,否则 - * 下一个迭代肯定走到root.val > p.val分支中,更新res。 - */ + public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { + if (root == null) { + return null; + } + if (p.val < root.val) { + TreeNode node = inorderSuccessor(root.left, p); + return node != null ? node : root; + } else { + return inorderSuccessor(root.right, p); + } + } + + public TreeNode predecessor(TreeNode root, TreeNode p) { + if (root == null) + return null; + + if (root.val >= p.val) { + return predecessor(root.left, p); + } else { + TreeNode right = predecessor(root.right, p); + return (right != null) ? right : root; + } + }*/ + + // 给上面的递归换成迭代写法 // 耗时4ms public TreeNode inorderSuccessor2(TreeNode root, TreeNode p) { TreeNode res = null; while (root != null) { - if (root.val > p.val) { + if (p.val < root.val) { res = root; root = root.left; } else { @@ -65,6 +75,8 @@ public TreeNode inorderSuccessor2(TreeNode root, TreeNode p) { * 给定Node,求其successor,步骤如下: * 1, 如果Node.right != null,则在Node.right中找最小的那个节点,即从Node.right开始,最左下角的节点 * 2, 如果Node.right == null,则不断往parent走,直到当前节点是其parent的左节点为止,其parent即为给定Node的successor + */ + /* private TreeNode inOrderSuccessor(TreeNode root, TreeNode node) { if (node.right != null) { return minValue(node.right); diff --git a/leetcode/solution/src/InsertDeleteGetRandom.java b/leetcode/solution/src/InsertDeleteGetRandom.java new file mode 100644 index 0000000..3be393b --- /dev/null +++ b/leetcode/solution/src/InsertDeleteGetRandom.java @@ -0,0 +1,56 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Random; + +/** + * 有几点要注意: + * remove时要判断删除的是不是最后一个,另外交换了结尾后要更新结尾数的idx + */ +// 耗时111ms +public class InsertDeleteGetRandom { + + ArrayList list; + HashMap map; + Random random; + + /** Initialize your data structure here. */ + public InsertDeleteGetRandom() { + map = new HashMap<>(); + list = new ArrayList<>(); + random = new Random(); + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + public boolean insert(int val) { + if (map.containsKey(val)) { + return false; + } + list.add(val); + map.put(val, list.size() - 1); + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + public boolean remove(int val) { + int index = map.getOrDefault(val, -1); + if (index < 0) { + return false; + } + if (index != list.size() - 1) { + int tail = list.get(list.size() - 1); + list.set(index, tail); + map.put(tail, index); + } + map.remove(val); + list.remove(list.size() - 1); + return true; + } + + /** Get a random element from the set. */ + public int getRandom() { + int index = random.nextInt(list.size()); + index = (index >= 0 ? index : -index); + return list.get(index); + } +} diff --git a/solution/src/main/java/com/inuker/solution/InsertDeleteGetRandomII.java b/leetcode/solution/src/InsertDeleteGetRandomII.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/InsertDeleteGetRandomII.java rename to leetcode/solution/src/InsertDeleteGetRandomII.java index c3bf840..ec6f23d 100644 --- a/solution/src/main/java/com/inuker/solution/InsertDeleteGetRandomII.java +++ b/leetcode/solution/src/InsertDeleteGetRandomII.java @@ -1,15 +1,4 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Random; -import java.util.Vector; - -/** - * Created by dingjikerbo on 2016/12/17. - */ +import java.util.*; /** * 这题的区别在于允许数字重复,那么保存index需要用set,删除的时候从set中随便删一个就行了 diff --git a/solution/src/main/java/com/inuker/solution/InsertInterval.java b/leetcode/solution/src/InsertInterval.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/InsertInterval.java rename to leetcode/solution/src/InsertInterval.java index 3b46189..5369066 100644 --- a/solution/src/main/java/com/inuker/solution/InsertInterval.java +++ b/leetcode/solution/src/InsertInterval.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.Interval; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/11/22. - */ - public class InsertInterval { public List insert(List intervals, Interval newInterval) { diff --git a/solution/src/main/java/com/inuker/solution/InsertionSortList.java b/leetcode/solution/src/InsertionSortList.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/InsertionSortList.java rename to leetcode/solution/src/InsertionSortList.java index 4aab3b9..4090938 100644 --- a/solution/src/main/java/com/inuker/solution/InsertionSortList.java +++ b/leetcode/solution/src/InsertionSortList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 2017/9/11. - */ - public class InsertionSortList { /** diff --git a/solution/src/main/java/com/inuker/solution/IntegerToEnglishWords.java b/leetcode/solution/src/IntegerToEnglishWords.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/IntegerToEnglishWords.java rename to leetcode/solution/src/IntegerToEnglishWords.java index 9d892b2..74375a4 100644 --- a/solution/src/main/java/com/inuker/solution/IntegerToEnglishWords.java +++ b/leetcode/solution/src/IntegerToEnglishWords.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/19. - */ - /** * TestCase * 0 diff --git a/solution/src/main/java/com/inuker/solution/IntegerToRoman.java b/leetcode/solution/src/IntegerToRoman.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/IntegerToRoman.java rename to leetcode/solution/src/IntegerToRoman.java index 27d661e..3e814cf 100644 --- a/solution/src/main/java/com/inuker/solution/IntegerToRoman.java +++ b/leetcode/solution/src/IntegerToRoman.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class IntegerToRoman { public String intToRoman(int num) { diff --git a/solution/src/main/java/com/inuker/solution/IntersectionOfTwoArrays.java b/leetcode/solution/src/IntersectionOfTwoArrays.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/IntersectionOfTwoArrays.java rename to leetcode/solution/src/IntersectionOfTwoArrays.java index 0721cf4..2a14c72 100644 --- a/solution/src/main/java/com/inuker/solution/IntersectionOfTwoArrays.java +++ b/leetcode/solution/src/IntersectionOfTwoArrays.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.HashSet; import java.util.Set; -/** - * Created by liwentian on 2017/9/22. - */ - public class IntersectionOfTwoArrays { public int[] intersection(int[] nums1, int[] nums2) { diff --git a/solution/src/main/java/com/inuker/solution/IntersectionOfTwoArraysII.java b/leetcode/solution/src/IntersectionOfTwoArraysII.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/IntersectionOfTwoArraysII.java rename to leetcode/solution/src/IntersectionOfTwoArraysII.java index 3dda626..5d812cb 100644 --- a/solution/src/main/java/com/inuker/solution/IntersectionOfTwoArraysII.java +++ b/leetcode/solution/src/IntersectionOfTwoArraysII.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.HashMap; -/** - * Created by liwentian on 2017/9/22. - */ - public class IntersectionOfTwoArraysII { public int[] intersect(int[] nums1, int[] nums2) { diff --git a/solution/src/main/java/com/inuker/solution/IntersectionOfTwoLinkedLists.java b/leetcode/solution/src/IntersectionOfTwoLinkedLists.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/IntersectionOfTwoLinkedLists.java rename to leetcode/solution/src/IntersectionOfTwoLinkedLists.java index 2ad7edb..f1f5661 100644 --- a/solution/src/main/java/com/inuker/solution/IntersectionOfTwoLinkedLists.java +++ b/leetcode/solution/src/IntersectionOfTwoLinkedLists.java @@ -1,7 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - /** * Created by dingjiekrbo on 2016/11/17. * https://leetcode.com/articles/intersection-two-linked-lists/ diff --git a/solution/src/main/java/com/inuker/solution/InvertBinaryTree.java b/leetcode/solution/src/InvertBinaryTree.java similarity index 72% rename from solution/src/main/java/com/inuker/solution/InvertBinaryTree.java rename to leetcode/solution/src/InvertBinaryTree.java index 0e763f1..6efd2c9 100644 --- a/solution/src/main/java/com/inuker/solution/InvertBinaryTree.java +++ b/leetcode/solution/src/InvertBinaryTree.java @@ -1,30 +1,12 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.LinkedList; import java.util.Queue; -/** - * Created by dingjikerbo on 16/11/28. - */ - /** * 给非递归法也要会写 + * 核心思路就是访问所有的节点,将其左右节点交换,可以采用递归,也可以BFS */ public class InvertBinaryTree { - /** 错误的写法,写顺手了 - public TreeNode invertTree(TreeNode root) { - if (root == null) { - return null; - } - - root.right = invertTree(root.left); - root.left = invertTree(root.right); - return root; - }*/ - public TreeNode invertTree(TreeNode root) { if (root == null) { return null; diff --git a/leetcode/solution/src/JewelsAndStones.java b/leetcode/solution/src/JewelsAndStones.java new file mode 100644 index 0000000..75d2068 --- /dev/null +++ b/leetcode/solution/src/JewelsAndStones.java @@ -0,0 +1,16 @@ +public class JewelsAndStones { + + public int numJewelsInStones(String J, String S) { + int character[] = new int[256]; + for (char c : J.toCharArray()) { + character[c]++; + } + int count = 0; + for (char c : S.toCharArray()) { + if (character[c] > 0) { + count++; + } + } + return count; + } +} diff --git a/solution/src/main/java/com/inuker/solution/JumpGame.java b/leetcode/solution/src/JumpGame.java similarity index 76% rename from solution/src/main/java/com/inuker/solution/JumpGame.java rename to leetcode/solution/src/JumpGame.java index a91d60b..beb0863 100644 --- a/solution/src/main/java/com/inuker/solution/JumpGame.java +++ b/leetcode/solution/src/JumpGame.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/5/11. - */ - public class JumpGame { public boolean canJump(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/JumpGameII.java b/leetcode/solution/src/JumpGameII.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/JumpGameII.java rename to leetcode/solution/src/JumpGameII.java index c2213d7..03b00b0 100644 --- a/solution/src/main/java/com/inuker/solution/JumpGameII.java +++ b/leetcode/solution/src/JumpGameII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2017/5/20. - */ - public class JumpGameII { /** diff --git a/leetcode/solution/src/KEmptySlots.java b/leetcode/solution/src/KEmptySlots.java new file mode 100644 index 0000000..e63d7a7 --- /dev/null +++ b/leetcode/solution/src/KEmptySlots.java @@ -0,0 +1,58 @@ +import java.util.TreeSet; + +/** + * 这题意思是第i盆花第flowers[i]天开,问第几天的时候存在这么一种情况:有两盆已经开的花中间恰好隔着k盆没开的花 + */ +public class KEmptySlots { + + public int kEmptySlots(int[] flowers, int k) { + TreeSet map = new TreeSet<>(); + for (int i = 0; i < flowers.length; i++) { + int flower = flowers[i] - 1; + map.add(flower); + + Integer key = map.ceiling(flower + 1); + if (key != null && key - flower == k + 1) { + return i + 1; + } + key = map.floor(flower - 1); + if (key != null && flower - key == k + 1) { + return i + 1; + } + } + + return -1; + } + + /** + * 时间复杂度O(n) + * days表示第i盆花第几天开 + * 天数越大,表示花开的越晚 + * 对于(left, right)这个区间,(这个区间刚好相隔k),如果days值都比left和right大,说明(left,right)区间的花都开的比left和right晚 + * 换言之,在left和right开的时候,中间的花都没开,而left和right刚好相隔k,符合条件。 + * 我们选择left和right之中较大的那个值作为备选结果之一,选取较大是因为表示发生的较晚,刚好触发条件 + * 但是题目要返回最早的那一天,所以我们要继续遍历下去 + * + * 此外还要注意,当发现(left,right)区间存在不符合条件的情况,则sliding window要从i开始,因为如果从(left,i)区间的任何一个数开始,都不会符合条件 + * 另外当找到一组符合条件的情况后,sliding window也要从i开始,也就是从right开始,假如从left+1开始,则当前的right就不符合大于sliding window两端的条件了 + */ + public int kEmptySlots2(int[] flowers, int k) { + int[] days = new int[flowers.length]; + for (int i = 0; i < flowers.length; i++) days[flowers[i] - 1] = i + 1; + int left = 0, right = k + 1, res = Integer.MAX_VALUE; + for (int i = left + 1; i <= right && right < days.length; i++) { + if (i == right) { + res = Math.min(res, Math.max(days[left], days[right])); + left = i; + right = k + 1 + i; + continue; + } + + if (days[i] < days[left] || days[i] < days[right]) { + left = i; + right = k + 1 + i; + } + } + return (res == Integer.MAX_VALUE) ? -1 : res; + } +} diff --git a/leetcode/solution/src/KthLargestElementInAStream.java b/leetcode/solution/src/KthLargestElementInAStream.java new file mode 100644 index 0000000..27cff7b --- /dev/null +++ b/leetcode/solution/src/KthLargestElementInAStream.java @@ -0,0 +1,26 @@ +import java.util.PriorityQueue; +import java.util.Queue; + +public class KthLargestElementInAStream { + + class KthLargest { + + Queue queue = new PriorityQueue<>(); + int capacity; + + public KthLargest(int k, int[] nums) { + capacity = k; + for (int n : nums) { + queue.offer(n); + } + } + + public int add(int val) { + queue.offer(val); + while (queue.size() > capacity) { + queue.poll(); + } + return queue.peek(); + } + } +} diff --git a/solution/src/main/java/com/inuker/solution/KthLargestElementInArray.java b/leetcode/solution/src/KthLargestElementInArray.java similarity index 78% rename from solution/src/main/java/com/inuker/solution/KthLargestElementInArray.java rename to leetcode/solution/src/KthLargestElementInArray.java index 288d2dc..6a55336 100644 --- a/solution/src/main/java/com/inuker/solution/KthLargestElementInArray.java +++ b/leetcode/solution/src/KthLargestElementInArray.java @@ -1,13 +1,10 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.PriorityQueue; -import java.util.Queue; +import java.util.Random; /** - * Created by dingjikerbo on 2016/11/17. + * 注意本题不是返回第k大的distinct number */ - public class KthLargestElementInArray { // 耗时15ms,时间复杂度O(nlgk),空间复杂度O(k) @@ -33,11 +30,23 @@ public int findKthLargest3(int[] nums, int k) { // T(n) = T(n / 2) + n = O(2n) // 对比快速排序T(n) = 2T(n / 2) + n = O(nlgn) // 区别在于这个被pivot分隔后,只用处理其中的一半,而快排两边都要处理 - // 耗时18ms + + /** + * shuffle非常有必要,性能提升很大 + */ public int findKthLargest(int[] nums, int k) { + shuffle(nums); return findKthLargest(nums, 0, nums.length - 1, k); } + private void shuffle(int[] nums) { + Random rnd = new Random(System.currentTimeMillis()); + for (int i = nums.length - 1; i > 1; i--) { + int index = rnd.nextInt(i + 1); + swap(nums, index, i); + } + } + public int findKthLargest(int[] nums, int start, int end, int k) { int pivot = partition(nums, start, end); @@ -52,6 +61,10 @@ public int findKthLargest(int[] nums, int start, int end, int k) { } } + /** + * 这里两端都是闭区间 + * 这里将数组分为两部分,左边小于pivot,右边大于pivot,中间可能等于pivot + */ public int partition(int[] nums, int start, int end) { int pivot = nums[end], left = start, right = end - 1; diff --git a/solution/src/main/java/com/inuker/solution/KthSmallestElementInASortedMatrix.java b/leetcode/solution/src/KthSmallestElementInASortedMatrix.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/KthSmallestElementInASortedMatrix.java rename to leetcode/solution/src/KthSmallestElementInASortedMatrix.java index e176d07..5d7e85b 100644 --- a/solution/src/main/java/com/inuker/solution/KthSmallestElementInASortedMatrix.java +++ b/leetcode/solution/src/KthSmallestElementInASortedMatrix.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.PriorityQueue; -/** - * Created by liwentian on 2017/9/12. - */ - public class KthSmallestElementInASortedMatrix { public int kthSmallest(int[][] matrix, int k) { diff --git a/leetcode/solution/src/KthSmallestElementInBST.java b/leetcode/solution/src/KthSmallestElementInBST.java new file mode 100644 index 0000000..461a001 --- /dev/null +++ b/leetcode/solution/src/KthSmallestElementInBST.java @@ -0,0 +1,89 @@ +import java.util.Stack; + +/** + * 这题关键是follow up + * 如果更新频繁,则通常的做法每次都是O(n),更优的做法是O(lgn) + * 即给node中记录左子树的节点个数,这样在找kth smallest时流程如下: + * 假设root的左子树节点有N个,则 + * 1, 当K=N+1时,kth就是root + * 2, 当KN+1时,就到右子树中找第K-N-1个 + * 所以当给定一棵树时,我们要先重建一下这棵树,统计一下各节点的左子树节点数,虽然首次是O(n) + * 但是之后就是O(h)了。 + */ +public class KthSmallestElementInBST { + + public int kthSmallest(TreeNode root, int k) { + Stack stack = new Stack<>(); + while (root != null || !stack.isEmpty()) { + if (root != null) { + stack.push(root); + root = root.left; + } else { + root = stack.pop(); + + if (--k == 0) { + return root.val; + } + + root = root.right; + } + } + throw new IllegalStateException(); + } + + public int kthSmallest2(TreeNode root, int k) { + TreeNodeWithCount rootWithCount = buildTreeWithCount(root); + return kthSmallest(rootWithCount, k); + } + + public int kthSmallest(TreeNodeWithCount root, int k) { + if (root == null) { + return -1; + } + + if (root.left != null) { + if (k <= root.left.count) { + return kthSmallest(root.left, k); + } else if (k == root.left.count + 1) { + return root.val; + } else { + return kthSmallest(root.right, k - root.left.count - 1); + } + } + + if (k == 1) { + return root.val; + } else { + return kthSmallest(root.right, k - 1); + } + } + + private TreeNodeWithCount buildTreeWithCount(TreeNode root) { + if (root == null) { + return null; + } + TreeNodeWithCount nroot = new TreeNodeWithCount(root.val); + nroot.left = buildTreeWithCount(root.left); + nroot.right = buildTreeWithCount(root.right); + + if (nroot.left != null) { + nroot.count += nroot.left.count; + } + + if (nroot.right != null) { + nroot.count += nroot.right.count; + } + return nroot; + } + + class TreeNodeWithCount { + TreeNodeWithCount left, right; + int count, val; + + TreeNodeWithCount(int val) { + this.val = val; + this.count = 1; + } + } +} diff --git a/solution/src/main/java/com/inuker/solution/LFUCache.java b/leetcode/solution/src/LFUCache.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/LFUCache.java rename to leetcode/solution/src/LFUCache.java index 797cff6..0878c1a 100644 --- a/solution/src/main/java/com/inuker/solution/LFUCache.java +++ b/leetcode/solution/src/LFUCache.java @@ -1,11 +1,6 @@ -package com.inuker.solution; - import java.util.HashMap; import java.util.LinkedHashSet; -/** - * Created by dingjikerbo on 17/1/2. - */ /** * 和LRU的区别是 * LRU,即便历史频率再高,如果最近用的少了一样踢掉 diff --git a/leetcode/solution/src/LRUCache.java b/leetcode/solution/src/LRUCache.java new file mode 100644 index 0000000..69b9695 --- /dev/null +++ b/leetcode/solution/src/LRUCache.java @@ -0,0 +1,64 @@ +import java.util.HashMap; + +public class LRUCache { + + private Node mHead; + private HashMap mMap; + private int mCapacity; + + public LRUCache(int capacity) { + mMap = new HashMap<>(); + mCapacity = capacity; + mHead = new Node(0, 0); + } + + public int get(int key) { + if (!mMap.containsKey(key)) { + return -1; + } + Node node = mMap.get(key); + node.remove(); + node.add(mHead); + return node.val; + } + + public void put(int key, int value) { + Node node = mMap.get(key); + if (node == null) { + node = new Node(key, value); + mMap.put(key, node); + } else { + node.val = value; + node.remove(); + } + node.add(mHead); + if (mMap.size() > mCapacity) { + Node prev = mHead.prev; + prev.remove(); + mMap.remove(prev.key); + } + } + + class Node { + Node prev, next; + int key, val; + + Node(int key, int val) { + this.key = key; + this.val = val; + prev = next = this; + } + + void remove() { + prev.next = next; + next.prev = prev; + } + + void add(Node head) { + next = head.next; + head.next.prev = this; + prev = head; + head.next = this; + } + } +} diff --git a/solution/src/main/java/com/inuker/solution/LargestBSTSubtree.java b/leetcode/solution/src/LargestBSTSubtree.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/LargestBSTSubtree.java rename to leetcode/solution/src/LargestBSTSubtree.java index 3df7a17..d7b906a 100644 --- a/solution/src/main/java/com/inuker/solution/LargestBSTSubtree.java +++ b/leetcode/solution/src/LargestBSTSubtree.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/12/3. - */ - public class LargestBSTSubtree { class Result { diff --git a/solution/src/main/java/com/inuker/solution/LargestNumber.java b/leetcode/solution/src/LargestNumber.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/LargestNumber.java rename to leetcode/solution/src/LargestNumber.java index 1e0f9f6..cce7008 100644 --- a/solution/src/main/java/com/inuker/solution/LargestNumber.java +++ b/leetcode/solution/src/LargestNumber.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.Comparator; -/** - * Created by dingjikerbo on 16/12/8. - */ - public class LargestNumber { public String largestNumber(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/LargestRectangleInHistogram.java b/leetcode/solution/src/LargestRectangleInHistogram.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/LargestRectangleInHistogram.java rename to leetcode/solution/src/LargestRectangleInHistogram.java index 47f3d94..bedb6aa 100644 --- a/solution/src/main/java/com/inuker/solution/LargestRectangleInHistogram.java +++ b/leetcode/solution/src/LargestRectangleInHistogram.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - import java.util.Stack; /** @@ -29,7 +23,12 @@ public int largestRectangleArea(int[] heights) { return max; } - /** 注意栈中的是index,不是高度 + /** + * 核心思路是用栈保存一个高度递增的index,当出现一个局部最高点时,计算以该最高点为高度的最大面积 + * 该局部最高点的形成可能是新加的柱子较矮,也可能是随着旧的高点不断出栈导致的 + * 该局部高点的特点是"相邻的柱子都比他高",这里相邻的意思是左边延伸到下一个出栈的index,右边延伸到新加的柱子 + * + * 注意栈中的是index,不是高度 * 栈保持递增,当出现小于栈顶的元素时,意味着可以计算栈顶可以延伸的矩形面积了 * 其左边界是次栈顶,右边界是当前元素 */ diff --git a/leetcode/solution/src/LeafSimilarTrees.java b/leetcode/solution/src/LeafSimilarTrees.java new file mode 100644 index 0000000..ca54857 --- /dev/null +++ b/leetcode/solution/src/LeafSimilarTrees.java @@ -0,0 +1,53 @@ +import java.util.Stack; + +public class LeafSimilarTrees { + + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + TreeIterator iterator1 = new TreeIterator(root1); + TreeIterator iterator2 = new TreeIterator(root2); + + while (true) { + TreeNode node1 = iterator1.nextLeaf(); + TreeNode node2 = iterator2.nextLeaf(); + + if (node1 == null && node2 == null) { + return true; + } + if (node1 == null || node2 == null) { + return false; + } + if (node1.val != node2.val) { + return false; + } + } + } + + public class TreeIterator { + Stack stack; + TreeNode root; + + TreeIterator(TreeNode root) { + this.root = root; + stack = new Stack<>(); + } + + TreeNode nextLeaf() { + TreeNode ret; + while (!stack.isEmpty() || root != null) { + if (root != null) { + stack.push(root); + ret = root; + root = root.left; + + if (ret.left == null && ret.right == null) { + return ret; + } + + } else { + root = stack.pop().right; + } + } + return null; + } + } +} diff --git a/leetcode/solution/src/LetterCombinationOfPhoneNumber.java b/leetcode/solution/src/LetterCombinationOfPhoneNumber.java new file mode 100644 index 0000000..853afbc --- /dev/null +++ b/leetcode/solution/src/LetterCombinationOfPhoneNumber.java @@ -0,0 +1,39 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class LetterCombinationOfPhoneNumber { + + /** + * leetcode的测试用例中不包括包含"0"或"1"的情况 + */ + + private static final String[] ARR = { + "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" + }; + + // 耗时2ms + public List letterCombinations(String digits) { + List res = new ArrayList<>(); + if (digits.length() == 0) { + return res; + } + dfs(digits, new StringBuilder(), res, 0); + return res; + } + + private void dfs(String digits, StringBuilder sb, List res, int start) { + if (start >= digits.length()) { + res.add(sb.toString()); + return; + } + + int n = digits.charAt(start) - '0'; + for (char c : ARR[n].toCharArray()) { + sb.append(c); + dfs(digits, sb, res, start + 1); + sb.setLength(sb.length() - 1); + } + } +} diff --git a/solution/src/main/java/com/inuker/solution/LicenseKeyFormatting.java b/leetcode/solution/src/LicenseKeyFormatting.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/LicenseKeyFormatting.java rename to leetcode/solution/src/LicenseKeyFormatting.java index 6b721b8..bbe9cc8 100644 --- a/solution/src/main/java/com/inuker/solution/LicenseKeyFormatting.java +++ b/leetcode/solution/src/LicenseKeyFormatting.java @@ -1,18 +1,10 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 17/8/26. - */ - /** * 将字符串s按长度k为一组,从右往左重排,组之间用"-"分隔,还要转成大写 * 注意别在最前面多加一个"-",即下面判断i != 0 */ - - public class LicenseKeyFormatting { - // 耗时22ms + // 耗时13ms public String licenseKeyFormatting(String S, int K) { StringBuilder sb = new StringBuilder(); @@ -20,7 +12,6 @@ public String licenseKeyFormatting(String S, int K) { if (S.charAt(i) != '-') { if (j % K == 0 && sb.length() > 0) { sb.append("-"); - j = 0; } sb.append(Character.toUpperCase(S.charAt(i))); diff --git a/solution/src/main/java/com/inuker/solution/LinkedListCycle.java b/leetcode/solution/src/LinkedListCycle.java similarity index 66% rename from solution/src/main/java/com/inuker/solution/LinkedListCycle.java rename to leetcode/solution/src/LinkedListCycle.java index e1cee81..2b6d823 100644 --- a/solution/src/main/java/com/inuker/solution/LinkedListCycle.java +++ b/leetcode/solution/src/LinkedListCycle.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 2016/11/17. - * https://leetcode.com/articles/linked-list-cycle/ - */ - public class LinkedListCycle { + // 注意判空 public boolean hasCycle(ListNode head) { for (ListNode fast = head, slow = head; fast != null && fast.next != null; ) { slow = slow.next; diff --git a/solution/src/main/java/com/inuker/solution/LinkedListCycleII.java b/leetcode/solution/src/LinkedListCycleII.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/LinkedListCycleII.java rename to leetcode/solution/src/LinkedListCycleII.java index 8fe19d7..5c16094 100644 --- a/solution/src/main/java/com/inuker/solution/LinkedListCycleII.java +++ b/leetcode/solution/src/LinkedListCycleII.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 2017/9/11. - */ - public class LinkedListCycleII { /** * 这里有个问题,如果链表是a,b,然后又回到a diff --git a/solution/src/main/java/com/inuker/solution/LinkedListRandomNode.java b/leetcode/solution/src/LinkedListRandomNode.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/LinkedListRandomNode.java rename to leetcode/solution/src/LinkedListRandomNode.java index 02d1fcb..3b7573b 100644 --- a/solution/src/main/java/com/inuker/solution/LinkedListRandomNode.java +++ b/leetcode/solution/src/LinkedListRandomNode.java @@ -1,13 +1,5 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - import java.util.Random; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class LinkedListRandomNode { private Random mRandom; diff --git a/solution/src/main/java/com/inuker/solution/LoggerRateLimiter.java b/leetcode/solution/src/LoggerRateLimiter.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/LoggerRateLimiter.java rename to leetcode/solution/src/LoggerRateLimiter.java index 8aab161..db6a6e5 100644 --- a/solution/src/main/java/com/inuker/solution/LoggerRateLimiter.java +++ b/leetcode/solution/src/LoggerRateLimiter.java @@ -1,14 +1,8 @@ -package com.inuker.solution; - import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Queue; -/** - * Created by liwentian on 2017/8/31. - */ - /** * 如果要考虑到空间消耗,则要另外定义一个List,每次新来一条日志,都要遍历 * list中10s外的poll了,同时从map中remove diff --git a/solution/src/main/java/com/inuker/solution/LongestAbsoluteFilePath.java b/leetcode/solution/src/LongestAbsoluteFilePath.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/LongestAbsoluteFilePath.java rename to leetcode/solution/src/LongestAbsoluteFilePath.java index 6aa74fe..2116455 100644 --- a/solution/src/main/java/com/inuker/solution/LongestAbsoluteFilePath.java +++ b/leetcode/solution/src/LongestAbsoluteFilePath.java @@ -1,13 +1,5 @@ -package com.inuker.solution; - -import java.util.ArrayDeque; -import java.util.Deque; import java.util.Stack; -/** - * Created by dingjikerbo on 16/11/26. - */ - public class LongestAbsoluteFilePath { // 耗时4ms diff --git a/solution/src/main/java/com/inuker/solution/LongestCommonPrefix.java b/leetcode/solution/src/LongestCommonPrefix.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/LongestCommonPrefix.java rename to leetcode/solution/src/LongestCommonPrefix.java index 4996559..1246091 100644 --- a/solution/src/main/java/com/inuker/solution/LongestCommonPrefix.java +++ b/leetcode/solution/src/LongestCommonPrefix.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/5/2. - */ - /** * 注意只有一个字符串的情况 * 还要注意字符串越界问题 diff --git a/solution/src/main/java/com/inuker/solution/LongestConsecutiveSequence.java b/leetcode/solution/src/LongestConsecutiveSequence.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/LongestConsecutiveSequence.java rename to leetcode/solution/src/LongestConsecutiveSequence.java index 7ea27cb..cf90150 100644 --- a/solution/src/main/java/com/inuker/solution/LongestConsecutiveSequence.java +++ b/leetcode/solution/src/LongestConsecutiveSequence.java @@ -1,9 +1,6 @@ -package com.inuker.solution; - import java.util.HashMap; /** - * Created by dingjikerbo on 16/11/22. * https://leetcode.com/articles/longest-consecutive-sequence/ */ public class LongestConsecutiveSequence { diff --git a/solution/src/main/java/com/inuker/solution/LongestIncreasingPathInAMatrix.java b/leetcode/solution/src/LongestIncreasingPathInAMatrix.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/LongestIncreasingPathInAMatrix.java rename to leetcode/solution/src/LongestIncreasingPathInAMatrix.java index 4af1f18..e4eb4ff 100644 --- a/solution/src/main/java/com/inuker/solution/LongestIncreasingPathInAMatrix.java +++ b/leetcode/solution/src/LongestIncreasingPathInAMatrix.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/1. - */ - /** * https://leetcode.com/articles/longest-increasing-path-matrix/ */ diff --git a/solution/src/main/java/com/inuker/solution/LongestIncreasingSubsequence.java b/leetcode/solution/src/LongestIncreasingSubsequence.java similarity index 53% rename from solution/src/main/java/com/inuker/solution/LongestIncreasingSubsequence.java rename to leetcode/solution/src/LongestIncreasingSubsequence.java index 34a886e..92e76f3 100644 --- a/solution/src/main/java/com/inuker/solution/LongestIncreasingSubsequence.java +++ b/leetcode/solution/src/LongestIncreasingSubsequence.java @@ -1,15 +1,9 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 17/1/5. - */ - public class LongestIncreasingSubsequence { /** - * 这题是典型的DP,f[i]包含i的最长子序列长度 + * 这题是典型的DP,f[i]包含i的最长递增子序列长度 */ public int lengthOfLIS(int[] nums) { int n = nums.length; @@ -33,24 +27,22 @@ public int lengthOfLIS(int[] nums) { return max; } + /** + * 核心思路是dp维护了一个递增的序列,dp[i]表示nums中长度为i+1的递增子序列中tail最小的值 + * tail越小意味着之后延长这个序列更容易 + * 为了保证dp[i]是tail最小的,我们遍历nums时,当发现有更小的值时,会替换dp[i] + */ public int lengthOfLIS2(int[] nums) { - int len = 1; - for (int i = 0; i < nums.length; i++) { - /** - * 注意这里要指定区间,且end是开区间 - */ - int k = Arrays.binarySearch(nums, 0, len, nums[i]); - /** - * 只处理k<0的情况 - */ - if (k < 0) { - k = -(k + 1); - if (k == len) { - len++; - } - nums[k] = nums[i]; - } + int[] dp = new int[nums.length]; + int len = 0; + + for(int x : nums) { + int i = Arrays.binarySearch(dp, 0, len, x); + if(i < 0) i = -(i + 1); + dp[i] = x; + if(i == len) len++; } + return len; } } diff --git a/solution/src/main/java/com/inuker/solution/LongestPalindrome.java b/leetcode/solution/src/LongestPalindrome.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/LongestPalindrome.java rename to leetcode/solution/src/LongestPalindrome.java index 7e2224c..4326fbe 100644 --- a/solution/src/main/java/com/inuker/solution/LongestPalindrome.java +++ b/leetcode/solution/src/LongestPalindrome.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/19. - */ - public class LongestPalindrome { public int longestPalindrome(String s) { diff --git a/solution/src/main/java/com/inuker/solution/LongestPalindromicSubstring.java b/leetcode/solution/src/LongestPalindromicSubstring.java similarity index 61% rename from solution/src/main/java/com/inuker/solution/LongestPalindromicSubstring.java rename to leetcode/solution/src/LongestPalindromicSubstring.java index 1217e54..9c2d555 100644 --- a/solution/src/main/java/com/inuker/solution/LongestPalindromicSubstring.java +++ b/leetcode/solution/src/LongestPalindromicSubstring.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - /** * 这题采用动态规划也可,但是不论时间还是空间性能都不好 */ @@ -11,21 +5,26 @@ public class LongestPalindromicSubstring { private int begin, maxLen; - // 耗时14ms,平均复杂度O(n) - public String longestPalindrome(String s) { + // 耗时11ms,平均复杂度O(n) + public String longestPalindrome(String s) { + int[] res = new int[2]; for (int i = 0; i < s.length(); i++) { - helper(s, i, i); - helper(s, i, i + 1); + helper(s, i - 1, i + 1, res); + helper(s, i, i + 1, res); } - return s.substring(begin, begin + maxLen); + return s.substring(res[1], res[1] + res[0]); } - private void helper(String s, int i, int j) { - for (; i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j); i--, j++) ; - int len = j - i - 1; - if (len > maxLen) { - maxLen = len; - begin = i + 1; + private void helper(String s, int left, int right, int[] res) { + for ( ; left >= 0 && right < s.length(); left--, right++) { + if (s.charAt(left) != s.charAt(right)) { + break; + } + } + int len = --right - ++left + 1; + if (len > res[0]) { + res[0] = len; + res[1] = left; } } diff --git a/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtLeastKRepeatingCharacters.java b/leetcode/solution/src/LongestSubstringWithAtLeastKRepeatingCharacters.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/LongestSubstringWithAtLeastKRepeatingCharacters.java rename to leetcode/solution/src/LongestSubstringWithAtLeastKRepeatingCharacters.java index 3da934b..0abd7e2 100644 --- a/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtLeastKRepeatingCharacters.java +++ b/leetcode/solution/src/LongestSubstringWithAtLeastKRepeatingCharacters.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/27. - */ - /** * 要注意,这道题不能用window法来做,window法是先尽可能扩张window到不符合条件,然后 * 缩小window直到将不符合因素排除,所以通常适用于AtMost类型的问题,因为首先要超出most, diff --git a/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostKDistinctCharacters.java b/leetcode/solution/src/LongestSubstringWithAtMostKDistinctCharacters.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostKDistinctCharacters.java rename to leetcode/solution/src/LongestSubstringWithAtMostKDistinctCharacters.java index f8d46e3..46cdd41 100644 --- a/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostKDistinctCharacters.java +++ b/leetcode/solution/src/LongestSubstringWithAtMostKDistinctCharacters.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import java.util.HashMap; - -/** - * Created by dingjikerbo on 16/11/27. - */ - public class LongestSubstringWithAtMostKDistinctCharacters { /** diff --git a/leetcode/solution/src/LongestSubstringWithAtMostTwoDistinctCharacters.java b/leetcode/solution/src/LongestSubstringWithAtMostTwoDistinctCharacters.java new file mode 100644 index 0000000..dc1675b --- /dev/null +++ b/leetcode/solution/src/LongestSubstringWithAtMostTwoDistinctCharacters.java @@ -0,0 +1,22 @@ +public class LongestSubstringWithAtMostTwoDistinctCharacters { + + // 1ms + public int lengthOfLongestSubstringTwoDistinct2(String s) { + if (s.length() == 0) { + return 0; + } + int[] dp = new int[256]; + int count = 0, longest = 0; + for (int i = 0, j = 0; j < s.length(); j++) { + if (dp[s.charAt(j)]++ == 0) { + for (++count; i <= j && count > 2; ) { + if (--dp[s.charAt(i++)] == 0) { + --count; + } + } + } + longest = Math.max(longest, j - i + 1); + } + return longest; + } +} diff --git a/leetcode/solution/src/LongestSubstringWithoutRepeatingCharacters.java b/leetcode/solution/src/LongestSubstringWithoutRepeatingCharacters.java new file mode 100644 index 0000000..ad292b7 --- /dev/null +++ b/leetcode/solution/src/LongestSubstringWithoutRepeatingCharacters.java @@ -0,0 +1,19 @@ +/** + * https://leetcode.com/articles/longest-substring-without-repeating-characters/ + */ +public class LongestSubstringWithoutRepeatingCharacters { + + public int lengthOfLongestSubstring(String s) { + int[] count = new int[256]; + int max = 0; + for (int i = 0, j = 0; i < s.length(); i++) { + char c = s.charAt(i); + count[c]++; + for ( ; j < i && count[c] > 1; j++) { + count[s.charAt(j)]--; + } + max = Math.max(max, i - j + 1); + } + return max; + } +} diff --git a/leetcode/solution/src/LongestUnivaluePath.java b/leetcode/solution/src/LongestUnivaluePath.java new file mode 100644 index 0000000..8d950c1 --- /dev/null +++ b/leetcode/solution/src/LongestUnivaluePath.java @@ -0,0 +1,27 @@ +public class LongestUnivaluePath { + + public int longestUnivaluePath(TreeNode root) { + int[] res = new int[1]; + dfs(root, res); + return res[0]; + } + + private int dfs(TreeNode node, int[] res) { + if (node == null) { + return 0; + } + int left = dfs(node.left, res); + int right = dfs(node.right, res); + + int lval = 0, rval = 0; + + if (node.left != null && node.left.val == node.val) { + lval = left + 1; + } + if (node.right != null && node.right.val == node.val) { + rval = right + 1; + } + res[0] = Math.max(res[0], lval + rval); + return Math.max(lval, rval); + } +} diff --git a/solution/src/main/java/com/inuker/solution/LongestValidParentheses.java b/leetcode/solution/src/LongestValidParentheses.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/LongestValidParentheses.java rename to leetcode/solution/src/LongestValidParentheses.java index e6789ca..b1ee7b9 100644 --- a/solution/src/main/java/com/inuker/solution/LongestValidParentheses.java +++ b/leetcode/solution/src/LongestValidParentheses.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - import java.util.Stack; /** diff --git a/solution/src/main/java/com/inuker/solution/LongestWordInDictionaryThroughDeleting.java b/leetcode/solution/src/LongestWordInDictionaryThroughDeleting.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/LongestWordInDictionaryThroughDeleting.java rename to leetcode/solution/src/LongestWordInDictionaryThroughDeleting.java index 1a492c8..98a9890 100644 --- a/solution/src/main/java/com/inuker/solution/LongestWordInDictionaryThroughDeleting.java +++ b/leetcode/solution/src/LongestWordInDictionaryThroughDeleting.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.List; -/** - * Created by liwentian on 2017/12/10. - */ - public class LongestWordInDictionaryThroughDeleting { public String findLongestWord(String s, List d) { diff --git a/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinarySearchTree.java b/leetcode/solution/src/LowestCommonAncestorOfBinarySearchTree.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinarySearchTree.java rename to leetcode/solution/src/LowestCommonAncestorOfBinarySearchTree.java index 8b58c0d..b895c46 100644 --- a/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinarySearchTree.java +++ b/leetcode/solution/src/LowestCommonAncestorOfBinarySearchTree.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - public class LowestCommonAncestorOfBinarySearchTree { /** diff --git a/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinaryTree.java b/leetcode/solution/src/LowestCommonAncestorOfBinaryTree.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinaryTree.java rename to leetcode/solution/src/LowestCommonAncestorOfBinaryTree.java index 13ca994..4c5689f 100644 --- a/solution/src/main/java/com/inuker/solution/LowestCommonAncestorOfBinaryTree.java +++ b/leetcode/solution/src/LowestCommonAncestorOfBinaryTree.java @@ -1,16 +1,5 @@ -package com.inuker.solution; +import java.util.*; -import com.leetcode.library.TreeNode; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Set; - -/** - * Created by dingjikerbo on 2016/11/16. - */ public class LowestCommonAncestorOfBinaryTree { /** diff --git a/solution/src/main/java/com/inuker/solution/MajorityElement.java b/leetcode/solution/src/MajorityElement.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/MajorityElement.java rename to leetcode/solution/src/MajorityElement.java index f9c00cb..bdedd39 100644 --- a/solution/src/main/java/com/inuker/solution/MajorityElement.java +++ b/leetcode/solution/src/MajorityElement.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class MajorityElement { public int majorityElement(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/MajorityElementII.java b/leetcode/solution/src/MajorityElementII.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/MajorityElementII.java rename to leetcode/solution/src/MajorityElementII.java index a7496b8..83a9cce 100644 --- a/solution/src/main/java/com/inuker/solution/MajorityElementII.java +++ b/leetcode/solution/src/MajorityElementII.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by liwentian on 2017/9/10. - */ - public class MajorityElementII { public List majorityElement(int[] nums) { diff --git a/leetcode/solution/src/MaxAreaOfIsland.java b/leetcode/solution/src/MaxAreaOfIsland.java new file mode 100644 index 0000000..9f01d6b --- /dev/null +++ b/leetcode/solution/src/MaxAreaOfIsland.java @@ -0,0 +1,28 @@ +public class MaxAreaOfIsland { + + public int maxAreaOfIsland(int[][] grid) { + int[] area = new int[1]; + int max = 0; + + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + area[0] = 0; + dfs(grid, i, j, area); + max = Math.max(max, area[0]); + } + } + return max; + } + + private void dfs(int[][] grid, int i, int j, int[] count) { + if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != 1) { + return; + } + grid[i][j] = 0; + count[0]++; + dfs(grid, i + 1, j, count); + dfs(grid, i - 1, j, count); + dfs(grid, i, j + 1, count); + dfs(grid, i, j - 1, count); + } +} diff --git a/solution/src/main/java/com/inuker/solution/MaxConsecutiveOnes.java b/leetcode/solution/src/MaxConsecutiveOnes.java similarity index 76% rename from solution/src/main/java/com/inuker/solution/MaxConsecutiveOnes.java rename to leetcode/solution/src/MaxConsecutiveOnes.java index d9215dd..f51f473 100644 --- a/solution/src/main/java/com/inuker/solution/MaxConsecutiveOnes.java +++ b/leetcode/solution/src/MaxConsecutiveOnes.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class MaxConsecutiveOnes { public int findMaxConsecutiveOnes(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/MaxConsecutiveOnesII.java b/leetcode/solution/src/MaxConsecutiveOnesII.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/MaxConsecutiveOnesII.java rename to leetcode/solution/src/MaxConsecutiveOnesII.java index a3b7867..b98a62a 100644 --- a/solution/src/main/java/com/inuker/solution/MaxConsecutiveOnesII.java +++ b/leetcode/solution/src/MaxConsecutiveOnesII.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.Queue; -/** - * Created by liwentian on 2017/9/10. - */ - public class MaxConsecutiveOnesII { /** diff --git a/solution/src/main/java/com/inuker/solution/MaxPointsOnALine.java b/leetcode/solution/src/MaxPointsOnALine.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/MaxPointsOnALine.java rename to leetcode/solution/src/MaxPointsOnALine.java index c2b6ac4..f77bcfd 100644 --- a/solution/src/main/java/com/inuker/solution/MaxPointsOnALine.java +++ b/leetcode/solution/src/MaxPointsOnALine.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.awt.Point; import java.util.HashMap; -/** - * Created by dingjikerbo on 16/12/7. - */ - /** * TestCase * 边界条件很多,比如有重复的点,有斜率无穷大的线 diff --git a/solution/src/main/java/com/inuker/solution/MaximalRectangle.java b/leetcode/solution/src/MaximalRectangle.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/MaximalRectangle.java rename to leetcode/solution/src/MaximalRectangle.java index 053904d..ddc77be 100644 --- a/solution/src/main/java/com/inuker/solution/MaximalRectangle.java +++ b/leetcode/solution/src/MaximalRectangle.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public abstract class MaximalRectangle { // 耗时10ms,时间复杂度是O(mn),空间复杂度O(n) diff --git a/solution/src/main/java/com/inuker/solution/MaximalSquare.java b/leetcode/solution/src/MaximalSquare.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/MaximalSquare.java rename to leetcode/solution/src/MaximalSquare.java index 7558aee..2000238 100644 --- a/solution/src/main/java/com/inuker/solution/MaximalSquare.java +++ b/leetcode/solution/src/MaximalSquare.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/23. - */ - /** * https://leetcode.com/articles/maximal-square/ */ diff --git a/leetcode/solution/src/MaximizeDistanceToClosestPerson.java b/leetcode/solution/src/MaximizeDistanceToClosestPerson.java new file mode 100644 index 0000000..f69e27a --- /dev/null +++ b/leetcode/solution/src/MaximizeDistanceToClosestPerson.java @@ -0,0 +1,46 @@ +import java.util.Arrays; + +public class MaximizeDistanceToClosestPerson { + + /** + * 这题要注意两个边界的情况,因为如果是非边界的情况,要坐在中间的 + */ + public int maxDistToClosest(int[] seats) { + int max = 0; + + int[] zone = new int[2]; + for (int index = 0; index < seats.length; ) { + Arrays.fill(zone, -1); + index = nextFree(seats, index, zone); + if (zone[0] == 0 || zone[1] == seats.length - 1) { + max = Math.max(max, zone[1] - zone[0] + 1); + } else { + max = Math.max(max, (zone[1] - zone[0] + 2) / 2); + } + } + + return max; + } + + /** + * 返回从start开始的连续的0区间 + */ + private int nextFree(int[] seats, int start, int[] zone) { + boolean enter = false; + for (int i = start, j = 0; i <= seats.length; i++) { + if (i < seats.length && seats[i] == 0) { + if (!enter) { + enter = true; + j = i; + } + } else { + if (enter) { + zone[0] = j; + zone[1] = i - 1; + return i + 1; + } + } + } + return seats.length; + } +} diff --git a/leetcode/solution/src/MaximumBinaryTree.java b/leetcode/solution/src/MaximumBinaryTree.java new file mode 100644 index 0000000..767ca33 --- /dev/null +++ b/leetcode/solution/src/MaximumBinaryTree.java @@ -0,0 +1,25 @@ +public class MaximumBinaryTree { + + /** + * 复杂度平均O(nlgn),最差O(n^2) + */ + public TreeNode constructMaximumBinaryTree(int[] nums, int start, int end) { + if (start > end) { + return null; + } + int max = start; + for (int i = start + 1; i <= end; i++) { + if (nums[i] > nums[max]) { + max = i; + } + } + TreeNode root = new TreeNode(nums[max]); + root.left = constructMaximumBinaryTree(nums, start, max - 1); + root.right = constructMaximumBinaryTree(nums, max + 1, end); + return root; + } + + public TreeNode constructMaximumBinaryTree(int[] nums) { + return constructMaximumBinaryTree(nums, 0, nums.length - 1); + } +} diff --git a/solution/src/main/java/com/inuker/solution/MaximumDepthOfBinaryTree.java b/leetcode/solution/src/MaximumDepthOfBinaryTree.java similarity index 53% rename from solution/src/main/java/com/inuker/solution/MaximumDepthOfBinaryTree.java rename to leetcode/solution/src/MaximumDepthOfBinaryTree.java index 2e1f7c0..73fe2f7 100644 --- a/solution/src/main/java/com/inuker/solution/MaximumDepthOfBinaryTree.java +++ b/leetcode/solution/src/MaximumDepthOfBinaryTree.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/11/28. - */ - public class MaximumDepthOfBinaryTree { - private int maxDepth(TreeNode node) { + public int maxDepth(TreeNode node) { if (node == null) { return 0; } diff --git a/solution/src/main/java/com/inuker/solution/MaximumGap.java b/leetcode/solution/src/MaximumGap.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/MaximumGap.java rename to leetcode/solution/src/MaximumGap.java index e91a3ef..2ee41a0 100644 --- a/solution/src/main/java/com/inuker/solution/MaximumGap.java +++ b/leetcode/solution/src/MaximumGap.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 16/12/8. - */ - public class MaximumGap { /** @@ -59,6 +53,7 @@ public int maximumGap(int[] nums) { maxGap = Math.max(maxGap, mins[i] - last); last = maxs[i]; } + // 最后的max别忘了 maxGap = Math.max(maxGap, max - last); return maxGap; } diff --git a/solution/src/main/java/com/inuker/solution/MaximumProductSubarray.java b/leetcode/solution/src/MaximumProductSubarray.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/MaximumProductSubarray.java rename to leetcode/solution/src/MaximumProductSubarray.java index 8839090..6c4d5a9 100644 --- a/solution/src/main/java/com/inuker/solution/MaximumProductSubarray.java +++ b/leetcode/solution/src/MaximumProductSubarray.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/1/5. - */ - public class MaximumProductSubarray { /** diff --git a/solution/src/main/java/com/inuker/solution/MaximumSizeSubarraySumEqualsK.java b/leetcode/solution/src/MaximumSizeSubarraySumEqualsK.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/MaximumSizeSubarraySumEqualsK.java rename to leetcode/solution/src/MaximumSizeSubarraySumEqualsK.java index f7663da..022112d 100644 --- a/solution/src/main/java/com/inuker/solution/MaximumSizeSubarraySumEqualsK.java +++ b/leetcode/solution/src/MaximumSizeSubarraySumEqualsK.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.HashMap; -/** - * Created by dingjikerbo on 2016/11/19. - */ - public class MaximumSizeSubarraySumEqualsK { // 耗时29ms,时间复杂度O(n) diff --git a/solution/src/main/java/com/inuker/solution/MaximumSubarray.java b/leetcode/solution/src/MaximumSubarray.java similarity index 58% rename from solution/src/main/java/com/inuker/solution/MaximumSubarray.java rename to leetcode/solution/src/MaximumSubarray.java index bf81892..2c7d279 100644 --- a/solution/src/main/java/com/inuker/solution/MaximumSubarray.java +++ b/leetcode/solution/src/MaximumSubarray.java @@ -1,34 +1,24 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/15. - */ - public class MaximumSubarray { // dp[i]表示包含第i个元素时的最大和 public int maxSubArray(int[] nums) { - if (nums.length == 0) { - return 0; - } int[] dp = new int[nums.length]; int max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { - dp[i] = nums[i]; - if (i > 0 && dp[i - 1] > 0) { - dp[i] += dp[i - 1]; - } + dp[i] = Math.max(i > 0 ? dp[i - 1] + nums[i] : nums[i], nums[i]); max = Math.max(max, dp[i]); } return max; } - public int maxSubArray2(int[] nums) { + /* 这里dp其实可以去掉,换成一个普通int变量即可 + public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE, prev = 0; for (int i = 0; i < nums.length; i++) { - prev = Math.max(nums[i], nums[i] + prev); + prev = Math.max(i > 0 ? prev + nums[i] : nums[i], nums[i]); max = Math.max(max, prev); } return max; } + */ } diff --git a/solution/src/main/java/com/inuker/solution/MedianOfTwoSortedArrays.java b/leetcode/solution/src/MedianOfTwoSortedArrays.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/MedianOfTwoSortedArrays.java rename to leetcode/solution/src/MedianOfTwoSortedArrays.java index 9e7a4d5..1edb615 100644 --- a/solution/src/main/java/com/inuker/solution/MedianOfTwoSortedArrays.java +++ b/leetcode/solution/src/MedianOfTwoSortedArrays.java @@ -1,7 +1,4 @@ -package com.inuker.solution; - /** - * Created by dingjikerbo on 16/12/20. * https://leetcode.com/articles/median-of-two-sorted-arrays/ */ @@ -27,7 +24,7 @@ private double findKth(int[] nums1, int start1, int end1, int[] nums2, int start if (len1 > len2) { return findKth(nums2, start2, end2, nums1, start1, end1, k); } else if (len1 == 0) { - return nums2[k - 1]; + return nums2[start2 + k - 1]; } else if (k == 1) { return Math.min(nums1[start1], nums2[start2]); } diff --git a/solution/src/main/java/com/inuker/solution/MeetingRooms.java b/leetcode/solution/src/MeetingRooms.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/MeetingRooms.java rename to leetcode/solution/src/MeetingRooms.java index 490e3c8..c2ae246 100644 --- a/solution/src/main/java/com/inuker/solution/MeetingRooms.java +++ b/leetcode/solution/src/MeetingRooms.java @@ -1,14 +1,6 @@ -package com.inuker.solution; - -import com.leetcode.library.Interval; - import java.util.Arrays; import java.util.Comparator; -/** - * Created by dingjikerbo on 16/11/20. - */ - /** * https://leetcode.com/articles/meeting-rooms/ */ diff --git a/solution/src/main/java/com/inuker/solution/MeetingRoomsII.java b/leetcode/solution/src/MeetingRoomsII.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/MeetingRoomsII.java rename to leetcode/solution/src/MeetingRoomsII.java index 16540f1..a4281e8 100644 --- a/solution/src/main/java/com/inuker/solution/MeetingRoomsII.java +++ b/leetcode/solution/src/MeetingRoomsII.java @@ -1,19 +1,11 @@ -package com.inuker.solution; - -import com.leetcode.library.Interval; - import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; -/** - * Created by dingjikerbo on 16/11/20. - */ - public class MeetingRoomsII { - // 耗时17ms,时间复杂度O(nlgn) + // 耗时7ms,时间复杂度O(nlgn) public int minMeetingRooms(Interval[] intervals) { Arrays.sort(intervals, new Comparator() { @Override diff --git a/solution/src/main/java/com/inuker/solution/MergeIntervals.java b/leetcode/solution/src/MergeIntervals.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/MergeIntervals.java rename to leetcode/solution/src/MergeIntervals.java index 7242531..ba5e827 100644 --- a/solution/src/main/java/com/inuker/solution/MergeIntervals.java +++ b/leetcode/solution/src/MergeIntervals.java @@ -1,14 +1,9 @@ -package com.inuker.solution; - -import com.leetcode.library.Interval; - import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** - * Created by dingjikerbo on 16/11/21. * https://leetcode.com/articles/merge-intervals/ */ diff --git a/leetcode/solution/src/MergeKSortedList.java b/leetcode/solution/src/MergeKSortedList.java new file mode 100644 index 0000000..c046b9d --- /dev/null +++ b/leetcode/solution/src/MergeKSortedList.java @@ -0,0 +1,81 @@ +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * https://leetcode.com/articles/merge-k-sorted-list/ + */ + +public class MergeKSortedList { + + // 耗时19ms + // 时间复杂度为O(knlgn),空间复杂度O(k) + /** + * 这里要注意lists中可能有node为null + */ + public ListNode mergeKLists(ListNode[] lists) { + ListNode dummy = new ListNode(0), cur = dummy; + + PriorityQueue queue = new PriorityQueue<>(new Comparator() { + @Override + public int compare(ListNode node1, ListNode node2) { + return node1.val - node2.val; + } + }); + + for (ListNode node : lists) { + if (node != null) { + queue.offer(node); + } + } + + while (!queue.isEmpty()) { + ListNode node = queue.poll(); + cur.next = node; + cur = cur.next; + if (node.next != null) { + queue.offer(node.next); + } + } + + return dummy.next; + } + + /** + * 第二种方法 + * 时间复杂度O(Nlgk),空间O(l) + * 耗时10ms + */ + public ListNode mergeKLists2(ListNode[] lists) { + return helper(lists, 0, lists.length - 1); + } + + private ListNode helper(ListNode[] lists, int start, int end) { + if (start > end) { + return null; + } + if (start == end) { + return lists[start]; + } + int mid = start + (end - start) / 2; + ListNode l1 = helper(lists, start, mid); + ListNode l2 = helper(lists, mid + 1, end); + return mergeTwoLists(l1, l2); + } + + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode p = l1, q = l2, cur = dummy; + for ( ; p != null && q != null; ) { + if (p.val < q.val) { + cur.next = p; + p = p.next; + } else { + cur.next = q; + q = q.next; + } + cur = cur.next; + } + cur.next = p != null ? p : q; + return dummy.next; + } +} diff --git a/solution/src/main/java/com/inuker/solution/MergeSortedArray.java b/leetcode/solution/src/MergeSortedArray.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/MergeSortedArray.java rename to leetcode/solution/src/MergeSortedArray.java index 1dfd673..d834f14 100644 --- a/solution/src/main/java/com/inuker/solution/MergeSortedArray.java +++ b/leetcode/solution/src/MergeSortedArray.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class MergeSortedArray { public void merge(int[] nums1, int m, int[] nums2, int n) { diff --git a/leetcode/solution/src/MergeTwoBinaryTrees.java b/leetcode/solution/src/MergeTwoBinaryTrees.java new file mode 100644 index 0000000..49cae76 --- /dev/null +++ b/leetcode/solution/src/MergeTwoBinaryTrees.java @@ -0,0 +1,13 @@ +public class MergeTwoBinaryTrees { + + public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { + if (t1 == null) + return t2; + if (t2 == null) + return t1; + t1.val += t2.val; + t1.left = mergeTrees(t1.left, t2.left); + t1.right = mergeTrees(t1.right, t2.right); + return t1; + } +} diff --git a/solution/src/main/java/com/inuker/solution/MergeTwoSortedList.java b/leetcode/solution/src/MergeTwoSortedList.java similarity index 81% rename from solution/src/main/java/com/inuker/solution/MergeTwoSortedList.java rename to leetcode/solution/src/MergeTwoSortedList.java index 2b3e110..f006d7c 100644 --- a/solution/src/main/java/com/inuker/solution/MergeTwoSortedList.java +++ b/leetcode/solution/src/MergeTwoSortedList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - public class MergeTwoSortedList { // 耗时15ms diff --git a/solution/src/main/java/com/inuker/solution/MinStack.java b/leetcode/solution/src/MinStack.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/MinStack.java rename to leetcode/solution/src/MinStack.java index 253ab94..ac8cf47 100644 --- a/solution/src/main/java/com/inuker/solution/MinStack.java +++ b/leetcode/solution/src/MinStack.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Stack; -/** - * Created by dingjikerbo on 2016/11/17. - */ - public class MinStack { Stack mMinStack; diff --git a/leetcode/solution/src/MinimumCostToHireKWorkers.java b/leetcode/solution/src/MinimumCostToHireKWorkers.java new file mode 100644 index 0000000..2741a11 --- /dev/null +++ b/leetcode/solution/src/MinimumCostToHireKWorkers.java @@ -0,0 +1,55 @@ +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.Queue; + +public class MinimumCostToHireKWorkers { + + class Man { + int quality; + int wage; + + Man(int a, int b) { + quality = a; + wage = b; + } + + double ratio() { + return (double) wage / quality; + } + } + + /** + * 这题意思是选取K个工人,保证付给他们的工资和quality的比例都是一样的,且不低于他们的期望工资,问最少付的工资是多少 + * 定义性价比为wage/quality,这个值越小表示性价比越高 + * 将所有工人按性价比排序,显然要少付工资,当然尽可能选取更多的高性价比工人 + * 为了满足所有人工资和quality比例都一样,这个比例显然是所选的K个工人中性价比最低的那个 + * 不能完全按性价比来,因为可能存在的情况是高性价比quality也高,在ratio一定的情况下,要付出的总工资也多 + * 所以要对性价比从高到低地遍历工人,边遍历边当满足K个人数的时候计算要付出的工资,人数超的时候踢掉quality最高的那个人,因为越往后遍历ratio越大,那么总体的quality + * 要尽可能小才行 + */ + public double mincostToHireWorkers(int[] quality, int[] wage, int K) { + Queue queue = new PriorityQueue<>(new Comparator() { + @Override + public int compare(Man o1, Man o2) { + return o1.ratio() > o2.ratio() ? 1 : -1; + } + }); + for (int i = 0; i < quality.length; i++) { + queue.offer(new Man(quality[i], wage[i])); + } + double money = Integer.MAX_VALUE, qsum = 0; + Queue queue2 = new PriorityQueue<>(Comparator.reverseOrder()); + while (!queue.isEmpty()) { + Man man = queue.poll(); + qsum += man.quality; + queue2.offer(man.quality); + if (queue2.size() > K) { + qsum -= queue2.poll(); + } + if (queue2.size() == K) { + money = Math.min(money, qsum * man.ratio()); + } + } + return money; + } +} diff --git a/solution/src/main/java/com/inuker/solution/MinimumDepthOfBinaryTree.java b/leetcode/solution/src/MinimumDepthOfBinaryTree.java similarity index 50% rename from solution/src/main/java/com/inuker/solution/MinimumDepthOfBinaryTree.java rename to leetcode/solution/src/MinimumDepthOfBinaryTree.java index ceffc06..82ad4f4 100644 --- a/solution/src/main/java/com/inuker/solution/MinimumDepthOfBinaryTree.java +++ b/leetcode/solution/src/MinimumDepthOfBinaryTree.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/11/28. - */ - public class MinimumDepthOfBinaryTree { /** @@ -24,31 +16,15 @@ public int minDepth(TreeNode root) { if (root == null) { return 0; } - // 如果一边空了,那这边深度为0,但是由于不是叶子节点,所以不能算,得看另一边。 + if (root.left == null && root.right == null) { + return 1; + } if (root.left == null) { return minDepth(root.right) + 1; - } else if (root.right == null) { - return minDepth(root.left) + 1; - } else { - return Math.min(minDepth(root.left), minDepth(root.right)) + 1; } - } - - /** - public int minDepth(TreeNode root) { - if (root == null) { - return 0; + if (root.right == null) { + return minDepth(root.left) + 1; } - return helper(root); + return Math.min(minDepth(root.left), minDepth(root.right)) + 1; } - - private int helper(TreeNode root) { - if (root == null) { - return Integer.MAX_VALUE; - } - if (root.left == null && root.right == null) { - return 1; - } - return Math.min(helper(root.left), helper(root.right)) + 1; - }*/ } diff --git a/solution/src/main/java/com/inuker/solution/MinimumHeightTrees.java b/leetcode/solution/src/MinimumHeightTrees.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/MinimumHeightTrees.java rename to leetcode/solution/src/MinimumHeightTrees.java index 8d51200..a231294 100644 --- a/solution/src/main/java/com/inuker/solution/MinimumHeightTrees.java +++ b/leetcode/solution/src/MinimumHeightTrees.java @@ -1,14 +1,4 @@ -package com.inuker.solution; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * Created by liwentian on 2017/9/3. - */ +import java.util.*; /** * 从叶子节点开始,一层层剥掉,直到最后剩下的节点就是所求深度最大的 diff --git a/solution/src/main/java/com/inuker/solution/MinimumSizeSubarraySum.java b/leetcode/solution/src/MinimumSizeSubarraySum.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/MinimumSizeSubarraySum.java rename to leetcode/solution/src/MinimumSizeSubarraySum.java index 4bf67a0..74245f5 100644 --- a/solution/src/main/java/com/inuker/solution/MinimumSizeSubarraySum.java +++ b/leetcode/solution/src/MinimumSizeSubarraySum.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 16/11/22. - */ - public class MinimumSizeSubarraySum { /** * 仍然采用滑动窗口的办法 diff --git a/solution/src/main/java/com/inuker/solution/MinimumWindowSubstring.java b/leetcode/solution/src/MinimumWindowSubstring.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/MinimumWindowSubstring.java rename to leetcode/solution/src/MinimumWindowSubstring.java index 6886d04..1d3cb68 100644 --- a/solution/src/main/java/com/inuker/solution/MinimumWindowSubstring.java +++ b/leetcode/solution/src/MinimumWindowSubstring.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/21. - */ - public class MinimumWindowSubstring { - // 耗时8ms,时间复杂度O(n) + // 耗时6ms,时间复杂度O(n) public String minWindow(String s, String t) { int[] tc = new int[256], sc = new int[256]; for (char c : t.toCharArray()) { diff --git a/solution/src/main/java/com/inuker/solution/MissingNumber.java b/leetcode/solution/src/MissingNumber.java similarity index 74% rename from solution/src/main/java/com/inuker/solution/MissingNumber.java rename to leetcode/solution/src/MissingNumber.java index 89c7763..97c42e2 100644 --- a/solution/src/main/java/com/inuker/solution/MissingNumber.java +++ b/leetcode/solution/src/MissingNumber.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class MissingNumber { public int missingNumber(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/MissingRanges.java b/leetcode/solution/src/MissingRanges.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/MissingRanges.java rename to leetcode/solution/src/MissingRanges.java index d27c689..4380310 100644 --- a/solution/src/main/java/com/inuker/solution/MissingRanges.java +++ b/leetcode/solution/src/MissingRanges.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/11. - */ - /** * TestCases * [], lower=1, upper=1 diff --git a/leetcode/solution/src/MostCommonWord.java b/leetcode/solution/src/MostCommonWord.java new file mode 100644 index 0000000..31649cf --- /dev/null +++ b/leetcode/solution/src/MostCommonWord.java @@ -0,0 +1,44 @@ +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; + +public class MostCommonWord { + + /** + * 要注意结尾的单词 + */ + public String mostCommonWord(String paragraph, String[] banned) { + HashMap map = new HashMap<>(); + HashSet bannes = new HashSet<>(Arrays.asList(banned)); + + String result = null; + int count = 0; + + boolean enterWord = false; + for (int i = 0, j = 0; j <= paragraph.length(); j++) { + char c = j < paragraph.length() ? paragraph.charAt(j) : '.'; + if (Character.isAlphabetic(c)) { + if (!enterWord) { + enterWord = true; + i = j; + } + } else { + if (enterWord) { + enterWord = false; + String word = paragraph.substring(i, j).toLowerCase(); + if (!bannes.contains(word)) { + int cnt = map.getOrDefault(word, 0) + 1; + map.put(word, cnt); + + if (cnt > count) { + count = cnt; + result = word; + } + } + } + } + } + + return result; + } +} diff --git a/solution/src/main/java/com/inuker/solution/MostFrequentSubtreeSum.java b/leetcode/solution/src/MostFrequentSubtreeSum.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/MostFrequentSubtreeSum.java rename to leetcode/solution/src/MostFrequentSubtreeSum.java index 43558b0..ab746d4 100644 --- a/solution/src/main/java/com/inuker/solution/MostFrequentSubtreeSum.java +++ b/leetcode/solution/src/MostFrequentSubtreeSum.java @@ -1,15 +1,7 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.HashMap; import java.util.LinkedList; import java.util.List; -/** - * Created by liwentian on 17/8/3. - */ - /** * 这题算法比较直观 */ diff --git a/solution/src/main/java/com/inuker/solution/MoveZeroes.java b/leetcode/solution/src/MoveZeroes.java similarity index 67% rename from solution/src/main/java/com/inuker/solution/MoveZeroes.java rename to leetcode/solution/src/MoveZeroes.java index 038c848..c93b7b5 100644 --- a/solution/src/main/java/com/inuker/solution/MoveZeroes.java +++ b/leetcode/solution/src/MoveZeroes.java @@ -1,23 +1,19 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/19. - */ - /** * https://leetcode.com/articles/move-zeroes/ */ public class MoveZeroes { /** - * 要保持顺序,写的次数最少 + * 要保持顺序 */ public void moveZeroes(int[] nums) { - for (int i = 0, j = 0; j < nums.length; j++) { - if (nums[j] != 0) { - swap(nums, i++, j); + int j = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] != 0) { + nums[j++] = nums[i]; } } + for ( ; j < nums.length; nums[j++] = 0); } private void swap(int[] nums, int i, int j) { @@ -28,6 +24,7 @@ private void swap(int[] nums, int i, int j) { /** * 如果不要求保持顺序,且写的次数最少 + * 从两头开始往中间走,如果左边是0,右边非0,则交换,写的次数是0的个数乘2 */ public void moveZeroes2(int[] nums) { for (int i = 0, j = nums.length - 1; j > i; ) { diff --git a/solution/src/main/java/com/inuker/solution/MovingAverage.java b/leetcode/solution/src/MovingAverage.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/MovingAverage.java rename to leetcode/solution/src/MovingAverage.java index 4d7eb68..3916cfa 100644 --- a/solution/src/main/java/com/inuker/solution/MovingAverage.java +++ b/leetcode/solution/src/MovingAverage.java @@ -1,12 +1,5 @@ -package com.inuker.solution; - import java.util.Deque; import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 16/12/4. - */ public class MovingAverage { diff --git a/solution/src/main/java/com/inuker/solution/MultiplyStrings.java b/leetcode/solution/src/MultiplyStrings.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/MultiplyStrings.java rename to leetcode/solution/src/MultiplyStrings.java index e596665..114cc6e 100644 --- a/solution/src/main/java/com/inuker/solution/MultiplyStrings.java +++ b/leetcode/solution/src/MultiplyStrings.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/22. - */ - public class MultiplyStrings { public String multiply(String num1, String num2) { diff --git a/solution/src/main/java/com/inuker/solution/MyQueue.java b/leetcode/solution/src/MyQueue.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/MyQueue.java rename to leetcode/solution/src/MyQueue.java index fbe1a71..6341b73 100644 --- a/solution/src/main/java/com/inuker/solution/MyQueue.java +++ b/leetcode/solution/src/MyQueue.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Stack; -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * https://leetcode.com/articles/implement-queue-using-stacks/ */ diff --git a/solution/src/main/java/com/inuker/solution/MyStack.java b/leetcode/solution/src/MyStack.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/MyStack.java rename to leetcode/solution/src/MyStack.java index 073f29b..e22ec04 100644 --- a/solution/src/main/java/com/inuker/solution/MyStack.java +++ b/leetcode/solution/src/MyStack.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.Queue; -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * https://leetcode.com/articles/implement-stack-using-queues/ */ diff --git a/solution/src/main/java/com/inuker/solution/NQueens.java b/leetcode/solution/src/NQueens.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/NQueens.java rename to leetcode/solution/src/NQueens.java index 030b708..43444a2 100644 --- a/solution/src/main/java/com/inuker/solution/NQueens.java +++ b/leetcode/solution/src/NQueens.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 17/1/12. - */ - public class NQueens { public List> solveNQueens(int n) { diff --git a/solution/src/main/java/com/inuker/solution/NQueensII.java b/leetcode/solution/src/NQueensII.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/NQueensII.java rename to leetcode/solution/src/NQueensII.java index c2fb4e6..d4ae0d5 100644 --- a/solution/src/main/java/com/inuker/solution/NQueensII.java +++ b/leetcode/solution/src/NQueensII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/1/12. - */ - public class NQueensII { private int total; diff --git a/solution/src/main/java/com/inuker/solution/NestedListWeightSum.java b/leetcode/solution/src/NestedListWeightSum.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/NestedListWeightSum.java rename to leetcode/solution/src/NestedListWeightSum.java index b0b2580..606fa13 100644 --- a/solution/src/main/java/com/inuker/solution/NestedListWeightSum.java +++ b/leetcode/solution/src/NestedListWeightSum.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - /** * https://leetcode.com/articles/nested-list-weight-sum/ */ diff --git a/solution/src/main/java/com/inuker/solution/NestedListWeightSumII.java b/leetcode/solution/src/NestedListWeightSumII.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/NestedListWeightSumII.java rename to leetcode/solution/src/NestedListWeightSumII.java index a304283..59e2bbf 100644 --- a/solution/src/main/java/com/inuker/solution/NestedListWeightSumII.java +++ b/leetcode/solution/src/NestedListWeightSumII.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - /** * https://leetcode.com/articles/nested-list-weight-sum/ */ diff --git a/leetcode/solution/src/NextClosestTime.java b/leetcode/solution/src/NextClosestTime.java new file mode 100644 index 0000000..7d75759 --- /dev/null +++ b/leetcode/solution/src/NextClosestTime.java @@ -0,0 +1,62 @@ +import java.util.Arrays; +import java.util.TreeSet; + +public class NextClosestTime { + + /** + * 整体思路如下: + * 首先对输入的时间所包含的数要统计一下,并从小到大排序 + * 接下来从时间的高位开始,寻找可替代的更大的数,如果找不到,就看下一位,如果找到了就替换成该数,判断时间是否有效 + * 如果有效,则将该位往上全部替换为全局最小的数,并返回结果。否则还原该位,并继续看下一位。 + */ + public String nextClosestTime(String time) { + int[] number = new int[4]; + + time = time.substring(0, 2) + time.substring(3); + + for (int i = 0; i < time.length(); i++) { + number[i] = time.charAt(i) - '0'; + } + + Arrays.sort(number); + + StringBuilder sb = new StringBuilder(time); + + int i; + for (i = 3; i >= 0; i--) { + char c = time.charAt(i); + int k = nextNumber(number, c - '0'); + if (k >= 0) { + sb.setCharAt(i, (char) (k + '0')); + if (isValid(sb)) { + break; + } + sb.setCharAt(i, c); + } + } + for (i++; i < 4; i++) { + sb.setCharAt(i, (char) (number[0] + '0')); + } + sb.insert(2, ':'); + return sb.toString(); + } + + // 判断时间是否有效 + private boolean isValid(StringBuilder sb) { + boolean flag1 = sb.charAt(0) < '2' || (sb.charAt(0) == '2' && sb.charAt(1) <= '3'); + boolean flag2 = sb.charAt(2) < '5' || (sb.charAt(2) == '5' && sb.charAt(3) <= '9'); + return flag1 && flag2; + } + + /** + * 找比n更大的数,number是一个升序的数组 + */ + private int nextNumber(int[] number, int n) { + for (int i = 0; i < number.length; i++) { + if (number[i] > n) { + return number[i]; + } + } + return -1; + } +} diff --git a/solution/src/main/java/com/inuker/solution/NextPermutation.java b/leetcode/solution/src/NextPermutation.java similarity index 59% rename from solution/src/main/java/com/inuker/solution/NextPermutation.java rename to leetcode/solution/src/NextPermutation.java index a4fce65..3c5efb2 100644 --- a/solution/src/main/java/com/inuker/solution/NextPermutation.java +++ b/leetcode/solution/src/NextPermutation.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - /** * https://leetcode.com/articles/next-permutation/ */ @@ -14,26 +8,24 @@ public class NextPermutation { * 然后从升序中找到一个大于nums[i-1]的最小数与i-1交换,然后对升序整体revert为降序即可 */ public void nextPermutation(int[] nums) { - int i = nums.length - 1; + int i, j; - for ( ; i >= 0; i--) { - if (i > 0 && nums[i - 1] < nums[i]) { + for (i = nums.length - 1; i > 0; i--) { + if (nums[i - 1] < nums[i]) { break; } } - if (i < 0) { - revert(nums, 0, nums.length - 1); - return; - } - - for (int j = nums.length - 1; j >= i; j--) { - if (nums[j] > nums[i - 1]) { - swap(nums, j, i - 1); - revert(nums, i, nums.length - 1); - break; + if (i > 0) { + for (j = i; j < nums.length; j++) { + if (nums[j] <= nums[i - 1]) { + break; + } } + swap(nums, i - 1, j - 1); } + + revert(nums, i, nums.length - 1); } private void swap(int[] nums, int left, int right) { diff --git a/solution/src/main/java/com/inuker/solution/NumArray.java b/leetcode/solution/src/NumArray.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/NumArray.java rename to leetcode/solution/src/NumArray.java index 9005296..9659f01 100644 --- a/solution/src/main/java/com/inuker/solution/NumArray.java +++ b/leetcode/solution/src/NumArray.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/26. - */ - /** * https://leetcode.com/articles/range-sum-query-immutable/ */ diff --git a/solution/src/main/java/com/inuker/solution/NumArrayII.java b/leetcode/solution/src/NumArrayII.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/NumArrayII.java rename to leetcode/solution/src/NumArrayII.java index 6b8e206..153d026 100644 --- a/solution/src/main/java/com/inuker/solution/NumArrayII.java +++ b/leetcode/solution/src/NumArrayII.java @@ -1,8 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/26. - */ /** * 这题可以用segment tree或binary index tree(bit),两者时间复杂度都是lgn,不过segment tree因为用到树, * 而bit用的是数组,所以bit更省空间。 diff --git a/solution/src/main/java/com/inuker/solution/NumMatrix.java b/leetcode/solution/src/NumMatrix.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/NumMatrix.java rename to leetcode/solution/src/NumMatrix.java index 6661c58..f5d5323 100644 --- a/solution/src/main/java/com/inuker/solution/NumMatrix.java +++ b/leetcode/solution/src/NumMatrix.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/26. - */ - /** * https://leetcode.com/articles/range-sum-query-2d-immutable/ */ diff --git a/solution/src/main/java/com/inuker/solution/NumMatrixII.java b/leetcode/solution/src/NumMatrixII.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/NumMatrixII.java rename to leetcode/solution/src/NumMatrixII.java index 20de7c5..ce0c8c9 100644 --- a/solution/src/main/java/com/inuker/solution/NumMatrixII.java +++ b/leetcode/solution/src/NumMatrixII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/27. - */ - /** * 这道题有两种方法 * 1,2D BIT diff --git a/solution/src/main/java/com/inuker/solution/NumberOfConnectedComponents.java b/leetcode/solution/src/NumberOfConnectedComponents.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/NumberOfConnectedComponents.java rename to leetcode/solution/src/NumberOfConnectedComponents.java index 9ba9593..07446e3 100644 --- a/solution/src/main/java/com/inuker/solution/NumberOfConnectedComponents.java +++ b/leetcode/solution/src/NumberOfConnectedComponents.java @@ -1,14 +1,8 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -/** - * Created by dingjikerbo on 17/1/2. - */ - public class NumberOfConnectedComponents { // 8ms diff --git a/solution/src/main/java/com/inuker/solution/NumberOfDigitOne.java b/leetcode/solution/src/NumberOfDigitOne.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/NumberOfDigitOne.java rename to leetcode/solution/src/NumberOfDigitOne.java index dce32db..fe8b2b3 100644 --- a/solution/src/main/java/com/inuker/solution/NumberOfDigitOne.java +++ b/leetcode/solution/src/NumberOfDigitOne.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/21. - */ - public class NumberOfDigitOne { /** diff --git a/solution/src/main/java/com/inuker/solution/NumberOfIslands.java b/leetcode/solution/src/NumberOfIslands.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/NumberOfIslands.java rename to leetcode/solution/src/NumberOfIslands.java index 3f1f93d..7e699e8 100644 --- a/solution/src/main/java/com/inuker/solution/NumberOfIslands.java +++ b/leetcode/solution/src/NumberOfIslands.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - import java.util.LinkedList; import java.util.Queue; diff --git a/solution/src/main/java/com/inuker/solution/NumberOfIslandsII.java b/leetcode/solution/src/NumberOfIslandsII.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/NumberOfIslandsII.java rename to leetcode/solution/src/NumberOfIslandsII.java index a835dcf..2a4d191 100644 --- a/solution/src/main/java/com/inuker/solution/NumberOfIslandsII.java +++ b/leetcode/solution/src/NumberOfIslandsII.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/11. - */ - /** * 经典的UF(Union Find)问题,可翻阅《算法》1.5章 * UF时间复杂度和节点个数有关 diff --git a/solution/src/main/java/com/inuker/solution/OddEvenLinkedList.java b/leetcode/solution/src/OddEvenLinkedList.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/OddEvenLinkedList.java rename to leetcode/solution/src/OddEvenLinkedList.java index 9e6608f..dbd91a7 100644 --- a/solution/src/main/java/com/inuker/solution/OddEvenLinkedList.java +++ b/leetcode/solution/src/OddEvenLinkedList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 16/12/7. - */ - public class OddEvenLinkedList { public ListNode oddEvenList(ListNode head) { diff --git a/solution/src/main/java/com/inuker/solution/OneEditDistance.java b/leetcode/solution/src/OneEditDistance.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/OneEditDistance.java rename to leetcode/solution/src/OneEditDistance.java index 6063d64..3786f06 100644 --- a/solution/src/main/java/com/inuker/solution/OneEditDistance.java +++ b/leetcode/solution/src/OneEditDistance.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/20. - */ - public class OneEditDistance { /** * 最容易错的是结尾的条件sL != tL diff --git a/solution/src/main/java/com/inuker/solution/PaintHouse.java b/leetcode/solution/src/PaintHouse.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/PaintHouse.java rename to leetcode/solution/src/PaintHouse.java index 3360784..2e4d1b8 100644 --- a/solution/src/main/java/com/inuker/solution/PaintHouse.java +++ b/leetcode/solution/src/PaintHouse.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/18. - */ - public class PaintHouse { public int minCost(int[][] costs) { diff --git a/solution/src/main/java/com/inuker/solution/PaintHouseII.java b/leetcode/solution/src/PaintHouseII.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/PaintHouseII.java rename to leetcode/solution/src/PaintHouseII.java index d1bf76a..751d23e 100644 --- a/solution/src/main/java/com/inuker/solution/PaintHouseII.java +++ b/leetcode/solution/src/PaintHouseII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/18. - */ - public class PaintHouseII { /** diff --git a/solution/src/main/java/com/inuker/solution/PalindromeLinkedList.java b/leetcode/solution/src/PalindromeLinkedList.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/PalindromeLinkedList.java rename to leetcode/solution/src/PalindromeLinkedList.java index e8b91e2..d6128d4 100644 --- a/solution/src/main/java/com/inuker/solution/PalindromeLinkedList.java +++ b/leetcode/solution/src/PalindromeLinkedList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - public class PalindromeLinkedList { // 耗时2ms diff --git a/solution/src/main/java/com/inuker/solution/PalindromeNumber.java b/leetcode/solution/src/PalindromeNumber.java similarity index 53% rename from solution/src/main/java/com/inuker/solution/PalindromeNumber.java rename to leetcode/solution/src/PalindromeNumber.java index 63e8338..2fd2171 100644 --- a/solution/src/main/java/com/inuker/solution/PalindromeNumber.java +++ b/leetcode/solution/src/PalindromeNumber.java @@ -1,11 +1,6 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class PalindromeNumber { + // 耗时101ms public boolean isPalindrome(int x) { if (x < 0) { return false; @@ -22,4 +17,19 @@ public boolean isPalindrome(int x) { return true; } + + /** + * 直接给数倒过来看是否相等 + * 耗时103ms + */ + public boolean isPalindrome2(int x) { + if (x < 0) { + return false; + } + int n = 0, m = x; + for ( ; x > 0; x /= 10) { + n = n * 10 + x % 10; + } + return n == m; + } } diff --git a/solution/src/main/java/com/inuker/solution/PalindromePairs.java b/leetcode/solution/src/PalindromePairs.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/PalindromePairs.java rename to leetcode/solution/src/PalindromePairs.java index c46f38c..8f9c3b8 100644 --- a/solution/src/main/java/com/inuker/solution/PalindromePairs.java +++ b/leetcode/solution/src/PalindromePairs.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class PalindromePairs { public List> palindromePairs(String[] words) { diff --git a/solution/src/main/java/com/inuker/solution/PalindromePartitioning.java b/leetcode/solution/src/PalindromePartitioning.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/PalindromePartitioning.java rename to leetcode/solution/src/PalindromePartitioning.java index f3013be..3693b58 100644 --- a/solution/src/main/java/com/inuker/solution/PalindromePartitioning.java +++ b/leetcode/solution/src/PalindromePartitioning.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Collections; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class PalindromePartitioning { /** diff --git a/solution/src/main/java/com/inuker/solution/PalindromePartitioningII.java b/leetcode/solution/src/PalindromePartitioningII.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/PalindromePartitioningII.java rename to leetcode/solution/src/PalindromePartitioningII.java index 5cce6af..3d14b4d 100644 --- a/solution/src/main/java/com/inuker/solution/PalindromePartitioningII.java +++ b/leetcode/solution/src/PalindromePartitioningII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class PalindromePartitioningII { /** diff --git a/solution/src/main/java/com/inuker/solution/PalindromePermutation.java b/leetcode/solution/src/PalindromePermutation.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/PalindromePermutation.java rename to leetcode/solution/src/PalindromePermutation.java index 39cf299..0f02c8f 100644 --- a/solution/src/main/java/com/inuker/solution/PalindromePermutation.java +++ b/leetcode/solution/src/PalindromePermutation.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/19. - */ - public class PalindromePermutation { public boolean canPermutePalindrome(String s) { diff --git a/solution/src/main/java/com/inuker/solution/PalindromePermutationII.java b/leetcode/solution/src/PalindromePermutationII.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/PalindromePermutationII.java rename to leetcode/solution/src/PalindromePermutationII.java index 2e08cb0..1e92297 100644 --- a/solution/src/main/java/com/inuker/solution/PalindromePermutationII.java +++ b/leetcode/solution/src/PalindromePermutationII.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/19. - */ - /** * https://leetcode.com/articles/palindrome-permutation-ii/ */ diff --git a/solution/src/main/java/com/inuker/solution/PartitionList.java b/leetcode/solution/src/PartitionList.java similarity index 80% rename from solution/src/main/java/com/inuker/solution/PartitionList.java rename to leetcode/solution/src/PartitionList.java index 68d8200..f03168f 100644 --- a/solution/src/main/java/com/inuker/solution/PartitionList.java +++ b/leetcode/solution/src/PartitionList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 2017/9/11. - */ - public class PartitionList { ListNode partition(ListNode head, int x) { diff --git a/solution/src/main/java/com/inuker/solution/PascalTriangleII.java b/leetcode/solution/src/PascalTriangleII.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/PascalTriangleII.java rename to leetcode/solution/src/PascalTriangleII.java index c448c85..da420e5 100644 --- a/solution/src/main/java/com/inuker/solution/PascalTriangleII.java +++ b/leetcode/solution/src/PascalTriangleII.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by liwentian on 17/8/12. - */ - public class PascalTriangleII { public List getRow(int rowIndex) { diff --git a/solution/src/main/java/com/inuker/solution/PascalsTriangle.java b/leetcode/solution/src/PascalsTriangle.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/PascalsTriangle.java rename to leetcode/solution/src/PascalsTriangle.java index 93bdb63..00c940e 100644 --- a/solution/src/main/java/com/inuker/solution/PascalsTriangle.java +++ b/leetcode/solution/src/PascalsTriangle.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by liwentian on 2017/9/10. - */ - public class PascalsTriangle { public List> generate(int numRows) { diff --git a/solution/src/main/java/com/inuker/solution/PathSum.java b/leetcode/solution/src/PathSum.java similarity index 74% rename from solution/src/main/java/com/inuker/solution/PathSum.java rename to leetcode/solution/src/PathSum.java index 8a7f0f6..f984901 100644 --- a/solution/src/main/java/com/inuker/solution/PathSum.java +++ b/leetcode/solution/src/PathSum.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/11/29. - */ - public class PathSum { public boolean hasPathSum(TreeNode root, int sum) { diff --git a/leetcode/solution/src/PathSumII.java b/leetcode/solution/src/PathSumII.java new file mode 100644 index 0000000..a3de058 --- /dev/null +++ b/leetcode/solution/src/PathSumII.java @@ -0,0 +1,29 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class PathSumII { + + public List> pathSum(TreeNode root, int sum) { + List> result = new LinkedList<>(); + helper(root, sum, result, new LinkedList<>()); + return result; + } + + private void helper(TreeNode node, int sum, List> result, List list) { + if (node == null) { + return; + } + + list.add(node.val); + + if (node.left == null && node.right == null && sum == node.val) { + result.add(new ArrayList<>(list)); + } else { + helper(node.left, sum - node.val, result, list); + helper(node.right, sum - node.val, result, list); + } + + list.remove(list.size() - 1); + } +} diff --git a/solution/src/main/java/com/inuker/solution/PathSumIII.java b/leetcode/solution/src/PathSumIII.java similarity index 57% rename from solution/src/main/java/com/inuker/solution/PathSumIII.java rename to leetcode/solution/src/PathSumIII.java index e6f29b8..50c85ef 100644 --- a/solution/src/main/java/com/inuker/solution/PathSumIII.java +++ b/leetcode/solution/src/PathSumIII.java @@ -1,13 +1,4 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 16/12/3. - */ +import java.util.HashMap; public class PathSumIII { @@ -58,35 +49,34 @@ private void helper(TreeNode root, int sum, int[] count) { helper(root.right, sum - root.val, count); } - /* 如果要给路径打出来 - public List pathSum(TreeNode root, int sum) { - List result = new LinkedList<>(); - pathSum(root, sum, result, ""); - return result; + /** + * 更优化的写法,时间复杂度O(n) + * 和Two Sum较类似,都是算出从root到当前节点的和,target为两段和的差值 + */ + public int pathSum2(TreeNode root, int sum) { + HashMap map = new HashMap<>(); + map.put(0, 1); + + int[] count = new int[1]; + helper(root, sum, 0, map, count); + return count[0]; } - private void pathSum(TreeNode root, int sum, List list, String path) { - if (root == null) { + private void helper(TreeNode node, int target, int sum, HashMap map, int[] count) { + if (node == null) { return; } - pathSumWithRoot(root, sum, list, path); - - pathSum(root.left, sum, list, ""); - pathSum(root.right, sum, list, ""); - } - - private void pathSumWithRoot(TreeNode root, int sum, List list, String path) { - if (root == null) { - return; + sum += node.val; + if (map.containsKey(sum - target)) { + count[0] += map.get(sum - target); } - String prefix = path.isEmpty() ? "" : path + "->"; + map.put(sum, map.getOrDefault(sum, 0) + 1); - if (root.val == sum) { - list.add(prefix + root.val); - } - pathSumWithRoot(root.left, sum - root.val, list, prefix + root.val); - pathSumWithRoot(root.right, sum - root.val, list, prefix + root.val); - }*/ + helper(node.left, target, sum, map, count); + helper(node.right, target, sum, map, count); + + map.put(sum, map.getOrDefault(sum, 0) - 1); + } } diff --git a/solution/src/main/java/com/inuker/solution/PeekingIterator.java b/leetcode/solution/src/PeekingIterator.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/PeekingIterator.java rename to leetcode/solution/src/PeekingIterator.java index 8da49e1..89dc5d2 100644 --- a/solution/src/main/java/com/inuker/solution/PeekingIterator.java +++ b/leetcode/solution/src/PeekingIterator.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Iterator; -/** - * Created by dingjikerbo on 16/12/10. - */ - public class PeekingIterator implements Iterator { private Iterator mIterator; diff --git a/solution/src/main/java/com/inuker/solution/PerfectRectangle.java b/leetcode/solution/src/PerfectRectangle.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/PerfectRectangle.java rename to leetcode/solution/src/PerfectRectangle.java index 2722304..b1d7d04 100644 --- a/solution/src/main/java/com/inuker/solution/PerfectRectangle.java +++ b/leetcode/solution/src/PerfectRectangle.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.HashSet; -/** - * Created by dingjikerbo on 17/1/2. - */ - /** * https://discuss.leetcode.com/topic/56052/really-easy-understanding-solution-o-n-java * http://www.cnblogs.com/grandyang/p/5825619.html diff --git a/solution/src/main/java/com/inuker/solution/PerfectSquares.java b/leetcode/solution/src/PerfectSquares.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/PerfectSquares.java rename to leetcode/solution/src/PerfectSquares.java index c707c8a..c980f06 100644 --- a/solution/src/main/java/com/inuker/solution/PerfectSquares.java +++ b/leetcode/solution/src/PerfectSquares.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ - public class PerfectSquares { public int numSquares(int n) { diff --git a/solution/src/main/java/com/inuker/solution/PermutationSequence.java b/leetcode/solution/src/PermutationSequence.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/PermutationSequence.java rename to leetcode/solution/src/PermutationSequence.java index 3080eee..ad5af92 100644 --- a/solution/src/main/java/com/inuker/solution/PermutationSequence.java +++ b/leetcode/solution/src/PermutationSequence.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class PermutationSequence { public String getPermutation(int n, int k) { diff --git a/solution/src/main/java/com/inuker/solution/Permutations.java b/leetcode/solution/src/Permutations.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/Permutations.java rename to leetcode/solution/src/Permutations.java index 22fd2ac..35aaf3d 100644 --- a/solution/src/main/java/com/inuker/solution/Permutations.java +++ b/leetcode/solution/src/Permutations.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class Permutations { public List> permute(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/PermutationsII.java b/leetcode/solution/src/PermutationsII.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/PermutationsII.java rename to leetcode/solution/src/PermutationsII.java index bbd7bd0..854645f 100644 --- a/solution/src/main/java/com/inuker/solution/PermutationsII.java +++ b/leetcode/solution/src/PermutationsII.java @@ -1,11 +1,4 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.List; diff --git a/solution/src/main/java/com/inuker/solution/PlusOne.java b/leetcode/solution/src/PlusOne.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/PlusOne.java rename to leetcode/solution/src/PlusOne.java index d2bf40a..c632da3 100644 --- a/solution/src/main/java/com/inuker/solution/PlusOne.java +++ b/leetcode/solution/src/PlusOne.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/8/30. - */ - public class PlusOne { public int[] plusOne(int[] digits) { diff --git a/solution/src/main/java/com/inuker/solution/PlusOneLinkedList.java b/leetcode/solution/src/PlusOneLinkedList.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/PlusOneLinkedList.java rename to leetcode/solution/src/PlusOneLinkedList.java index ada866a..766b196 100644 --- a/solution/src/main/java/com/inuker/solution/PlusOneLinkedList.java +++ b/leetcode/solution/src/PlusOneLinkedList.java @@ -1,13 +1,5 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - import java.util.Stack; -/** - * Created by liwentian on 2017/9/10. - */ - public class PlusOneLinkedList { public ListNode plusOne(ListNode head) { diff --git a/solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNode.java b/leetcode/solution/src/PopulatingNextRightPointersInEachNode.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNode.java rename to leetcode/solution/src/PopulatingNextRightPointersInEachNode.java index d619254..9e8c5bf 100644 --- a/solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNode.java +++ b/leetcode/solution/src/PopulatingNextRightPointersInEachNode.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeLinkNode; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class PopulatingNextRightPointersInEachNode { /** 递归法,巧妙地运用dummy使代码很简洁 diff --git a/solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNodeII.java b/leetcode/solution/src/PopulatingNextRightPointersInEachNodeII.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNodeII.java rename to leetcode/solution/src/PopulatingNextRightPointersInEachNodeII.java index a6be3eb..cb5747e 100644 --- a/solution/src/main/java/com/inuker/solution/PopulatingNextRightPointersInEachNodeII.java +++ b/leetcode/solution/src/PopulatingNextRightPointersInEachNodeII.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeLinkNode; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class PopulatingNextRightPointersInEachNodeII { /** diff --git a/solution/src/main/java/com/inuker/solution/Pow.java b/leetcode/solution/src/Pow.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/Pow.java rename to leetcode/solution/src/Pow.java index a5f1e71..c6175ed 100644 --- a/solution/src/main/java/com/inuker/solution/Pow.java +++ b/leetcode/solution/src/Pow.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class Pow { /** diff --git a/leetcode/solution/src/ProductOfArrayExceptSelf.java b/leetcode/solution/src/ProductOfArrayExceptSelf.java new file mode 100644 index 0000000..ca37575 --- /dev/null +++ b/leetcode/solution/src/ProductOfArrayExceptSelf.java @@ -0,0 +1,20 @@ +public class ProductOfArrayExceptSelf { + + // 耗时1ms + /** + * 对于每个数,就是给其左边所有数乘一遍,再给其右边所有数乘一遍 + */ + public int[] productExceptSelf(int[] nums) { + int[] res = new int[nums.length]; + int left = 1, right = 1; + for (int i = 0; i < nums.length; i++) { + res[i] = left; + left *= nums[i]; + } + for (int i = nums.length - 1; i >= 0; i--) { + res[i] *= right; + right *= nums[i]; + } + return res; + } +} diff --git a/solution/src/main/java/com/inuker/solution/QueueReconstructionByHeight.java b/leetcode/solution/src/QueueReconstructionByHeight.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/QueueReconstructionByHeight.java rename to leetcode/solution/src/QueueReconstructionByHeight.java index 17bd267..539f846 100644 --- a/solution/src/main/java/com/inuker/solution/QueueReconstructionByHeight.java +++ b/leetcode/solution/src/QueueReconstructionByHeight.java @@ -1,12 +1,9 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** - * Created by liwentian on 2017/9/1. *

* 这题核心思路是: * 1,先取出高度最高的那一组,如果有若干个高度相同的,则按k升序排列,这就是他们之后的相对顺序了。 diff --git a/solution/src/main/java/com/inuker/solution/RandomPickIndex.java b/leetcode/solution/src/RandomPickIndex.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/RandomPickIndex.java rename to leetcode/solution/src/RandomPickIndex.java index 61abcec..390e589 100644 --- a/solution/src/main/java/com/inuker/solution/RandomPickIndex.java +++ b/leetcode/solution/src/RandomPickIndex.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Random; -/** - * Created by dingjikerbo on 16/11/22. - */ - /** * 注意这里一定要给整个数组遍历完,这样才能保证所有数字的概率是一样的,否则只能保证 * 当前遍历过的数都是等概率的。 diff --git a/solution/src/main/java/com/inuker/solution/RangeAddition.java b/leetcode/solution/src/RangeAddition.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/RangeAddition.java rename to leetcode/solution/src/RangeAddition.java index c6ba1c0..5d0a220 100644 --- a/solution/src/main/java/com/inuker/solution/RangeAddition.java +++ b/leetcode/solution/src/RangeAddition.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - /** * https://leetcode.com/articles/range-addition/ */ diff --git a/solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4.java b/leetcode/solution/src/ReadNCharactersGivenRead4.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4.java rename to leetcode/solution/src/ReadNCharactersGivenRead4.java index 2447bb8..9f916e2 100644 --- a/solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4.java +++ b/leetcode/solution/src/ReadNCharactersGivenRead4.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/20. - */ - public abstract class ReadNCharactersGivenRead4 { public int read(char[] buf, int n) { diff --git a/solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4II.java b/leetcode/solution/src/ReadNCharactersGivenRead4II.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4II.java rename to leetcode/solution/src/ReadNCharactersGivenRead4II.java index afd8a1d..c49256f 100644 --- a/solution/src/main/java/com/inuker/solution/ReadNCharactersGivenRead4II.java +++ b/leetcode/solution/src/ReadNCharactersGivenRead4II.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/20. - */ - public abstract class ReadNCharactersGivenRead4II { private char[] mTmp = new char[4]; diff --git a/solution/src/main/java/com/inuker/solution/RearrangeStringKDistanceApart.java b/leetcode/solution/src/RearrangeStringKDistanceApart.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/RearrangeStringKDistanceApart.java rename to leetcode/solution/src/RearrangeStringKDistanceApart.java index 3e0d464..2ab20c4 100644 --- a/solution/src/main/java/com/inuker/solution/RearrangeStringKDistanceApart.java +++ b/leetcode/solution/src/RearrangeStringKDistanceApart.java @@ -1,14 +1,8 @@ -package com.inuker.solution; - import java.util.Comparator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; -/** - * Created by dingjikerbo on 17/1/6. - */ - public class RearrangeStringKDistanceApart { /** * 这题思路是先统计有哪些字符,并将这些字符按频率从高到底放在优先队列中,由于相同字符之间距离至少是k, diff --git a/solution/src/main/java/com/inuker/solution/ReconstructItinerary.java b/leetcode/solution/src/ReconstructItinerary.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/ReconstructItinerary.java rename to leetcode/solution/src/ReconstructItinerary.java index 745c17b..43f80f1 100644 --- a/solution/src/main/java/com/inuker/solution/ReconstructItinerary.java +++ b/leetcode/solution/src/ReconstructItinerary.java @@ -1,18 +1,5 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Stack; +import java.util.*; -/** - * Created by liwentian on 2017/9/2. - */ /** * 这题有两个前提 * 1, 必须从JFK开始 diff --git a/solution/src/main/java/com/inuker/solution/RecoverBinarySearchTree.java b/leetcode/solution/src/RecoverBinarySearchTree.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/RecoverBinarySearchTree.java rename to leetcode/solution/src/RecoverBinarySearchTree.java index 982106f..3f3e335 100644 --- a/solution/src/main/java/com/inuker/solution/RecoverBinarySearchTree.java +++ b/leetcode/solution/src/RecoverBinarySearchTree.java @@ -1,13 +1,5 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.Stack; -/** - * Created by dingjikerbo on 16/11/30. - */ - public class RecoverBinarySearchTree { TreeNode first, second, prev; diff --git a/solution/src/main/java/com/inuker/solution/RectangleArea.java b/leetcode/solution/src/RectangleArea.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/RectangleArea.java rename to leetcode/solution/src/RectangleArea.java index 6a36bfc..93deb8b 100644 --- a/solution/src/main/java/com/inuker/solution/RectangleArea.java +++ b/leetcode/solution/src/RectangleArea.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/8. - */ - public class RectangleArea { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { diff --git a/solution/src/main/java/com/inuker/solution/RedundantConnection.java b/leetcode/solution/src/RedundantConnection.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/RedundantConnection.java rename to leetcode/solution/src/RedundantConnection.java index 27799cf..01ee412 100644 --- a/solution/src/main/java/com/inuker/solution/RedundantConnection.java +++ b/leetcode/solution/src/RedundantConnection.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/12/7. - */ - /** * https://leetcode.com/articles/redundant-connection/ */ diff --git a/solution/src/main/java/com/inuker/solution/RegularExpressionMatching.java b/leetcode/solution/src/RegularExpressionMatching.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/RegularExpressionMatching.java rename to leetcode/solution/src/RegularExpressionMatching.java index a7300e7..cbdac88 100644 --- a/solution/src/main/java/com/inuker/solution/RegularExpressionMatching.java +++ b/leetcode/solution/src/RegularExpressionMatching.java @@ -1,8 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/20. - */ /** * 这道题最重要的是no bug,而不是性能 * 要给所有cases cover到 diff --git a/solution/src/main/java/com/inuker/solution/RemoveDuplicateLetters.java b/leetcode/solution/src/RemoveDuplicateLetters.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/RemoveDuplicateLetters.java rename to leetcode/solution/src/RemoveDuplicateLetters.java index 61819b8..831e6a9 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveDuplicateLetters.java +++ b/leetcode/solution/src/RemoveDuplicateLetters.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/1/2. - */ - public class RemoveDuplicateLetters { diff --git a/leetcode/solution/src/RemoveDuplicateList.java b/leetcode/solution/src/RemoveDuplicateList.java new file mode 100644 index 0000000..663d605 --- /dev/null +++ b/leetcode/solution/src/RemoveDuplicateList.java @@ -0,0 +1,57 @@ +public class RemoveDuplicateList { + + /** + * 一个链表,删除相邻且重复的 + * 如 1, 3, 3, 3, 1, 2, 4, 4,只保留1, 1, 2 + */ + public ListNode removeDup(ListNode head) { + ListNode dummy = new ListNode(0), cur = dummy; + + ListNode last = null; + int count = 0; + + for (ListNode p = head; p != null; p = p.next) { + if (last == null || last.val == p.val) { + last = p; + count++; + } else { + if (count == 1) { + cur.next = last; + cur = cur.next; + } + last = p; + count = 1; + } + } + + if (last != null && count == 1) { + cur.next = last; + cur = cur.next; + } + + cur.next = null; + return dummy.next; + } + + // 可在上面的基础上精简 + // count是可以去掉的 + public ListNode removeDup2(ListNode head) { + if (head == null) { + return null; + } + ListNode dummy = new ListNode(0), cur = dummy; + ListNode last = head; + + for (ListNode p = head.next; p != null; p = p.next) { + if (last.val != p.val) { + if (last.next == p) { + cur.next = last; + cur = cur.next; + } + last = p; + } + } + cur.next = (last.next == null ? last : null); + return dummy.next; + } +} diff --git a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArray.java b/leetcode/solution/src/RemoveDuplicatesFromSortedArray.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArray.java rename to leetcode/solution/src/RemoveDuplicatesFromSortedArray.java index 003af37..fa93580 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArray.java +++ b/leetcode/solution/src/RemoveDuplicatesFromSortedArray.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/24. - */ - /** * https://leetcode.com/articles/remove-duplicates-sorted-array/ */ diff --git a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArrayII.java b/leetcode/solution/src/RemoveDuplicatesFromSortedArrayII.java similarity index 79% rename from solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArrayII.java rename to leetcode/solution/src/RemoveDuplicatesFromSortedArrayII.java index 327dc10..11230f5 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedArrayII.java +++ b/leetcode/solution/src/RemoveDuplicatesFromSortedArrayII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/24. - */ - public class RemoveDuplicatesFromSortedArrayII { public int removeDuplicates(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedList.java b/leetcode/solution/src/RemoveDuplicatesFromSortedList.java similarity index 80% rename from solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedList.java rename to leetcode/solution/src/RemoveDuplicatesFromSortedList.java index 2dda9c5..0814495 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedList.java +++ b/leetcode/solution/src/RemoveDuplicatesFromSortedList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/24. - */ - -import com.leetcode.library.ListNode; - /** * https://leetcode.com/articles/remove-duplicates-sorted-list/ */ diff --git a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedListII.java b/leetcode/solution/src/RemoveDuplicatesFromSortedListII.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedListII.java rename to leetcode/solution/src/RemoveDuplicatesFromSortedListII.java index 9f7e0ff..1cea4bc 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveDuplicatesFromSortedListII.java +++ b/leetcode/solution/src/RemoveDuplicatesFromSortedListII.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 16/11/24. - */ - public class RemoveDuplicatesFromSortedListII { public ListNode deleteDuplicates(ListNode head) { diff --git a/solution/src/main/java/com/inuker/solution/RemoveElement.java b/leetcode/solution/src/RemoveElement.java similarity index 78% rename from solution/src/main/java/com/inuker/solution/RemoveElement.java rename to leetcode/solution/src/RemoveElement.java index f96b265..8e8fcef 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveElement.java +++ b/leetcode/solution/src/RemoveElement.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/20. - */ - public class RemoveElement { public int removeElement(int[] nums, int val) { diff --git a/solution/src/main/java/com/inuker/solution/RemoveInvalidParentheses.java b/leetcode/solution/src/RemoveInvalidParentheses.java similarity index 98% rename from solution/src/main/java/com/inuker/solution/RemoveInvalidParentheses.java rename to leetcode/solution/src/RemoveInvalidParentheses.java index ab2703f..3bc3c0e 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveInvalidParentheses.java +++ b/leetcode/solution/src/RemoveInvalidParentheses.java @@ -1,14 +1,8 @@ -package com.inuker.solution; - import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * Created by dingjikerbo on 2016/11/19. - */ - /** * TestCase * "" diff --git a/solution/src/main/java/com/inuker/solution/RemoveKDigits.java b/leetcode/solution/src/RemoveKDigits.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/RemoveKDigits.java rename to leetcode/solution/src/RemoveKDigits.java index a15ab70..9394e25 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveKDigits.java +++ b/leetcode/solution/src/RemoveKDigits.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/20. - */ - /** * TestCase: * "10", 2 diff --git a/solution/src/main/java/com/inuker/solution/RemoveLinkedListElements.java b/leetcode/solution/src/RemoveLinkedListElements.java similarity index 76% rename from solution/src/main/java/com/inuker/solution/RemoveLinkedListElements.java rename to leetcode/solution/src/RemoveLinkedListElements.java index 7faf5d0..cb724ff 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveLinkedListElements.java +++ b/leetcode/solution/src/RemoveLinkedListElements.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 2016/12/20. - */ - public class RemoveLinkedListElements { public ListNode removeElements(ListNode head, int val) { diff --git a/solution/src/main/java/com/inuker/solution/RemoveNthNodeFromEndOfList.java b/leetcode/solution/src/RemoveNthNodeFromEndOfList.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/RemoveNthNodeFromEndOfList.java rename to leetcode/solution/src/RemoveNthNodeFromEndOfList.java index 78e2133..ea2dd02 100644 --- a/solution/src/main/java/com/inuker/solution/RemoveNthNodeFromEndOfList.java +++ b/leetcode/solution/src/RemoveNthNodeFromEndOfList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/20. - */ - -import com.leetcode.library.ListNode; - /** * https://leetcode.com/articles/remove-nth-node-end-list/ */ diff --git a/solution/src/main/java/com/inuker/solution/ReorderList.java b/leetcode/solution/src/ReorderList.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/ReorderList.java rename to leetcode/solution/src/ReorderList.java index 2c81b8e..ed4940e 100644 --- a/solution/src/main/java/com/inuker/solution/ReorderList.java +++ b/leetcode/solution/src/ReorderList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 2017/9/11. - */ - public class ReorderList { public void reorderList(ListNode head) { diff --git a/solution/src/main/java/com/inuker/solution/RepeatedSubstringPattern.java b/leetcode/solution/src/RepeatedSubstringPattern.java similarity index 81% rename from solution/src/main/java/com/inuker/solution/RepeatedSubstringPattern.java rename to leetcode/solution/src/RepeatedSubstringPattern.java index 588309a..4334411 100644 --- a/solution/src/main/java/com/inuker/solution/RepeatedSubstringPattern.java +++ b/leetcode/solution/src/RepeatedSubstringPattern.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/12/9. - */ - public class RepeatedSubstringPattern { /** @@ -11,15 +5,20 @@ public class RepeatedSubstringPattern { */ public boolean repeatedSubstringPattern(String str) { int l = str.length(); + boolean flag = true; for (int i = l / 2; i >= 1; i--) { if (l % i == 0) { int m = l / i; + if (m % 2 == 0 && !flag) { + continue; + } String subS = str.substring(0, i); StringBuilder sb = new StringBuilder(); for (int j = 0; j < m; j++) { sb.append(subS); } if (sb.toString().equals(str)) return true; + flag = false; } } return false; diff --git a/leetcode/solution/src/RestoreIPAddresses.java b/leetcode/solution/src/RestoreIPAddresses.java new file mode 100644 index 0000000..87e7e23 --- /dev/null +++ b/leetcode/solution/src/RestoreIPAddresses.java @@ -0,0 +1,42 @@ +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; + +public class RestoreIPAddresses { + + /** + * 注意,0可以,但是00,01, 010这种是不允许的 + */ + public List restoreIpAddresses(String s) { + List result = new ArrayList<>(); + dfs(s, 0, new LinkedList<>(), result); + return new ArrayList<>(result); + } + + private void dfs(String s, int index, Deque ips, List result) { + if (ips.size() > 4) { + return; + } + if (index >= s.length()) { + if (ips.size() == 4) { + result.add(String.join(".", ips)); + } + return; + } + for (int i = 1; i <= 3 && index + i <= s.length(); i++) { + String t = s.substring(index, index + i); + int k = Integer.parseInt(t); + if (i == 3 && k > 255) { + break; + } + ips.offer(t); + dfs(s, index + i, ips, result); + ips.pollLast(); + + if (k == 0) { + break; + } + } + } +} diff --git a/solution/src/main/java/com/inuker/solution/ReverseBits.java b/leetcode/solution/src/ReverseBits.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/ReverseBits.java rename to leetcode/solution/src/ReverseBits.java index 8927358..5285fbc 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseBits.java +++ b/leetcode/solution/src/ReverseBits.java @@ -1,8 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ public class ReverseBits { diff --git a/solution/src/main/java/com/inuker/solution/ReverseInteger.java b/leetcode/solution/src/ReverseInteger.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/ReverseInteger.java rename to leetcode/solution/src/ReverseInteger.java index f24da04..3c6b2f9 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseInteger.java +++ b/leetcode/solution/src/ReverseInteger.java @@ -1,8 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ public class ReverseInteger { diff --git a/solution/src/main/java/com/inuker/solution/ReverseLinkedList.java b/leetcode/solution/src/ReverseLinkedList.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/ReverseLinkedList.java rename to leetcode/solution/src/ReverseLinkedList.java index eb625cb..e858f36 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseLinkedList.java +++ b/leetcode/solution/src/ReverseLinkedList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -import com.leetcode.library.ListNode; - /** * https://leetcode.com/articles/reverse-linked-list/ */ diff --git a/solution/src/main/java/com/inuker/solution/ReverseLinkedListII.java b/leetcode/solution/src/ReverseLinkedListII.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/ReverseLinkedListII.java rename to leetcode/solution/src/ReverseLinkedListII.java index 96e45dc..fa6e474 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseLinkedListII.java +++ b/leetcode/solution/src/ReverseLinkedListII.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 2017/9/11. - */ - public class ReverseLinkedListII { public ListNode reverseBetween(ListNode head, int m, int n) { diff --git a/solution/src/main/java/com/inuker/solution/ReverseNodesInKGroup.java b/leetcode/solution/src/ReverseNodesInKGroup.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/ReverseNodesInKGroup.java rename to leetcode/solution/src/ReverseNodesInKGroup.java index bf713a9..0f6903a 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseNodesInKGroup.java +++ b/leetcode/solution/src/ReverseNodesInKGroup.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 2016/11/24. - */ - public class ReverseNodesInKGroup { public ListNode reverseKGroup(ListNode head, int k) { diff --git a/solution/src/main/java/com/inuker/solution/ReverseString.java b/leetcode/solution/src/ReverseString.java similarity index 64% rename from solution/src/main/java/com/inuker/solution/ReverseString.java rename to leetcode/solution/src/ReverseString.java index 8d2480a..86bb628 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseString.java +++ b/leetcode/solution/src/ReverseString.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class ReverseString { public String reverseString(String s) { diff --git a/solution/src/main/java/com/inuker/solution/ReverseStringII.java b/leetcode/solution/src/ReverseStringII.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/ReverseStringII.java rename to leetcode/solution/src/ReverseStringII.java index 68f8c25..3c0142c 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseStringII.java +++ b/leetcode/solution/src/ReverseStringII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class ReverseStringII { public String reverseStr(String s, int k) { diff --git a/solution/src/main/java/com/inuker/solution/ReverseVowelsOfaString.java b/leetcode/solution/src/ReverseVowelsOfaString.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/ReverseVowelsOfaString.java rename to leetcode/solution/src/ReverseVowelsOfaString.java index 89f5b71..3ea675c 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseVowelsOfaString.java +++ b/leetcode/solution/src/ReverseVowelsOfaString.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/8/31. - */ - public class ReverseVowelsOfaString { diff --git a/leetcode/solution/src/ReverseWordsInAString.java b/leetcode/solution/src/ReverseWordsInAString.java new file mode 100644 index 0000000..161c63b --- /dev/null +++ b/leetcode/solution/src/ReverseWordsInAString.java @@ -0,0 +1,33 @@ +public class ReverseWordsInAString { + + public static String reverseWords(String s) { + int i, j = 0; + boolean flag = false; + + StringBuilder sb = new StringBuilder(); + + for (i = s.length() - 1; i >= 0; i--) { + if (s.charAt(i) == ' ') { + if (!flag) { + continue; + } else { + flag = false; + sb.append(s.substring(i + 1, j + 1)).append(" "); + } + } else { + if (!flag) { + flag = true; + j = i; + } + } + } + + if (flag) { + sb.append(s.substring(i + 1, j + 1)); + } + if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ' ') { + sb.setLength(sb.length() - 1); + } + return sb.toString(); + } +} diff --git a/solution/src/main/java/com/inuker/solution/ReverseWordsInAStringII.java b/leetcode/solution/src/ReverseWordsInAStringII.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/ReverseWordsInAStringII.java rename to leetcode/solution/src/ReverseWordsInAStringII.java index 432ef7a..fb079d4 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseWordsInAStringII.java +++ b/leetcode/solution/src/ReverseWordsInAStringII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 17/8/12. - */ - public class ReverseWordsInAStringII { public void reverseWords(char[] s) { diff --git a/solution/src/main/java/com/inuker/solution/ReverseWordsInAStringIII.java b/leetcode/solution/src/ReverseWordsInAStringIII.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/ReverseWordsInAStringIII.java rename to leetcode/solution/src/ReverseWordsInAStringIII.java index 7f864cc..5787f79 100644 --- a/solution/src/main/java/com/inuker/solution/ReverseWordsInAStringIII.java +++ b/leetcode/solution/src/ReverseWordsInAStringIII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - /** * https://leetcode.com/articles/reverse-words-in-a-string/ */ diff --git a/solution/src/main/java/com/inuker/solution/RomanToInteger.java b/leetcode/solution/src/RomanToInteger.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/RomanToInteger.java rename to leetcode/solution/src/RomanToInteger.java index 1ce840b..96da591 100644 --- a/solution/src/main/java/com/inuker/solution/RomanToInteger.java +++ b/leetcode/solution/src/RomanToInteger.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class RomanToInteger { public int romanToInt(String s) { diff --git a/solution/src/main/java/com/inuker/solution/RotateArray.java b/leetcode/solution/src/RotateArray.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/RotateArray.java rename to leetcode/solution/src/RotateArray.java index f712b8b..b0deb0a 100644 --- a/solution/src/main/java/com/inuker/solution/RotateArray.java +++ b/leetcode/solution/src/RotateArray.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class RotateArray { public void rotate(int[] nums, int k) { diff --git a/amazon/src/main/java/com/leetcode/amazon/RotateImage.java b/leetcode/solution/src/RotateImage.java similarity index 88% rename from amazon/src/main/java/com/leetcode/amazon/RotateImage.java rename to leetcode/solution/src/RotateImage.java index b24b160..8ce4a29 100644 --- a/amazon/src/main/java/com/leetcode/amazon/RotateImage.java +++ b/leetcode/solution/src/RotateImage.java @@ -1,11 +1,6 @@ -package com.leetcode.amazon; - -/** - * Created by liwentian on 17/8/9. - */ - public class RotateImage { + // 耗时2ms public void rotate(int[][] matrix) { int n = matrix.length; diff --git a/solution/src/main/java/com/inuker/solution/RotateList.java b/leetcode/solution/src/RotateList.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/RotateList.java rename to leetcode/solution/src/RotateList.java index efbbc71..4200872 100644 --- a/solution/src/main/java/com/inuker/solution/RotateList.java +++ b/leetcode/solution/src/RotateList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 2017/9/11. - */ - public class RotateList { public ListNode rotateRight(ListNode head, int n) { diff --git a/solution/src/main/java/com/inuker/solution/SameTree.java b/leetcode/solution/src/SameTree.java similarity index 73% rename from solution/src/main/java/com/inuker/solution/SameTree.java rename to leetcode/solution/src/SameTree.java index 8292901..503fa6e 100644 --- a/solution/src/main/java/com/inuker/solution/SameTree.java +++ b/leetcode/solution/src/SameTree.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/11/28. - */ - public class SameTree { public boolean isSameTree(TreeNode p, TreeNode q) { diff --git a/solution/src/main/java/com/inuker/solution/Search2DMatrix.java b/leetcode/solution/src/Search2DMatrix.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/Search2DMatrix.java rename to leetcode/solution/src/Search2DMatrix.java index 017cbe0..0f424b4 100644 --- a/solution/src/main/java/com/inuker/solution/Search2DMatrix.java +++ b/leetcode/solution/src/Search2DMatrix.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import java.util.Arrays; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - public class Search2DMatrix { // 耗时11ms diff --git a/solution/src/main/java/com/inuker/solution/Search2DMatrixII.java b/leetcode/solution/src/Search2DMatrixII.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/Search2DMatrixII.java rename to leetcode/solution/src/Search2DMatrixII.java index 5757c86..b8e3be7 100644 --- a/solution/src/main/java/com/inuker/solution/Search2DMatrixII.java +++ b/leetcode/solution/src/Search2DMatrixII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - public class Search2DMatrixII { // 耗时14ms diff --git a/leetcode/solution/src/SearchForARange.java b/leetcode/solution/src/SearchForARange.java new file mode 100644 index 0000000..456d22d --- /dev/null +++ b/leetcode/solution/src/SearchForARange.java @@ -0,0 +1,37 @@ +public class SearchForARange { + + /** + * TestCase + * [1], 0 + * [1], 1 + */ + public int[] searchRange(int[] nums, int target) { + if (nums.length == 0) { + return new int[]{-1, -1}; + } + int first = firstHigherEqual(nums, target); + if (first == nums.length || nums[first] != target) { + return new int[] { + -1, -1 + }; + } + return new int[] { + first, + firstHigherEqual(nums, target + 1) - 1 + }; + } + + // 测区间只有1个数或两个数的情况 + private int firstHigherEqual(int[] nums, int target) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) / 2; + if (nums[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } +} diff --git a/solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArray.java b/leetcode/solution/src/SearchInRotatedSortedArray.java similarity index 84% rename from solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArray.java rename to leetcode/solution/src/SearchInRotatedSortedArray.java index aadbc9c..75b7472 100644 --- a/solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArray.java +++ b/leetcode/solution/src/SearchInRotatedSortedArray.java @@ -1,15 +1,9 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class SearchInRotatedSortedArray { + /** - * TestCase - * [1, 2], 1/2/3 - * [2, 1], 2/1/3 - * [1], 1/2 + * 给各种情况考虑到位 + * 关键是判断范围时要先固定单调区间 + * 注意Case[3,1],1 */ public int search(int[] nums, int target) { int left = 0, right = nums.length - 1; diff --git a/solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArrayII.java b/leetcode/solution/src/SearchInRotatedSortedArrayII.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArrayII.java rename to leetcode/solution/src/SearchInRotatedSortedArrayII.java index eec8ff6..5014371 100644 --- a/solution/src/main/java/com/inuker/solution/SearchInRotatedSortedArrayII.java +++ b/leetcode/solution/src/SearchInRotatedSortedArrayII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class SearchInRotatedSortedArrayII { /** * TestCase diff --git a/solution/src/main/java/com/inuker/solution/SearchInsertPosition.java b/leetcode/solution/src/SearchInsertPosition.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/SearchInsertPosition.java rename to leetcode/solution/src/SearchInsertPosition.java index 49ce536..15e2abb 100644 --- a/solution/src/main/java/com/inuker/solution/SearchInsertPosition.java +++ b/leetcode/solution/src/SearchInsertPosition.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 2016/12/17. - */ - public class SearchInsertPosition { public int searchInsert(int[] nums, int target) { diff --git a/solution/src/main/java/com/inuker/solution/SegmentTreeNode.java b/leetcode/solution/src/SegmentTreeNode.java similarity index 74% rename from solution/src/main/java/com/inuker/solution/SegmentTreeNode.java rename to leetcode/solution/src/SegmentTreeNode.java index a132182..15eb3e2 100644 --- a/solution/src/main/java/com/inuker/solution/SegmentTreeNode.java +++ b/leetcode/solution/src/SegmentTreeNode.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/26. - */ - public class SegmentTreeNode { public SegmentTreeNode left, right; diff --git a/solution/src/main/java/com/inuker/solution/SelfCrossing.java b/leetcode/solution/src/SelfCrossing.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/SelfCrossing.java rename to leetcode/solution/src/SelfCrossing.java index 61311f2..ee9c63c 100644 --- a/solution/src/main/java/com/inuker/solution/SelfCrossing.java +++ b/leetcode/solution/src/SelfCrossing.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/21. - */ - /** * 这题非常数学,最好画一下,总的来说可以归纳为三种情况: * 1. 第4条线和第1条线相交 diff --git a/solution/src/main/java/com/inuker/solution/SentenceScreenFitting.java b/leetcode/solution/src/SentenceScreenFitting.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/SentenceScreenFitting.java rename to leetcode/solution/src/SentenceScreenFitting.java index 32db5fc..d4ab086 100644 --- a/solution/src/main/java/com/inuker/solution/SentenceScreenFitting.java +++ b/leetcode/solution/src/SentenceScreenFitting.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/11. - */ - /** * https://discuss.leetcode.com/category/546/sentence-screen-fitting */ diff --git a/solution/src/main/java/com/inuker/solution/SerializeAndDeserializeBST.java b/leetcode/solution/src/SerializeAndDeserializeBST.java similarity index 79% rename from solution/src/main/java/com/inuker/solution/SerializeAndDeserializeBST.java rename to leetcode/solution/src/SerializeAndDeserializeBST.java index acb7ca2..7b0a36e 100644 --- a/solution/src/main/java/com/inuker/solution/SerializeAndDeserializeBST.java +++ b/leetcode/solution/src/SerializeAndDeserializeBST.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 17/8/3. - */ - /** * 本题和#297一样 */ diff --git a/solution/src/main/java/com/inuker/solution/SetMatrixZeroes.java b/leetcode/solution/src/SetMatrixZeroes.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/SetMatrixZeroes.java rename to leetcode/solution/src/SetMatrixZeroes.java index f9c258f..00206d3 100644 --- a/solution/src/main/java/com/inuker/solution/SetMatrixZeroes.java +++ b/leetcode/solution/src/SetMatrixZeroes.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 17/8/12. - */ - public class SetMatrixZeroes { public void setZeroes(int[][] matrix) { diff --git a/solution/src/main/java/com/inuker/solution/ShortestDistanceFromAllBuildings.java b/leetcode/solution/src/ShortestDistanceFromAllBuildings.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/ShortestDistanceFromAllBuildings.java rename to leetcode/solution/src/ShortestDistanceFromAllBuildings.java index ea243b8..b623b0f 100644 --- a/solution/src/main/java/com/inuker/solution/ShortestDistanceFromAllBuildings.java +++ b/leetcode/solution/src/ShortestDistanceFromAllBuildings.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.Queue; -/** - * Created by dingjikerbo on 2016/12/11. - */ - public class ShortestDistanceFromAllBuildings { /** diff --git a/solution/src/main/java/com/inuker/solution/ShortestPalindrome.java b/leetcode/solution/src/ShortestPalindrome.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/ShortestPalindrome.java rename to leetcode/solution/src/ShortestPalindrome.java index 478743f..8ffdb4e 100644 --- a/solution/src/main/java/com/inuker/solution/ShortestPalindrome.java +++ b/leetcode/solution/src/ShortestPalindrome.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - /** * https://segmentfault.com/a/1190000003059361 */ diff --git a/solution/src/main/java/com/inuker/solution/ShortestWordDistance.java b/leetcode/solution/src/ShortestWordDistance.java similarity index 81% rename from solution/src/main/java/com/inuker/solution/ShortestWordDistance.java rename to leetcode/solution/src/ShortestWordDistance.java index 949e380..67bd274 100644 --- a/solution/src/main/java/com/inuker/solution/ShortestWordDistance.java +++ b/leetcode/solution/src/ShortestWordDistance.java @@ -1,12 +1,3 @@ -package com.inuker.solution; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 2016/11/25. - */ - public class ShortestWordDistance { // 耗时3ms diff --git a/solution/src/main/java/com/inuker/solution/ShortestWordDistanceII.java b/leetcode/solution/src/ShortestWordDistanceII.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/ShortestWordDistanceII.java rename to leetcode/solution/src/ShortestWordDistanceII.java index dcf4f78..8ad89d4 100644 --- a/solution/src/main/java/com/inuker/solution/ShortestWordDistanceII.java +++ b/leetcode/solution/src/ShortestWordDistanceII.java @@ -1,15 +1,8 @@ -package com.inuker.solution; - -import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -/** - * Created by liwentian on 2017/9/10. - */ - public class ShortestWordDistanceII { private Map> map; diff --git a/solution/src/main/java/com/inuker/solution/ShortestWordDistanceIII.java b/leetcode/solution/src/ShortestWordDistanceIII.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/ShortestWordDistanceIII.java rename to leetcode/solution/src/ShortestWordDistanceIII.java index cef3649..584d71a 100644 --- a/solution/src/main/java/com/inuker/solution/ShortestWordDistanceIII.java +++ b/leetcode/solution/src/ShortestWordDistanceIII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/10. - */ - public class ShortestWordDistanceIII { public int shortestWordDistance(String[] words, String word1, String word2) { diff --git a/solution/src/main/java/com/inuker/solution/ShuffleAnArray.java b/leetcode/solution/src/ShuffleAnArray.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/ShuffleAnArray.java rename to leetcode/solution/src/ShuffleAnArray.java index c44160a..5bfd258 100644 --- a/solution/src/main/java/com/inuker/solution/ShuffleAnArray.java +++ b/leetcode/solution/src/ShuffleAnArray.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.Random; -/** - * Created by dingjikerbo on 16/12/8. - */ - public class ShuffleAnArray { private int[] mNums; diff --git a/solution/src/main/java/com/inuker/solution/SimplifyPath.java b/leetcode/solution/src/SimplifyPath.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/SimplifyPath.java rename to leetcode/solution/src/SimplifyPath.java index 2faa399..b36448b 100644 --- a/solution/src/main/java/com/inuker/solution/SimplifyPath.java +++ b/leetcode/solution/src/SimplifyPath.java @@ -1,19 +1,10 @@ -package com.inuker.solution; - import java.util.Deque; import java.util.LinkedList; -/** - * Created by dingjikerbo on 16/11/22. - */ - public class SimplifyPath { public String simplifyPath(String path) { String[] ss = path.split("/"); - /** - * 注意这里要用双端队列,因为后面要生成路径需要从前往后 - */ Deque queue = new LinkedList<>(); for (String s : ss) { /** diff --git a/solution/src/main/java/com/inuker/solution/SlidingWindowMaximum.java b/leetcode/solution/src/SlidingWindowMaximum.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/SlidingWindowMaximum.java rename to leetcode/solution/src/SlidingWindowMaximum.java index 8c2c7e9..3524255 100644 --- a/solution/src/main/java/com/inuker/solution/SlidingWindowMaximum.java +++ b/leetcode/solution/src/SlidingWindowMaximum.java @@ -1,14 +1,4 @@ -package com.inuker.solution; - -import java.util.Comparator; -import java.util.Deque; -import java.util.LinkedList; -import java.util.PriorityQueue; -import java.util.Queue; - -/** - * Created by dingjikerbo on 2016/11/16. - */ +import java.util.*; /** * TestCases diff --git a/solution/src/main/java/com/inuker/solution/SlidingWindowMedian.java b/leetcode/solution/src/SlidingWindowMedian.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/SlidingWindowMedian.java rename to leetcode/solution/src/SlidingWindowMedian.java index c555d6a..a9b939c 100644 --- a/solution/src/main/java/com/inuker/solution/SlidingWindowMedian.java +++ b/leetcode/solution/src/SlidingWindowMedian.java @@ -1,12 +1,8 @@ -package com.inuker.solution; - -import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; /** - * Created by liwentian on 2017/9/12. * https://leetcode.com/articles/sliding-window-median/ * 和 #295 Find Median from Data Stream 比较类似 */ diff --git a/solution/src/main/java/com/inuker/solution/SmallestGoodBase.java b/leetcode/solution/src/SmallestGoodBase.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/SmallestGoodBase.java rename to leetcode/solution/src/SmallestGoodBase.java index 8c533e8..257d024 100644 --- a/solution/src/main/java/com/inuker/solution/SmallestGoodBase.java +++ b/leetcode/solution/src/SmallestGoodBase.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.math.BigInteger; -/** - * Created by liwentian on 2017/9/22. - */ - public class SmallestGoodBase { public String smallestGoodBase(String nn) { diff --git a/solution/src/main/java/com/inuker/solution/SmallestRectangleEnclosingBlackPixels.java b/leetcode/solution/src/SmallestRectangleEnclosingBlackPixels.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/SmallestRectangleEnclosingBlackPixels.java rename to leetcode/solution/src/SmallestRectangleEnclosingBlackPixels.java index 1c14288..f71408d 100644 --- a/solution/src/main/java/com/inuker/solution/SmallestRectangleEnclosingBlackPixels.java +++ b/leetcode/solution/src/SmallestRectangleEnclosingBlackPixels.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/22. - */ - public class SmallestRectangleEnclosingBlackPixels { private char[][] image; diff --git a/solution/src/main/java/com/inuker/solution/SortCharactersByFrequency.java b/leetcode/solution/src/SortCharactersByFrequency.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/SortCharactersByFrequency.java rename to leetcode/solution/src/SortCharactersByFrequency.java index d1bc049..858813c 100644 --- a/solution/src/main/java/com/inuker/solution/SortCharactersByFrequency.java +++ b/leetcode/solution/src/SortCharactersByFrequency.java @@ -1,15 +1,4 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; - -/** - * Created by liwentian on 2017/9/22. - */ +import java.util.*; public class SortCharactersByFrequency { diff --git a/solution/src/main/java/com/inuker/solution/SortColors.java b/leetcode/solution/src/SortColors.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/SortColors.java rename to leetcode/solution/src/SortColors.java index e529289..8554544 100644 --- a/solution/src/main/java/com/inuker/solution/SortColors.java +++ b/leetcode/solution/src/SortColors.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/22. - */ - public class SortColors { /** diff --git a/solution/src/main/java/com/inuker/solution/SortList.java b/leetcode/solution/src/SortList.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/SortList.java rename to leetcode/solution/src/SortList.java index c2d035c..bd10a33 100644 --- a/solution/src/main/java/com/inuker/solution/SortList.java +++ b/leetcode/solution/src/SortList.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by liwentian on 2017/9/11. - */ - /** * 这题采用merge sort,可自顶向下或自底向上 * 区别是自顶向下是递归的,需要额外的空间 diff --git a/solution/src/main/java/com/inuker/solution/SparseMatrixMultiplication.java b/leetcode/solution/src/SparseMatrixMultiplication.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/SparseMatrixMultiplication.java rename to leetcode/solution/src/SparseMatrixMultiplication.java index 0df48e5..60ec5fb 100644 --- a/solution/src/main/java/com/inuker/solution/SparseMatrixMultiplication.java +++ b/leetcode/solution/src/SparseMatrixMultiplication.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/19. - */ - /** * 这题有点意思,只要给里层两个for循环交换一下顺序即可 */ diff --git a/solution/src/main/java/com/inuker/solution/SpiralMatrix.java b/leetcode/solution/src/SpiralMatrix.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/SpiralMatrix.java rename to leetcode/solution/src/SpiralMatrix.java index fcc9c6a..3cd7e21 100644 --- a/solution/src/main/java/com/inuker/solution/SpiralMatrix.java +++ b/leetcode/solution/src/SpiralMatrix.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.List; -/** - * Created by liwentian on 2017/9/10. - */ - public class SpiralMatrix { public List spiralOrder(int[][] matrix) { diff --git a/solution/src/main/java/com/inuker/solution/SplitArrayLargestSum.java b/leetcode/solution/src/SplitArrayLargestSum.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/SplitArrayLargestSum.java rename to leetcode/solution/src/SplitArrayLargestSum.java index 9fadf84..b1370a6 100644 --- a/solution/src/main/java/com/inuker/solution/SplitArrayLargestSum.java +++ b/leetcode/solution/src/SplitArrayLargestSum.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/19. - */ - /** * 将数组切成m段,求所有段中最大值的最小值 * 我们倒过来思考,假设这个值为k,则意味着所有段的和都不会超过k,如果我们能确保这种情况下数组能被切成m段,则表明k是候选的值。那怎样确保k是最小值呢? diff --git a/solution/src/main/java/com/inuker/solution/Sqrt.java b/leetcode/solution/src/Sqrt.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/Sqrt.java rename to leetcode/solution/src/Sqrt.java index 13d2c32..e8aff4e 100644 --- a/solution/src/main/java/com/inuker/solution/Sqrt.java +++ b/leetcode/solution/src/Sqrt.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class Sqrt { /** diff --git a/solution/src/main/java/com/inuker/solution/StrStr.java b/leetcode/solution/src/StrStr.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/StrStr.java rename to leetcode/solution/src/StrStr.java index 10bb0ca..4f49e9b 100644 --- a/solution/src/main/java/com/inuker/solution/StrStr.java +++ b/leetcode/solution/src/StrStr.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - public class StrStr { // 这里非常重要的是i<=len1-len2,如果没有这个会超时 diff --git a/leetcode/solution/src/String2Integer.java b/leetcode/solution/src/String2Integer.java new file mode 100644 index 0000000..1b0c12d --- /dev/null +++ b/leetcode/solution/src/String2Integer.java @@ -0,0 +1,47 @@ +/** + * 要求如下: + * 1. 过滤掉前面的空格 + * 2. 考虑正负号 + * 3. 如果溢出则返回上限或下限 + * 4. 解析时遇到非法字符则停止,返回当前结果 + * 5,防御空串 + */ + +/** + * TestCase: "" + */ +public class String2Integer { + + public int myAtoi(String str) { + int i = 0, sign = 1; + for ( ; i < str.length() && str.charAt(i) == ' '; i++); + if (i < str.length()) { + char csign = str.charAt(i); + if (csign == '-') { + sign = -1; + i++; + } else if (csign == '+') { + sign = 1; + i++; + } else if (csign < '0' || csign > '9') { + return 0; + } else {} + } + long number = 0; + for ( ; i < str.length(); i++) { + char c = str.charAt(i); + if (c < '0' || c > '9') { + break; + } + number = number * 10 + (c - '0'); + + if (number * sign > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + if (number * sign < Integer.MIN_VALUE) { + return Integer.MIN_VALUE; + } + } + return (int) (number * sign); + } +} diff --git a/solution/src/main/java/com/inuker/solution/StrobogrammaticNumber.java b/leetcode/solution/src/StrobogrammaticNumber.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/StrobogrammaticNumber.java rename to leetcode/solution/src/StrobogrammaticNumber.java index de3bdd3..5ffcd25 100644 --- a/solution/src/main/java/com/inuker/solution/StrobogrammaticNumber.java +++ b/leetcode/solution/src/StrobogrammaticNumber.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/8/31. - */ - /** * 旋转180度,而不是上下镜像 */ diff --git a/solution/src/main/java/com/inuker/solution/SubarraySumEqualsK.java b/leetcode/solution/src/SubarraySumEqualsK.java similarity index 66% rename from solution/src/main/java/com/inuker/solution/SubarraySumEqualsK.java rename to leetcode/solution/src/SubarraySumEqualsK.java index ed45c26..b8fd099 100644 --- a/solution/src/main/java/com/inuker/solution/SubarraySumEqualsK.java +++ b/leetcode/solution/src/SubarraySumEqualsK.java @@ -1,9 +1,6 @@ -package com.inuker.solution; - import java.util.HashMap; /** - * Created by liwentian on 2017/12/5. * https://leetcode.com/articles/subarray-sum-equals-k/ */ @@ -11,6 +8,7 @@ public class SubarraySumEqualsK { /** * 注意map.put(0,1),即当前数自己也算是一种 + * TestCase [1], 0,即k=0的情况 */ public int subarraySum(int[] nums, int k) { HashMap map = new HashMap<>(); @@ -18,6 +16,8 @@ public int subarraySum(int[] nums, int k) { int count = 0; for (int i = 0, sum = 0; i < nums.length; i++) { sum += nums[i]; + // 以下两句顺序非常重要,因为两个差要至少相差一个数以上,因此不能刚给当前sum放到Map就参与运算 + // 比如k=0,如果刚给sum放到map就参与运算,那么sum-sum=0的情况是非法的 count += map.getOrDefault(sum - k, 0); map.put(sum, map.getOrDefault(sum, 0) + 1); } diff --git a/solution/src/main/java/com/inuker/solution/Subsets.java b/leetcode/solution/src/Subsets.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/Subsets.java rename to leetcode/solution/src/Subsets.java index d9deacf..c26b40f 100644 --- a/solution/src/main/java/com/inuker/solution/Subsets.java +++ b/leetcode/solution/src/Subsets.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/11/22. - */ - /** * 思路是对每个index,有两种情况,要还是不要 * 要注意的是添加结果到result时,要复制一个列表,别直接加list diff --git a/solution/src/main/java/com/inuker/solution/SubsetsII.java b/leetcode/solution/src/SubsetsII.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/SubsetsII.java rename to leetcode/solution/src/SubsetsII.java index 7166f0d..c84b198 100644 --- a/solution/src/main/java/com/inuker/solution/SubsetsII.java +++ b/leetcode/solution/src/SubsetsII.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 2016/11/22. - */ - public class SubsetsII { public List> subsetsWithDup(int[] nums) { diff --git a/solution/src/main/java/com/inuker/solution/SubstringWithConcatenationOfAllWords.java b/leetcode/solution/src/SubstringWithConcatenationOfAllWords.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/SubstringWithConcatenationOfAllWords.java rename to leetcode/solution/src/SubstringWithConcatenationOfAllWords.java index 5dd7fcf..1922d7e 100644 --- a/solution/src/main/java/com/inuker/solution/SubstringWithConcatenationOfAllWords.java +++ b/leetcode/solution/src/SubstringWithConcatenationOfAllWords.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.HashMap; import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 17/5/6. - */ - public class SubstringWithConcatenationOfAllWords { // 118ms,最直接的做法 diff --git a/leetcode/solution/src/SubtreeOfAnotherTree.java b/leetcode/solution/src/SubtreeOfAnotherTree.java new file mode 100644 index 0000000..5096804 --- /dev/null +++ b/leetcode/solution/src/SubtreeOfAnotherTree.java @@ -0,0 +1,19 @@ +public class SubtreeOfAnotherTree { + + /** + * 非递归的办法是拼成字符串,看是否是子串 + */ + public boolean isSubtree(TreeNode s, TreeNode t) { + return isEqual(s, t) || (s != null && (isSubtree(s.left, t) || isSubtree(s.right, t))); + } + + private boolean isEqual(TreeNode s, TreeNode t) { + if (t == null && s == null) { + return true; + } + if (t == null || s == null) { + return false; + } + return s.val == t.val && isEqual(s.left, t.left) && isEqual(s.right, t.right); + } +} diff --git a/solution/src/main/java/com/inuker/solution/SudokuSolver.java b/leetcode/solution/src/SudokuSolver.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/SudokuSolver.java rename to leetcode/solution/src/SudokuSolver.java index cbb9dae..47f73f0 100644 --- a/solution/src/main/java/com/inuker/solution/SudokuSolver.java +++ b/leetcode/solution/src/SudokuSolver.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/5/9. - */ - public class SudokuSolver { public void solveSudoku(char[][] board) { diff --git a/solution/src/main/java/com/inuker/solution/SumOfLeftLeaves.java b/leetcode/solution/src/SumOfLeftLeaves.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/SumOfLeftLeaves.java rename to leetcode/solution/src/SumOfLeftLeaves.java index 9f5f9bb..6893aaf 100644 --- a/solution/src/main/java/com/inuker/solution/SumOfLeftLeaves.java +++ b/leetcode/solution/src/SumOfLeftLeaves.java @@ -1,13 +1,5 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.Stack; -/** - * Created by dingjikerbo on 2016/12/2. - */ - public class SumOfLeftLeaves { public int sumOfLeftLeaves(TreeNode root) { diff --git a/leetcode/solution/src/SumRootToLeafNumbers.java b/leetcode/solution/src/SumRootToLeafNumbers.java new file mode 100644 index 0000000..6ffc49a --- /dev/null +++ b/leetcode/solution/src/SumRootToLeafNumbers.java @@ -0,0 +1,24 @@ +public class SumRootToLeafNumbers { + + public int sumNumbers(TreeNode root) { + int[] res = new int[1]; + helper(root, 0, res); + return res[0]; + } + + private void helper(TreeNode node, int sum, int[] res) { + if (node == null) { + return; + } + + int n = sum * 10 + node.val; + + if (node.left == null && node.right == null) { + res[0] += n; + } else { + helper(node.left, n, res); + helper(node.right, n, res); + } + } + +} diff --git a/solution/src/main/java/com/inuker/solution/SummaryRanges.java b/leetcode/solution/src/SummaryRanges.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/SummaryRanges.java rename to leetcode/solution/src/SummaryRanges.java index e599cf2..649b443 100644 --- a/solution/src/main/java/com/inuker/solution/SummaryRanges.java +++ b/leetcode/solution/src/SummaryRanges.java @@ -1,13 +1,6 @@ -package com.inuker.solution; - -import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -/** - * Created by liwentian on 2017/9/10. - */ - /** * https://leetcode.com/articles/summary-ranges/ * 和 163. Missing Ranges 比较类似 diff --git a/solution/src/main/java/com/inuker/solution/SuperUglyNumber.java b/leetcode/solution/src/SuperUglyNumber.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/SuperUglyNumber.java rename to leetcode/solution/src/SuperUglyNumber.java index 6e1f4e7..1aff921 100644 --- a/solution/src/main/java/com/inuker/solution/SuperUglyNumber.java +++ b/leetcode/solution/src/SuperUglyNumber.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.Arrays; import java.util.PriorityQueue; -/** - * Created by liwentian on 2017/9/22. - */ - public class SuperUglyNumber { public int nthSuperUglyNumber(int n, int[] primes) { diff --git a/solution/src/main/java/com/inuker/solution/SurroundedRegions.java b/leetcode/solution/src/SurroundedRegions.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/SurroundedRegions.java rename to leetcode/solution/src/SurroundedRegions.java index dab0f06..c93252d 100644 --- a/solution/src/main/java/com/inuker/solution/SurroundedRegions.java +++ b/leetcode/solution/src/SurroundedRegions.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.Queue; -/** - * Created by dingjikerbo on 2016/12/11. - */ - public class SurroundedRegions { /** diff --git a/solution/src/main/java/com/inuker/solution/SwapNodesInPairs.java b/leetcode/solution/src/SwapNodesInPairs.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/SwapNodesInPairs.java rename to leetcode/solution/src/SwapNodesInPairs.java index ddc4f21..ca514f8 100644 --- a/solution/src/main/java/com/inuker/solution/SwapNodesInPairs.java +++ b/leetcode/solution/src/SwapNodesInPairs.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -/** - * Created by dingjikerbo on 17/5/6. - */ - public class SwapNodesInPairs { public ListNode swapPairs(ListNode head) { diff --git a/leetcode/solution/src/SymmetricTree.java b/leetcode/solution/src/SymmetricTree.java new file mode 100644 index 0000000..13628a7 --- /dev/null +++ b/leetcode/solution/src/SymmetricTree.java @@ -0,0 +1,118 @@ +import java.util.LinkedList; +import java.util.Queue; +import java.util.Stack; + +public class SymmetricTree { + + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return true; + } + return isSymmetric(root.left, root.right); + } + + private boolean isSymmetric(TreeNode left, TreeNode right) { + if (left == null && right == null) { + return true; + } + if (left == null || right == null) { + return false; + } + return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); + } + + public boolean isSymmetric2(TreeNode root) { + if (root == null) { + return true; + } + Queue queue1 = new LinkedList<>(); + Queue queue2 = new LinkedList<>(); + queue1.offer(root.left); + queue2.offer(root.right); + while (!queue1.isEmpty() && !queue2.isEmpty()) { + TreeNode left = queue1.poll(); + TreeNode right = queue2.poll(); + if (left == null && right == null) { + continue; + } + if (left == null || right == null) { + return false; + } + if (left.val != right.val) { + return false; + } + queue1.offer(left.left); + queue1.offer(left.right); + queue2.offer(right.right); + queue2.offer(right.left); + } + return queue1.isEmpty() && queue2.isEmpty(); + } + + /** + * 基于isSymmetric2,不过只要一个queue就够了 + */ + public boolean isSymmetri3(TreeNode root) { + Queue queue = new LinkedList<>(); + queue.offer(root); + queue.offer(root); + while (!queue.isEmpty()) { + TreeNode left = queue.poll(); + TreeNode right = queue.poll(); + if (left == null && right == null) { + continue; + } + if (left == null || right == null) { + return false; + } + if (left.val != right.val) { + return false; + } + queue.offer(left.left); + queue.offer(right.right); + queue.offer(left.right); + queue.offer(right.left); + } + return true; + } + + /** + * 非递归写法 + */ + public boolean isSymmetric2(TreeNode left, TreeNode right) { + if (left == null && right == null) { + return true; + } + if (left == null || right == null) { + return false; + } + + Stack stack1 = new Stack(); + Stack stack2 = new Stack(); + + while (!stack1.isEmpty() || left != null) { + if (left != null) { + if (right == null) { + return false; + } + if (left.val != right.val) { + return false; + } + stack1.push(left); + stack2.push(right); + left = left.left; + right = right.right; + } else { + if (right != null) { + return false; + } + if (stack2.isEmpty()) { + return false; + } + left = stack1.pop().right; + right = stack2.pop().left; + } + } + return stack2.isEmpty() && right == null; + } +} diff --git a/leetcode/solution/src/TaskScheduler.java b/leetcode/solution/src/TaskScheduler.java new file mode 100644 index 0000000..d1b0a17 --- /dev/null +++ b/leetcode/solution/src/TaskScheduler.java @@ -0,0 +1,23 @@ +import java.util.Arrays; + +public class TaskScheduler { + + /** + * 这题关键是先按频率排序,最高频的优先占座,中间隔着stub,然后依次插次低频的 + * 有两种情况, + * 一种是stub不够用,元素不但给stub替换完了,还要多塞元素,如AAAABBBBCCCCDDDD, n=2,这种情况结果是tasks.length + * 第二种是stub太多了,元素替换不完,中间留了不少空,如AABB, n=3,这种情况结果是(count[25] - 1) * n + count[25] + 24 - i + * 这里(count[25] - 1) * n是插入的stub总数,24 - i是除了count[25]外和count[25]同样频率的数的个数 + */ + public int leastInterval(char[] tasks, int n) { + int[] count = new int[26]; + for (char c : tasks) { + count[c - 'A']++; + } + Arrays.sort(count); + int i = 25; + for (; i >= 0 && count[i] == count[25]; i--) ; + // (count[25] - 1) * n + count[25] + 24 - i = (count[25] - 1) * (n + 1) + 25 - i + return Math.max(tasks.length, (count[25] - 1) * (n + 1) + 25 - i); + } +} diff --git a/solution/src/main/java/com/inuker/solution/TextJustification.java b/leetcode/solution/src/TextJustification.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/TextJustification.java rename to leetcode/solution/src/TextJustification.java index 06aab3a..a8a7bfe 100644 --- a/solution/src/main/java/com/inuker/solution/TextJustification.java +++ b/leetcode/solution/src/TextJustification.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.List; -/** - * Created by dingjikerbo on 16/12/17. - */ - /** * 这题应该多做几遍,没什么技巧,就是考码代码能力 * 类似题目为https://leetcode.com/problems/sentence-screen-fitting/ diff --git a/solution/src/main/java/com/inuker/solution/TheSkylineProblem.java b/leetcode/solution/src/TheSkylineProblem.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/TheSkylineProblem.java rename to leetcode/solution/src/TheSkylineProblem.java index 59316eb..010f722 100644 --- a/solution/src/main/java/com/inuker/solution/TheSkylineProblem.java +++ b/leetcode/solution/src/TheSkylineProblem.java @@ -1,16 +1,4 @@ -package com.inuker.solution; - -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.TreeMap; - -/** - * Created by dingjikerbo on 16/12/17. - */ +import java.util.*; /** * 这题的核心就是求外轮廓,就是所有building覆盖到的区域的最高处构成的轮廓,所以我们关注的核心是当前有效区域的最高处,所以我们要维护 diff --git a/leetcode/solution/src/ThirdMaximumNumber.java b/leetcode/solution/src/ThirdMaximumNumber.java new file mode 100644 index 0000000..6621e58 --- /dev/null +++ b/leetcode/solution/src/ThirdMaximumNumber.java @@ -0,0 +1,27 @@ +/** + * 这题注意边界情况 + */ +public class ThirdMaximumNumber { + + public int thirdMax(int[] nums) { + long first = (long) Integer.MIN_VALUE - 1; + long second = first, third = first; + + for (int i = 0; i < nums.length; i++) { + if (nums[i] == first || nums[i] == second || nums[i] == third) { + continue; + } + if (nums[i] > first) { + third = second; + second = first; + first = nums[i]; + } else if (nums[i] > second) { + third = second; + second = nums[i]; + } else if (nums[i] > third) { + third = nums[i]; + } + } + return (int) (third >= Integer.MIN_VALUE ? third : first); + } +} diff --git a/amazon/src/main/java/com/leetcode/amazon/ThreeSum.java b/leetcode/solution/src/ThreeSum.java similarity index 92% rename from amazon/src/main/java/com/leetcode/amazon/ThreeSum.java rename to leetcode/solution/src/ThreeSum.java index d6c4b9f..b1d1403 100644 --- a/amazon/src/main/java/com/leetcode/amazon/ThreeSum.java +++ b/leetcode/solution/src/ThreeSum.java @@ -1,15 +1,14 @@ -package com.leetcode.amazon; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** - * Created by liwentian on 17/8/11. + * 这题重要的是查重 + * 两重循环都要查重 */ - public class ThreeSum { + // 耗时30ms public List> threeSum(int[] nums) { Arrays.sort(nums); @@ -33,8 +32,6 @@ public List> threeSum(int[] nums) { } } - return result; } - } diff --git a/leetcode/solution/src/ThreeSumClosest.java b/leetcode/solution/src/ThreeSumClosest.java new file mode 100644 index 0000000..7c10b1e --- /dev/null +++ b/leetcode/solution/src/ThreeSumClosest.java @@ -0,0 +1,29 @@ +import java.util.Arrays; + +public class ThreeSumClosest { + + public int threeSumClosest(int[] nums, int target) { + Arrays.sort(nums); + + int min = Integer.MAX_VALUE, res = 0; + for (int k = 0; k < nums.length - 2; k++) { + + for (int i = k + 1, j = nums.length - 1; i < j; ) { + int sum = nums[k] + nums[i] + nums[j]; + if (sum > target) { + j--; + } else if (sum < target) { + i++; + } else { + return sum; + } + int delta = Math.abs(sum - target); + if (delta < min) { + min = delta; + res = sum; + } + } + } + return res; + } +} diff --git a/solution/src/main/java/com/inuker/solution/ThreeSumSmaller.java b/leetcode/solution/src/ThreeSumSmaller.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/ThreeSumSmaller.java rename to leetcode/solution/src/ThreeSumSmaller.java index 96f4670..38eb926 100644 --- a/solution/src/main/java/com/inuker/solution/ThreeSumSmaller.java +++ b/leetcode/solution/src/ThreeSumSmaller.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 16/12/13. - */ - /** * https://leetcode.com/articles/3sum-smaller/ */ diff --git a/solution/src/main/java/com/inuker/solution/TopKFrequentElements.java b/leetcode/solution/src/TopKFrequentElements.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/TopKFrequentElements.java rename to leetcode/solution/src/TopKFrequentElements.java index b762da4..01bb7ab 100644 --- a/solution/src/main/java/com/inuker/solution/TopKFrequentElements.java +++ b/leetcode/solution/src/TopKFrequentElements.java @@ -1,26 +1,41 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.TreeMap; - -/** - * Created by dingjikerbo on 16/12/10. - */ +import java.util.*; public class TopKFrequentElements { /** - * 先统计每个元素次数,再用Priority排序 + * 首选方法,时间复杂度O(n),省去了排序 + * 结尾注意list的size大于k了,要截一部分 */ - // 耗时46ms,最差复杂度O(nlgn),当k< topKFrequent(int[] nums, int k) { + Map map = new HashMap(); + int max = 0; + for (int n : nums) { + int count = map.getOrDefault(n, 0) + 1; + map.put(n, count); + max = Math.max(max, count); + } + List[] lists = new LinkedList[max + 1]; + for (int key : map.keySet()) { + int count = map.get(key); + if (lists[count] == null) { + lists[count] = new LinkedList(); + } + lists[count].add(key); + } + List result = new LinkedList(); + for (int i = lists.length - 1; i >= 0 && result.size() < k; i--) { + if (lists[i] != null) { + result.addAll(lists[i]); + } + } + return result.subList(0, k); + } + + /** + * 先统计每个元素次数,再用Priority排序 + */ + // 耗时46ms,最差复杂度O(nlgk),当k< topKFrequent2(int[] nums, int k) { HashMap map = new HashMap<>(); for (int n : nums) { map.put(n, map.getOrDefault(n, 0) + 1); @@ -44,7 +59,7 @@ public int compare(Integer o1, Integer o2) { return list; } - public List topKFrequent2(int[] nums, int k) { + public List topKFrequent3(int[] nums, int k) { Map map = new HashMap<>(); for(int n: nums){ map.put(n, map.getOrDefault(n,0)+1); @@ -66,31 +81,4 @@ public List topKFrequent2(int[] nums, int k) { } return res; } - - // 耗时23ms,时间复杂度O(n),空间复杂度O(n) - // 这里有个问题,result的size可能大于k了 - public List topKFrequent3(int[] nums, int k) { - Map map = new HashMap(); - int max = 0; - for (int n : nums) { - int count = map.getOrDefault(n, 0) + 1; - map.put(n, count); - max = Math.max(max, count); - } - List[] lists = new LinkedList[max + 1]; - for (int key : map.keySet()) { - int count = map.get(key); - if (lists[count] == null) { - lists[count] = new LinkedList(); - } - lists[count].add(key); - } - List result = new LinkedList(); - for (int i = lists.length - 1; i >= 0 && result.size() < k; i--) { - if (lists[i] != null) { - result.addAll(lists[i]); - } - } - return result.subList(0, k); - } } diff --git a/solution/src/main/java/com/inuker/solution/TotalHammingDistance.java b/leetcode/solution/src/TotalHammingDistance.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/TotalHammingDistance.java rename to leetcode/solution/src/TotalHammingDistance.java index e49e685..390fa78 100644 --- a/solution/src/main/java/com/inuker/solution/TotalHammingDistance.java +++ b/leetcode/solution/src/TotalHammingDistance.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/1/7. - */ - public class TotalHammingDistance { /** * 思路是依次遍历每个数字的第i位,统计出为1的有m个,为0的有n个,则在这一位上 diff --git a/leetcode/solution/src/TrappingRainWater.java b/leetcode/solution/src/TrappingRainWater.java new file mode 100644 index 0000000..85e6a53 --- /dev/null +++ b/leetcode/solution/src/TrappingRainWater.java @@ -0,0 +1,23 @@ +/** + * 核心思路就是对于每根柱子,找到其左边最高的柱子和右边最高的柱子,构成一个桶,形成一个水平面,然后对该柱子形成的高度差就是能装的水 + */ +public class TrappingRainWater { + + // 耗时24ms + public int trap(int[] height) { + int[] left = new int[height.length]; + int[] right = new int[height.length]; + + for (int i = 1; i < height.length; i++) { + left[i] = Math.max(left[i - 1], height[i - 1]); + } + for (int i = height.length - 2; i >= 0; i--) { + right[i] = Math.max(right[i + 1], height[i + 1]); + } + int rain = 0; + for (int i = 1; i < height.length - 1; i++) { + rain += Math.max(0, Math.min(left[i], right[i]) - height[i]); + } + return rain; + } +} diff --git a/solution/src/main/java/com/inuker/solution/TrappingRainWaterII.java b/leetcode/solution/src/TrappingRainWaterII.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/TrappingRainWaterII.java rename to leetcode/solution/src/TrappingRainWaterII.java index e6409a9..42eee53 100644 --- a/solution/src/main/java/com/inuker/solution/TrappingRainWaterII.java +++ b/leetcode/solution/src/TrappingRainWaterII.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; -/** - * Created by dingjikerbo on 2016/11/16. - */ - /** * 思路是从外围开始,选择最短的柱子,以该柱子为标准,计算其四周的柱子所能容纳的水,并且更新四周柱子的高度,并加到小堆中。 * 为什么这样呢?一个柱子所能蓄的水和该柱子相邻的四根柱子有关,所以我们从边界开始,不断向中间靠拢,每次都取队列中最短的那根柱子计算 diff --git a/solution/src/main/java/com/inuker/solution/Trie.java b/leetcode/solution/src/Trie.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/Trie.java rename to leetcode/solution/src/Trie.java index afb17dd..6461993 100644 --- a/solution/src/main/java/com/inuker/solution/Trie.java +++ b/leetcode/solution/src/Trie.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/23. - */ - /** * https://leetcode.com/articles/implement-trie-prefix-tree/ */ diff --git a/leetcode/solution/src/TrimABinarySearchTree.java b/leetcode/solution/src/TrimABinarySearchTree.java new file mode 100644 index 0000000..f501905 --- /dev/null +++ b/leetcode/solution/src/TrimABinarySearchTree.java @@ -0,0 +1,16 @@ +public class TrimABinarySearchTree { + + public TreeNode trimBST(TreeNode root, int L, int R) { + if (root == null) { + return root; + } else if (root.val > R) { + return trimBST(root.left, L, R); + } else if (root.val < L) { + return trimBST(root.right, L, R); + } else { + root.left = trimBST(root.left, L, R); + root.right = trimBST(root.right, L, R); + return root; + } + } +} diff --git a/leetcode/solution/src/TwoSum.java b/leetcode/solution/src/TwoSum.java new file mode 100644 index 0000000..44ff8e6 --- /dev/null +++ b/leetcode/solution/src/TwoSum.java @@ -0,0 +1,19 @@ +import java.util.HashMap; + +public class TwoSum { + + /** + * one pass + * 要注意map.put要放在for末尾,对于case[3, 3], target=6的情况,如果放在开头会覆盖第一个3 + */ + public int[] twoSum2(int[] nums, int target) { + HashMap map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + if (map.containsKey(target - nums[i])) { + return new int[] {map.get(target - nums[i]), i}; + } + map.put(nums[i], i); + } + return null; + } +} diff --git a/solution/src/main/java/com/inuker/solution/TwoSumII.java b/leetcode/solution/src/TwoSumII.java similarity index 87% rename from solution/src/main/java/com/inuker/solution/TwoSumII.java rename to leetcode/solution/src/TwoSumII.java index 35bd68c..a950ae5 100644 --- a/solution/src/main/java/com/inuker/solution/TwoSumII.java +++ b/leetcode/solution/src/TwoSumII.java @@ -1,7 +1,4 @@ -package com.inuker.solution; - /** - * Created by dingjikerbo on 2016/11/17. * https://leetcode.com/articles/two-sum-ii-input-array-sorted/ */ diff --git a/solution/src/main/java/com/inuker/solution/TwoSumIII.java b/leetcode/solution/src/TwoSumIII.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/TwoSumIII.java rename to leetcode/solution/src/TwoSumIII.java index b39b74f..d385382 100644 --- a/solution/src/main/java/com/inuker/solution/TwoSumIII.java +++ b/leetcode/solution/src/TwoSumIII.java @@ -1,13 +1,8 @@ -package com.inuker.solution; - import java.util.HashMap; -/** - * Created by dingjikerbo on 2016/12/15. - */ - /** * 支持相同数存在 + * 如果需要find快,则每次add时都要遍历map中所有key,更新sum的map */ public class TwoSumIII { diff --git a/solution/src/main/java/com/inuker/solution/TwoSumIV.java b/leetcode/solution/src/TwoSumIV.java similarity index 52% rename from solution/src/main/java/com/inuker/solution/TwoSumIV.java rename to leetcode/solution/src/TwoSumIV.java index 5a31fa7..70651e4 100644 --- a/solution/src/main/java/com/inuker/solution/TwoSumIV.java +++ b/leetcode/solution/src/TwoSumIV.java @@ -1,20 +1,15 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; -/** - * Created by liwentian on 2017/9/10. - */ - /** * https://leetcode.com/articles/two-sum-iv/ */ public class TwoSumIV { + /** + * 先遍历一遍,生成一个递增序列,再从两端往中间检查 + */ public boolean findTarget(TreeNode root, int k) { List nums = new ArrayList<>(); inorder(root, nums); @@ -32,4 +27,23 @@ public void inorder(TreeNode root, List nums) { nums.add(root.val); inorder(root.right, nums); } + + /** + * 更简单一点,遍历树,用一个hashset记录每个元素 + * 时间空间都是O(n) + */ + public boolean findTarget2(TreeNode root, int k) { + return visit(root, k, new HashSet<>()); + } + + private boolean visit(TreeNode root, int k, HashSet set) { + if (root == null) { + return false; + } + if (set.contains(k - root.val)) { + return true; + } + set.add(root.val); + return visit(root.left, k, set) || visit(root.right, k, set); + } } diff --git a/solution/src/main/java/com/inuker/solution/UTFValidation.java b/leetcode/solution/src/UTFValidation.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/UTFValidation.java rename to leetcode/solution/src/UTFValidation.java index 9b627b0..f15c404 100644 --- a/solution/src/main/java/com/inuker/solution/UTFValidation.java +++ b/leetcode/solution/src/UTFValidation.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/8/31. - */ - public class UTFValidation { public boolean validUtf8(int[] data) { diff --git a/solution/src/main/java/com/inuker/solution/UglyNumber.java b/leetcode/solution/src/UglyNumber.java similarity index 78% rename from solution/src/main/java/com/inuker/solution/UglyNumber.java rename to leetcode/solution/src/UglyNumber.java index 8fa54c2..5d8b070 100644 --- a/solution/src/main/java/com/inuker/solution/UglyNumber.java +++ b/leetcode/solution/src/UglyNumber.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ - public class UglyNumber { public boolean isUgly(int num) { diff --git a/solution/src/main/java/com/inuker/solution/UglyNumberII.java b/leetcode/solution/src/UglyNumberII.java similarity index 86% rename from solution/src/main/java/com/inuker/solution/UglyNumberII.java rename to leetcode/solution/src/UglyNumberII.java index 1846e08..82ed5e1 100644 --- a/solution/src/main/java/com/inuker/solution/UglyNumberII.java +++ b/leetcode/solution/src/UglyNumberII.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/12/10. - */ - public class UglyNumberII { public int nthUglyNumber(int n) { diff --git a/solution/src/main/java/com/inuker/solution/UniqueBinarySearchTrees.java b/leetcode/solution/src/UniqueBinarySearchTrees.java similarity index 83% rename from solution/src/main/java/com/inuker/solution/UniqueBinarySearchTrees.java rename to leetcode/solution/src/UniqueBinarySearchTrees.java index 0b5c731..69232b8 100644 --- a/solution/src/main/java/com/inuker/solution/UniqueBinarySearchTrees.java +++ b/leetcode/solution/src/UniqueBinarySearchTrees.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/28. - */ - /** * 动态规划,依次建立1,2,3,...颗节点能有多少种树构造的dp */ diff --git a/leetcode/solution/src/UniqueBinarySearchTreesII.java b/leetcode/solution/src/UniqueBinarySearchTreesII.java new file mode 100644 index 0000000..83bbb2f --- /dev/null +++ b/leetcode/solution/src/UniqueBinarySearchTreesII.java @@ -0,0 +1,119 @@ +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * Dp的解法可以参考https://discuss.leetcode.com/topic/2940/java-solution-with-dp + */ +public class UniqueBinarySearchTreesII { + + public List generateTrees(int n) { + if (n < 1) { + return Collections.EMPTY_LIST; + } + return generateTrees(1, n); + } + + // 从start到end之间取一个数作为root,左边构成left,右边构成right + private List generateTrees(int start, int end) { + List list = new LinkedList(); + if (start > end) { + list.add(null); + return list; + } + for (int i = start; i <= end; i++) { + List lefts = generateTrees(start, i - 1); + List rights = generateTrees(i + 1, end); + for (TreeNode left : lefts) { + for (TreeNode right : rights) { + TreeNode root = new TreeNode(i); + root.left = left; + root.right = right; + list.add(root); + } + + } + } + return list; + } + + /** + * 这里面明显有重复计算的部分,可缓存[1,n]的结果加速,时间降到2ms + */ + /* + public List generateTrees(int start, int end, List[] map) { + List result = new LinkedList<>(); + if (start > end) { + result.add(null); + return result; + } + if (start == 1 && map[end] != null) { + return map[end]; + } + for (int i = start; i <= end; i++) { + List lefts = generateTrees(start, i - 1, map); + List rights = generateTrees(i + 1, end, map); + for (TreeNode left : lefts) { + for (TreeNode right : rights) { + TreeNode root = new TreeNode(i); + root.left = left; + root.right = right; + result.add(root); + } + } + } + if (start == 1) { + map[end] = result; + } + return result; + } + + public List generateTrees(int n) { + if (n < 1) { + return Collections.EMPTY_LIST; + } + List[] map = new LinkedList[n + 1]; + return generateTrees(1, n, map); + }*/ + + /** + * 可考虑迭代的DP写法 + */ + /* + public List generateTrees(int n) { + if (n == 0) { + return Collections.EMPTY_LIST; + } + + List[] map = new LinkedList[n + 1]; + map[0] = new LinkedList<>(); + map[0].add(null); + + for (int i = 1; i <= n; i++) { + map[i] = new LinkedList<>(); + for (int j = 1; j <= i; j++) { + for (TreeNode left : map[j - 1]) { + for (TreeNode right : map[i - j]) { + TreeNode root = new TreeNode(j); + root.left = left; + root.right = clone(right, j); + map[i].add(root); + } + } + } + } + + return map[n]; + } + + public TreeNode clone(TreeNode node, int offset) { + if (node == null) { + return null; + } + TreeNode root = new TreeNode(node.val + offset); + root.left = clone(node.left, offset); + root.right = clone(node.right, offset); + return root; + } + */ +} diff --git a/leetcode/solution/src/UniqueEmailAddresses.java b/leetcode/solution/src/UniqueEmailAddresses.java new file mode 100644 index 0000000..ca967e3 --- /dev/null +++ b/leetcode/solution/src/UniqueEmailAddresses.java @@ -0,0 +1,25 @@ +import java.util.HashSet; +import java.util.Set; + +public class UniqueEmailAddresses { + + public int numUniqueEmails(String[] emails) { + Set set = new HashSet<>(); + for (String email : emails) { + set.add(make(email)); + } + return set.size(); + } + + private String make(String email) { + int index = email.indexOf("@"); + String host = email.substring(index + 1); + String name = email.substring(0, index); + int index2 = name.indexOf("+"); + if (index2 >= 0) { + name = name.substring(0, index2); + } + name = name.replaceAll(".", ""); + return name + "@" + host; + } +} diff --git a/solution/src/main/java/com/inuker/solution/ValidAnagram.java b/leetcode/solution/src/ValidAnagram.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/ValidAnagram.java rename to leetcode/solution/src/ValidAnagram.java index e1e33c0..1ef239f 100644 --- a/solution/src/main/java/com/inuker/solution/ValidAnagram.java +++ b/leetcode/solution/src/ValidAnagram.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 2016/11/17. - */ - /** * https://leetcode.com/articles/valid-anagram/ */ diff --git a/solution/src/main/java/com/inuker/solution/ValidPalindrome.java b/leetcode/solution/src/ValidPalindrome.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/ValidPalindrome.java rename to leetcode/solution/src/ValidPalindrome.java index 0e21fec..6d7d12d 100644 --- a/solution/src/main/java/com/inuker/solution/ValidPalindrome.java +++ b/leetcode/solution/src/ValidPalindrome.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/22. - */ - public class ValidPalindrome { /** diff --git a/leetcode/solution/src/ValidParentheses.java b/leetcode/solution/src/ValidParentheses.java new file mode 100644 index 0000000..86ef6f5 --- /dev/null +++ b/leetcode/solution/src/ValidParentheses.java @@ -0,0 +1,36 @@ +/** + * 要注意栈判空 + */ +public class ValidParentheses { + + // 耗时4ms + public boolean isValid(String s) { + int[] stack = new int[s.length()]; + int index = 0; + for (int i = 0; i < s.length(); i++) { + switch (s.charAt(i)) { + case '(': + case '[': + case '{': + stack[index++] = i; + break; + case ')': + if (index == 0 || s.charAt(stack[--index]) != '(') { + return false; + } + break; + case ']': + if (index == 0 || s.charAt(stack[--index]) != '[') { + return false; + } + break; + case '}': + if (index == 0 || s.charAt(stack[--index]) != '{') { + return false; + } + break; + } + } + return index == 0; + } +} diff --git a/solution/src/main/java/com/inuker/solution/ValidPerfectSquare.java b/leetcode/solution/src/ValidPerfectSquare.java similarity index 91% rename from solution/src/main/java/com/inuker/solution/ValidPerfectSquare.java rename to leetcode/solution/src/ValidPerfectSquare.java index 326eedf..4da4dbc 100644 --- a/solution/src/main/java/com/inuker/solution/ValidPerfectSquare.java +++ b/leetcode/solution/src/ValidPerfectSquare.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/22. - */ - public class ValidPerfectSquare { public boolean isPerfectSquare(int num) { diff --git a/solution/src/main/java/com/inuker/solution/ValidSudoku.java b/leetcode/solution/src/ValidSudoku.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/ValidSudoku.java rename to leetcode/solution/src/ValidSudoku.java index 4fb6008..1a6e188 100644 --- a/solution/src/main/java/com/inuker/solution/ValidSudoku.java +++ b/leetcode/solution/src/ValidSudoku.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 17/5/9. - */ - public class ValidSudoku { public boolean isValidSudoku(char[][] board) { diff --git a/solution/src/main/java/com/inuker/solution/ValidWordAbbr.java b/leetcode/solution/src/ValidWordAbbr.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/ValidWordAbbr.java rename to leetcode/solution/src/ValidWordAbbr.java index 6f87894..b1819d0 100644 --- a/solution/src/main/java/com/inuker/solution/ValidWordAbbr.java +++ b/leetcode/solution/src/ValidWordAbbr.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.HashMap; import java.util.HashSet; import java.util.Set; -/** - * Created by dingjikerbo on 16/12/4. - */ - /** * 参考https://leetcode.com/articles/unique-word-abbreviation/ */ diff --git a/solution/src/main/java/com/inuker/solution/ValidWordAbbreviation.java b/leetcode/solution/src/ValidWordAbbreviation.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/ValidWordAbbreviation.java rename to leetcode/solution/src/ValidWordAbbreviation.java index 3f958b5..4b064d9 100644 --- a/solution/src/main/java/com/inuker/solution/ValidWordAbbreviation.java +++ b/leetcode/solution/src/ValidWordAbbreviation.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 2017/9/6. - */ - public class ValidWordAbbreviation { public boolean validWordAbbreviation(String word, String abbr) { diff --git a/solution/src/main/java/com/inuker/solution/ValidWordSquare.java b/leetcode/solution/src/ValidWordSquare.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/ValidWordSquare.java rename to leetcode/solution/src/ValidWordSquare.java index d40e71d..60de6c8 100644 --- a/solution/src/main/java/com/inuker/solution/ValidWordSquare.java +++ b/leetcode/solution/src/ValidWordSquare.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.List; -/** - * Created by dingjikerbo on 17/1/2. - */ - /** * 这题还挺容易错 */ diff --git a/solution/src/main/java/com/inuker/solution/ValidateBinarySearchTree.java b/leetcode/solution/src/ValidateBinarySearchTree.java similarity index 85% rename from solution/src/main/java/com/inuker/solution/ValidateBinarySearchTree.java rename to leetcode/solution/src/ValidateBinarySearchTree.java index 0c6d37c..1c8c077 100644 --- a/solution/src/main/java/com/inuker/solution/ValidateBinarySearchTree.java +++ b/leetcode/solution/src/ValidateBinarySearchTree.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - public class ValidateBinarySearchTree { // 耗时1ms diff --git a/solution/src/main/java/com/inuker/solution/Vector2D.java b/leetcode/solution/src/Vector2D.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/Vector2D.java rename to leetcode/solution/src/Vector2D.java index 4e0aa03..8c418fe 100644 --- a/solution/src/main/java/com/inuker/solution/Vector2D.java +++ b/leetcode/solution/src/Vector2D.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.Iterator; import java.util.List; -/** - * Created by dingjikerbo on 2016/12/15. - */ - public class Vector2D implements Iterator { private Iterator> mIterator; diff --git a/solution/src/main/java/com/inuker/solution/VerifyPreorderSequenceInBinarySearchTree.java b/leetcode/solution/src/VerifyPreorderSequenceInBinarySearchTree.java similarity index 90% rename from solution/src/main/java/com/inuker/solution/VerifyPreorderSequenceInBinarySearchTree.java rename to leetcode/solution/src/VerifyPreorderSequenceInBinarySearchTree.java index da9ed7e..bcd4fed 100644 --- a/solution/src/main/java/com/inuker/solution/VerifyPreorderSequenceInBinarySearchTree.java +++ b/leetcode/solution/src/VerifyPreorderSequenceInBinarySearchTree.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/2. - */ - public class VerifyPreorderSequenceInBinarySearchTree { public boolean verifyPreorder(int[] preorder) { diff --git a/solution/src/main/java/com/inuker/solution/WallsAndGates.java b/leetcode/solution/src/WallsAndGates.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/WallsAndGates.java rename to leetcode/solution/src/WallsAndGates.java index 9bd8a27..ca0fe5d 100644 --- a/solution/src/main/java/com/inuker/solution/WallsAndGates.java +++ b/leetcode/solution/src/WallsAndGates.java @@ -1,12 +1,6 @@ -package com.inuker.solution; - import java.util.LinkedList; import java.util.Queue; -/** - * Created by dingjikerbo on 16/11/25. - */ - /** * https://leetcode.com/articles/walls-and-gates/ */ diff --git a/solution/src/main/java/com/inuker/solution/WiggleSort.java b/leetcode/solution/src/WiggleSort.java similarity index 82% rename from solution/src/main/java/com/inuker/solution/WiggleSort.java rename to leetcode/solution/src/WiggleSort.java index f0a8ccf..84b21d2 100644 --- a/solution/src/main/java/com/inuker/solution/WiggleSort.java +++ b/leetcode/solution/src/WiggleSort.java @@ -1,11 +1,3 @@ -package com.inuker.solution; - -import java.util.Arrays; - -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * https://leetcode.com/articles/wiggle-sort/ */ diff --git a/solution/src/main/java/com/inuker/solution/WiggleSortII.java b/leetcode/solution/src/WiggleSortII.java similarity index 97% rename from solution/src/main/java/com/inuker/solution/WiggleSortII.java rename to leetcode/solution/src/WiggleSortII.java index 7180c75..37eb4da 100644 --- a/solution/src/main/java/com/inuker/solution/WiggleSortII.java +++ b/leetcode/solution/src/WiggleSortII.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * TestCase * [1,2,2,1,2,1,1,1,1,2,2,2] diff --git a/solution/src/main/java/com/inuker/solution/WildcardMatching.java b/leetcode/solution/src/WildcardMatching.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/WildcardMatching.java rename to leetcode/solution/src/WildcardMatching.java index 1fdba82..3895bd5 100644 --- a/solution/src/main/java/com/inuker/solution/WildcardMatching.java +++ b/leetcode/solution/src/WildcardMatching.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/20. - */ - public class WildcardMatching { // 这道题关键是遇到"*"的处理以及后面匹配失败时的回溯 diff --git a/google/src/main/java/com/leetcode/google/WordBreak.java b/leetcode/solution/src/WordBreak.java similarity index 85% rename from google/src/main/java/com/leetcode/google/WordBreak.java rename to leetcode/solution/src/WordBreak.java index c8a43f5..4c260d9 100644 --- a/google/src/main/java/com/leetcode/google/WordBreak.java +++ b/leetcode/solution/src/WordBreak.java @@ -1,14 +1,12 @@ -package com.leetcode.google; - -import java.util.HashSet; import java.util.List; /** - * Created by liwentian on 2017/9/3. + * https://leetcode.com/articles/word-break/ */ - public class WordBreak { + // 耗时3ms + // 典型的DP问题 public boolean wordBreak(String s, List wordDict) { int n = s.length(); diff --git a/solution/src/main/java/com/inuker/solution/WordBreakII.java b/leetcode/solution/src/WordBreakII.java similarity index 88% rename from solution/src/main/java/com/inuker/solution/WordBreakII.java rename to leetcode/solution/src/WordBreakII.java index 75f76ca..d3e77f5 100644 --- a/solution/src/main/java/com/inuker/solution/WordBreakII.java +++ b/leetcode/solution/src/WordBreakII.java @@ -1,17 +1,4 @@ -package com.inuker.solution; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Created by dingjikerbo on 2016/11/17. - */ +import java.util.*; /** * 这题是个典型的DFS,不过为了加速用了缓存避免重复计算 diff --git a/solution/src/main/java/com/inuker/solution/WordDictionary.java b/leetcode/solution/src/WordDictionary.java similarity index 95% rename from solution/src/main/java/com/inuker/solution/WordDictionary.java rename to leetcode/solution/src/WordDictionary.java index 41a0235..8e3485a 100644 --- a/solution/src/main/java/com/inuker/solution/WordDictionary.java +++ b/leetcode/solution/src/WordDictionary.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/22. - */ - public class WordDictionary { private class Trie { diff --git a/solution/src/main/java/com/inuker/solution/WordLadder.java b/leetcode/solution/src/WordLadder.java similarity index 73% rename from solution/src/main/java/com/inuker/solution/WordLadder.java rename to leetcode/solution/src/WordLadder.java index 7e79ae5..ac66c6b 100644 --- a/solution/src/main/java/com/inuker/solution/WordLadder.java +++ b/leetcode/solution/src/WordLadder.java @@ -1,14 +1,8 @@ -package com.inuker.solution; - import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; -/** - * Created by dingjikerbo on 2016/11/17. - */ - /** * TestCases "a", "c", ["a", "b", "c"] @@ -21,45 +15,46 @@ public class WordLadder { /** * 要注意添加节点时要给单词从dict中删掉 */ - // 常规的BFS,耗时141ms + // 常规的BFS,耗时64ms public int ladderLength(String beginWord, String endWord, Set wordList) { - wordList.remove(beginWord); - wordList.add(endWord); - + HashSet words = new HashSet<>(wordList); Queue queue = new LinkedList<>(); - Queue next = new LinkedList<>(); - queue.add(beginWord); + queue.offer(beginWord); - int ladder = 1; + Queue next = new LinkedList<>(); + int length = 1; while (!queue.isEmpty()) { - String word = queue.poll(); - - StringBuilder sb = new StringBuilder(word); - for (int i = 0; i < word.length(); i++) { - char c = word.charAt(i); - for (int j = 0; j < 26; j++) { - if (j + 'a' == c) { - continue; - } - sb.setCharAt(i, (char) (j + 'a')); - String s = sb.toString(); + String s = queue.poll(); - if (s.equals(endWord)) { - return ladder + 1; - } + if (s.equals(endWord)) { + return length; + } + + if (!words.isEmpty()) { + StringBuilder sb = new StringBuilder(s); + for (int i = 0; i < s.length(); i++) { + for (char c = 'a'; c <= 'z'; c++) { + if (c == s.charAt(i)) { + continue; + } - if (wordList.remove(s)) { - next.add(s); + sb.setCharAt(i, c); + String st = sb.toString(); + + if (words.contains(st)) { + next.offer(st); + words.remove(st); + } } + sb.setCharAt(i, s.charAt(i)); } - sb.setCharAt(i, c); } if (queue.isEmpty()) { queue.addAll(next); next.clear(); - ladder++; + length++; } } diff --git a/solution/src/main/java/com/inuker/solution/WordLadderII.java b/leetcode/solution/src/WordLadderII.java similarity index 94% rename from solution/src/main/java/com/inuker/solution/WordLadderII.java rename to leetcode/solution/src/WordLadderII.java index 9b190f9..e9c9c5a 100644 --- a/solution/src/main/java/com/inuker/solution/WordLadderII.java +++ b/leetcode/solution/src/WordLadderII.java @@ -1,14 +1,4 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * Created by dingjikerbo on 2016/11/17. - */ +import java.util.*; /** * TestCases diff --git a/solution/src/main/java/com/inuker/solution/WordSearch.java b/leetcode/solution/src/WordSearch.java similarity index 93% rename from solution/src/main/java/com/inuker/solution/WordSearch.java rename to leetcode/solution/src/WordSearch.java index 62ff807..2d751ae 100644 --- a/solution/src/main/java/com/inuker/solution/WordSearch.java +++ b/leetcode/solution/src/WordSearch.java @@ -1,9 +1,3 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/22. - */ - public class WordSearch { // 耗时9ms diff --git a/solution/src/main/java/com/inuker/solution/WordSearchII.java b/leetcode/solution/src/WordSearchII.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/WordSearchII.java rename to leetcode/solution/src/WordSearchII.java index ed6cac1..42a8d70 100644 --- a/solution/src/main/java/com/inuker/solution/WordSearchII.java +++ b/leetcode/solution/src/WordSearchII.java @@ -1,14 +1,8 @@ -package com.inuker.solution; - import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; -/** - * Created by dingjikerbo on 16/11/22. - */ - public class WordSearchII { private class Trie { diff --git a/solution/src/main/java/com/inuker/solution/WordSquares.java b/leetcode/solution/src/WordSquares.java similarity index 89% rename from solution/src/main/java/com/inuker/solution/WordSquares.java rename to leetcode/solution/src/WordSquares.java index 53aff23..0d428b8 100644 --- a/solution/src/main/java/com/inuker/solution/WordSquares.java +++ b/leetcode/solution/src/WordSquares.java @@ -1,15 +1,4 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Created by dingjikerbo on 17/1/2. - */ +import java.util.*; /** * https://discuss.leetcode.com/topic/63516/explained-my-java-solution-using-trie-126ms-16-16 diff --git a/solution/src/main/java/com/inuker/solution/ZigZagConversion.java b/leetcode/solution/src/ZigZagConversion.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/ZigZagConversion.java rename to leetcode/solution/src/ZigZagConversion.java index 0b1a43a..8c13ae8 100644 --- a/solution/src/main/java/com/inuker/solution/ZigZagConversion.java +++ b/leetcode/solution/src/ZigZagConversion.java @@ -1,11 +1,5 @@ -package com.inuker.solution; - import java.util.Arrays; -/** - * Created by dingjikerbo on 17/4/29. - */ - /** * 这道题一定要注意numRows为1的情况 */ diff --git a/solution/src/main/java/com/inuker/solution/ZigzagIterator.java b/leetcode/solution/src/ZigzagIterator.java similarity index 92% rename from solution/src/main/java/com/inuker/solution/ZigzagIterator.java rename to leetcode/solution/src/ZigzagIterator.java index 1e517fc..f5224f1 100644 --- a/solution/src/main/java/com/inuker/solution/ZigzagIterator.java +++ b/leetcode/solution/src/ZigzagIterator.java @@ -1,13 +1,7 @@ -package com.inuker.solution; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; -/** - * Created by dingjikerbo on 16/12/10. - */ - /** * 可以轻易拓展到k的情况 */ diff --git a/solution/src/main/java/com/inuker/solution/system/DesignTinyURL.java b/leetcode/solution/src/system/DesignTinyURL.java similarity index 96% rename from solution/src/main/java/com/inuker/solution/system/DesignTinyURL.java rename to leetcode/solution/src/system/DesignTinyURL.java index a58b5a2..f6cc465 100644 --- a/solution/src/main/java/com/inuker/solution/system/DesignTinyURL.java +++ b/leetcode/solution/src/system/DesignTinyURL.java @@ -1,8 +1,4 @@ -package com.inuker.solution.system; - -/** - * Created by liwentian on 2017/10/17. - */ +package system; public class DesignTinyURL { diff --git a/solution/src/main/java/com/inuker/solution/system/Info.java b/leetcode/solution/src/system/Info.java similarity index 52% rename from solution/src/main/java/com/inuker/solution/system/Info.java rename to leetcode/solution/src/system/Info.java index f42f53e..63d659a 100644 --- a/solution/src/main/java/com/inuker/solution/system/Info.java +++ b/leetcode/solution/src/system/Info.java @@ -1,8 +1,4 @@ -package com.inuker.solution.system; - -/** - * Created by liwentian on 2017/10/17. - */ +package system; public class Info { /** diff --git a/leetcode/src/Main.java b/leetcode/src/Main.java new file mode 100644 index 0000000..549368f --- /dev/null +++ b/leetcode/src/Main.java @@ -0,0 +1,25 @@ + +public class Main { + + public static class Solution { + + int reversePairs(int[] arr, int m) { + int pairs = 0; + for (int i = m - 1, j = arr.length - 1; j >= m; j--) { + for ( ; i >= 0 && arr[i] > arr[j]; i--); + pairs += m - 1 - i; + } + return pairs; + } + } + + + public static void main(String[] args) { + Solution s = new Solution(); + int[] arr = { + 1, 4, 8, 9, 2, 3, 6, 7 + }; + int n = s.reversePairs(arr, 4); + System.out.println(n); + } +} diff --git a/library/.gitignore b/library/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/library/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/library/build.gradle b/library/build.gradle deleted file mode 100644 index 49df001..0000000 --- a/library/build.gradle +++ /dev/null @@ -1,8 +0,0 @@ -apply plugin: 'java' - -dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) -} - -sourceCompatibility = "1.7" -targetCompatibility = "1.7" diff --git a/library/library.iml b/library/library.iml deleted file mode 100644 index 163b10e..0000000 --- a/library/library.iml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/library/src/main/java/.DS_Store b/library/src/main/java/.DS_Store deleted file mode 100644 index 0a8bc21..0000000 Binary files a/library/src/main/java/.DS_Store and /dev/null differ diff --git a/library/src/main/java/com/.DS_Store b/library/src/main/java/com/.DS_Store deleted file mode 100644 index d74398f..0000000 Binary files a/library/src/main/java/com/.DS_Store and /dev/null differ diff --git a/library/src/main/java/com/leetcode/.DS_Store b/library/src/main/java/com/leetcode/.DS_Store deleted file mode 100644 index 6e03305..0000000 Binary files a/library/src/main/java/com/leetcode/.DS_Store and /dev/null differ diff --git a/progen.txt b/progen.txt deleted file mode 100644 index cf95517..0000000 --- a/progen.txt +++ /dev/null @@ -1,2 +0,0 @@ -67. Add Binary -https://leetcode.com/problems/add-binary/ \ No newline at end of file diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 5ff209f..0000000 --- a/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -include ':app', ':solution', ':google', ':library', ':facebook', ':amazon', ':tools', ':test' \ No newline at end of file diff --git a/solution/.gitignore b/solution/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/solution/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/solution/build.gradle b/solution/build.gradle deleted file mode 100644 index ecca447..0000000 --- a/solution/build.gradle +++ /dev/null @@ -1,13 +0,0 @@ -apply plugin: 'java' - -dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - compile project(path: ':library') -} - -tasks.withType(JavaCompile) { - options.encoding = "UTF-8" -} - -sourceCompatibility = "1.8" -targetCompatibility = "1.8" diff --git a/solution/solution.iml b/solution/solution.iml deleted file mode 100644 index e2c2fa5..0000000 --- a/solution/solution.iml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/solution/src/main/java/com/inuker/solution/.DS_Store b/solution/src/main/java/com/inuker/solution/.DS_Store deleted file mode 100644 index 5008ddf..0000000 Binary files a/solution/src/main/java/com/inuker/solution/.DS_Store and /dev/null differ diff --git a/solution/src/main/java/com/inuker/solution/AddBinary.java b/solution/src/main/java/com/inuker/solution/AddBinary.java deleted file mode 100644 index 95f4c5b..0000000 --- a/solution/src/main/java/com/inuker/solution/AddBinary.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/19. - */ - -public class AddBinary { - - public String addBinary(String a, String b) { - StringBuilder sb = new StringBuilder(); - int i = a.length() - 1, j = b.length() - 1, k = 0; - for ( ; i >= 0 || j >= 0 || k > 0; i--, j--) { - int i0 = i >= 0 ? a.charAt(i) - '0' : 0; - int j0 = j >= 0 ? b.charAt(j) - '0' : 0; - int s = i0 + j0 + k; - sb.insert(0, s & 1); - k = s >> 1; - } - return sb.toString(); - } -} diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversalII.java b/solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversalII.java deleted file mode 100644 index c251ecd..0000000 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeLevelOrderTraversalII.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - -public class BinaryTreeLevelOrderTraversalII { - - // 耗时2ms,和I一样,只不过加到result时添加到头 - public List> levelOrder(TreeNode root) { - List> result = new LinkedList>(); - - if (root == null) { - return result; - } - - Queue queue = new LinkedList(); - Queue next = new LinkedList(); - queue.add(root); - - List cur = null; - - while (!queue.isEmpty()) { - TreeNode node = queue.poll(); - - if (cur == null) { - cur = new LinkedList(); - result.add(0, cur); - } - - cur.add(node.val); - - if (node.left != null) { - next.add(node.left); - } - - if (node.right != null) { - next.add(node.right); - } - - if (queue.isEmpty()) { - Queue temp = queue; - queue = next; - next = temp; - cur = null; // 注意这里要置空 - } - } - - return result; - } -} diff --git a/solution/src/main/java/com/inuker/solution/BinaryTreeRightSideView.java b/solution/src/main/java/com/inuker/solution/BinaryTreeRightSideView.java deleted file mode 100644 index 93d9584..0000000 --- a/solution/src/main/java/com/inuker/solution/BinaryTreeRightSideView.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - -public class BinaryTreeRightSideView { - - public List rightSideView(TreeNode root) { - List result = new LinkedList(); - - if (root == null) { - return result; - } - - Queue queue = new LinkedList(); - Queue next = new LinkedList(); - - queue.add(root); - - while (!queue.isEmpty()) { - TreeNode node = queue.poll(); - - if (node.left != null) { - next.add(node.left); - } - - if (node.right != null) { - next.add(node.right); - } - - if (queue.isEmpty()) { - result.add(node.val); - Queue temp = queue; - queue = next; - next = temp; - } - } - - return result; - } -} diff --git a/solution/src/main/java/com/inuker/solution/CopyListWithRandomPointer.java b/solution/src/main/java/com/inuker/solution/CopyListWithRandomPointer.java deleted file mode 100644 index 26bc9b5..0000000 --- a/solution/src/main/java/com/inuker/solution/CopyListWithRandomPointer.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -import com.leetcode.library.RandomListNode; - -/** - * 易错的地方在于random要判空 - */ -public class CopyListWithRandomPointer { - - - public RandomListNode copyRandomList(RandomListNode head) { - for (RandomListNode node = head; node != null; ) { - RandomListNode next = node.next; - - RandomListNode copy = new RandomListNode(node.label); - copy.next = next; - node.next = copy; - node = next; - } - - for (RandomListNode node = head; node != null; ) { - node.next.random = node.random != null ? node.random.next : null; - node = node.next.next; - } - - RandomListNode dummy = new RandomListNode(0), cur = dummy; - for (RandomListNode node = head; node != null; ) { - cur.next = node.next; - cur = cur.next; - - node.next = node.next.next; - node = node.next; - } - - return dummy.next; - } -} - - diff --git a/solution/src/main/java/com/inuker/solution/DecodeWays.java b/solution/src/main/java/com/inuker/solution/DecodeWays.java deleted file mode 100644 index 98006a6..0000000 --- a/solution/src/main/java/com/inuker/solution/DecodeWays.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 16/11/20. - */ - -/** - * TestCases - * "" - * "1" - * "1787897759966261825913315262377298132516969578441236833255596967132573482281598412163216914566534565" - * "7893749912342187894921836847319981199844151766195952528631828655978178193192959793156142441128167383" - */ -public class DecodeWays { - - /** - * 超时了,有大量的字符串复制,不过思路挺直观的 - * 注意这里s为空时要返回0,但是在递归时s为空要返回1,所以为了区分这两种情况,分出了helper - */ - public int numDecodings(String s) { - if (s.length() == 0) { - return 0; - } - return helper(s); - } - - public int helper(String s) { - /** - * 如果能一直正确匹配到结尾了是合法的 - */ - if (s.length() == 0) { - return 1; - } - - // 以0开头的是非法的 - if (s.charAt(0) == '0') { - return 0; - } - - int ways = 0; - - if (s.length() > 1 && (s.charAt(0) == '1' || (s.charAt(0) == '2' && (s.charAt(1) >= '0' && s.charAt(1) <= '6')))) { - ways += helper(s.substring(2)); - } - - ways += helper(s.substring(1)); - - return ways; - } - - /** - // 这里继续优化,为避免重复运算,对结果进行了缓存,性能非常好,耗时2ms - public int numDecodings(String s) { - if (s.length() == 0) { - return 0; - } - int[] f = new int[s.length()]; - Arrays.fill(f, -1); - return helper(s.toCharArray(), f, 0); - } - - public int helper(char[] s, int[] f, int i) { - if (i >= s.length) { - return 1; - } - - if (s[i] == '0') { - return 0; - } - - // 这里一定要包括等于0,因为0也是要缓存的,表示后面的子串都不可能合法,比如30....... - if (f[i] >= 0) { - return f[i]; - } - - int ways = 0; - - if (i < s.length - 1 && (s[i] == '1' || (s[i] == '2' && (s[i + 1] >= '0' && s[i + 1] <= '6')))) { - ways += helper(s, f, i + 2); - } - - f[i] = ways + helper(s, f, i + 1); - - return f[i]; - } -*/ - - // DP,耗时2ms,复杂度O(n) - public int numDecodings2(String s) { - if (s.length() == 0) { - return 0; - } - int n = s.length(); - int[] f = new int[n + 1]; - f[0] = 1; - f[1] = s.charAt(0) == '0' ? 0 : 1; - - for (int i = 1; i < n; i++) { - if (s.charAt(i - 1) == '1' || (s.charAt(i - 1) == '2' && s.charAt(i) <= '6')) { - f[i + 1] = f[i - 1]; - } - if (s.charAt(i) != '0') { - f[i + 1] += f[i]; - } - } - return f[n]; - } -} diff --git a/solution/src/main/java/com/inuker/solution/EvaluateDivision.java b/solution/src/main/java/com/inuker/solution/EvaluateDivision.java deleted file mode 100644 index 1811f62..0000000 --- a/solution/src/main/java/com/inuker/solution/EvaluateDivision.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.inuker.solution; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -/** - * Created by liwentian on 2017/9/3. - */ - -/** - * 1, 首先给除的结果都存起来,建立有向图 - * 2,用DFS遍历路径 - */ -public class EvaluateDivision { - - public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { - HashMap> valueMap = new HashMap<>(); - - for (int i = 0; i < equations.length; i++) { - String[] equation = equations[i]; - HashMap map = valueMap.computeIfAbsent(equation[0], k -> new HashMap<>()); - map.put(equation[1], values[i]); - map = valueMap.computeIfAbsent(equation[1], k -> new HashMap<>()); - map.put(equation[0], 1 / values[i]); - } - - double[] result = new double[queries.length]; - for (int i = 0; i < queries.length; i++) { - double[] value = new double[] {1.0}; - result[i] = dfs(valueMap, queries[i][0], queries[i][1], new HashSet<>(), value) ? value[0] : -1.0; - } - return result; - } - - private boolean dfs(HashMap> map, String start, String end, HashSet set, double[] value) { - if (!map.containsKey(start) || !map.containsKey(end) || set.contains(start)) { - return false; - } - if (start.equals(end)) { - return true; - } - set.add(start); - HashMap valueMap = map.get(start); - boolean flag = false; - for (Map.Entry entry : valueMap.entrySet()) { - value[0] *= entry.getValue(); - if (dfs(map, entry.getKey(), end, set, value)) { - flag = true; - break; - } - value[0] /= entry.getValue(); - } - set.remove(start); - return flag; - } -} diff --git a/solution/src/main/java/com/inuker/solution/FirstUniqueCharacterInAString.java b/solution/src/main/java/com/inuker/solution/FirstUniqueCharacterInAString.java deleted file mode 100644 index ada2ebf..0000000 --- a/solution/src/main/java/com/inuker/solution/FirstUniqueCharacterInAString.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.inuker.solution; - -import java.util.Arrays; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -public class FirstUniqueCharacterInAString { - - // 耗时21ms,O(2n) - public int firstUniqChar(String s) { - int[] cnt = new int[26]; - for (char c : s.toCharArray()) { - cnt[c - 'a']++; - } - for (int i = 0; i < s.length(); i++) { - if (cnt[s.charAt(i) - 'a'] == 1) { - return i; - } - } - return -1; - } -} diff --git a/solution/src/main/java/com/inuker/solution/GroupAnagrams.java b/solution/src/main/java/com/inuker/solution/GroupAnagrams.java deleted file mode 100644 index 0253be2..0000000 --- a/solution/src/main/java/com/inuker/solution/GroupAnagrams.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.inuker.solution; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 16/11/22. - */ - -public class GroupAnagrams { - - public List> groupAnagrams(String[] strs) { - HashMap> map = new HashMap<>(); - - for (String s : strs) { - char[] cc = s.toCharArray(); - Arrays.sort(cc); - - String t = new String(cc); - - List list = map.get(t); - if (list == null) { - list = new LinkedList<>(); - map.put(t, list); - } - - list.add(s); - } - - return new LinkedList<>(map.values()); - } - -} diff --git a/solution/src/main/java/com/inuker/solution/HouseRobberIII.java b/solution/src/main/java/com/inuker/solution/HouseRobberIII.java deleted file mode 100644 index d785739..0000000 --- a/solution/src/main/java/com/inuker/solution/HouseRobberIII.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 16/12/1. - */ - -public class HouseRobberIII { - - public int rob(TreeNode root) { - return rob(root, true); - } - - /** - * @param rob true表示不定,false表示不选root - */ - private int rob(TreeNode root, boolean rob) { - if (root == null) { - return 0; - } - - if (rob) { - return Math.max(root.val + rob(root.left, false) + rob(root.right, false), - rob(root.left, true) + rob(root.right, true)); - } else { - return rob(root.left, true) + rob(root.right, true); - } - } -} diff --git a/solution/src/main/java/com/inuker/solution/InsertDeleteGetRandom.java b/solution/src/main/java/com/inuker/solution/InsertDeleteGetRandom.java deleted file mode 100644 index 6404809..0000000 --- a/solution/src/main/java/com/inuker/solution/InsertDeleteGetRandom.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.inuker.solution; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Random; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -/** - * 有几点要注意: - * remove时要判断删除的是不是最后一个,另外交换了结尾后要更新结尾数的idx - */ -// 耗时111ms -public class InsertDeleteGetRandom { - - private HashMap mMap; - private List mList; - private Random mRandom; - - public InsertDeleteGetRandom() { - mList = new ArrayList(); - mMap = new HashMap(); - mRandom = new Random(); - } - - public boolean insert(int val) { - if (mMap.containsKey(val)) { - return false; - } - mList.add(val); - mMap.put(val, mList.size() - 1); - return true; - } - - public boolean remove(int val) { - if (!mMap.containsKey(val)) { - return false; - } - int index = mMap.remove(val); - int lastIndex = mList.size() - 1; - if (index != lastIndex) { - int lastVal = mList.get(lastIndex); - mList.set(index, lastVal); - // 这里要注意重新设置lastVal的index - mMap.put(lastVal, index); - } - mList.remove(lastIndex); - return true; - } - - public int getRandom() { - int index = mRandom.nextInt(mList.size()); - return mList.get(index); - } -} diff --git a/solution/src/main/java/com/inuker/solution/KthSmallestElementInBST.java b/solution/src/main/java/com/inuker/solution/KthSmallestElementInBST.java deleted file mode 100644 index 488a1ff..0000000 --- a/solution/src/main/java/com/inuker/solution/KthSmallestElementInBST.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.Stack; - -/** - * Created by dingjikerbo on 16/11/30. - */ - -/** - * 这题关键是follow up - * 如果更新频繁,则通常的做法每次都是O(n),更优的做法是O(lgn) - * 即给node中记录左子树的节点个数,这样在找kth smallest时流程如下: - * 假设root的左子树节点有N个,则 - * 1, 当K=N+1时,kth就是root - * 2, 当KN+1时,就到右子树中找第K-N-1个 - * 所以当给定一棵树时,我们要先重建一下这棵树,统计一下各节点的左子树节点数,虽然首次是O(n) - * 但是之后就是O(h)了。 - */ -public class KthSmallestElementInBST { - - public int kthSmallest(TreeNode root, int k) { - int[] kth = new int[1]; - inorderTraversal(root, k, kth); - return kth[0]; - } - - private int inorderTraversal(TreeNode root, int k, int[] kth) { - if (root == null) { - return k; - } - - k = inorderTraversal(root.left, k, kth); - - if (--k == 0) { - kth[0] = root.val; - return 0; - } - - return inorderTraversal(root.right, k, kth); - } - - /** - * 非递归法 - */ - public int kthSmallest2(TreeNode root, int k) { - Stack stack = new Stack<>(); - while (root != null || !stack.isEmpty()) { - if (root != null) { - stack.push(root); - root = root.left; - } else { - root = stack.pop(); - - if (--k == 0) { - return root.val; - } - - root = root.right; - } - } - throw new IllegalStateException(); - } - - /** - * Morris - */ - private int kthSmallest3(TreeNode root, int k) { - TreeNode temp; - - while (root != null) { - if (root.left == null) { - if (--k == 0) { - return root.val; - } - root = root.right; - } else { - temp = root.left; - while (temp.right != null && temp.right != root) { - temp = temp.right; - } - if (temp.right == null) { - temp.right = root; - root = root.left; - } else { - temp.right = null; - if (--k == 0) { - return root.val; - } - root = root.right; - } - } - } - throw new IllegalStateException(); - } -} diff --git a/solution/src/main/java/com/inuker/solution/LetterCombinationOfPhoneNumber.java b/solution/src/main/java/com/inuker/solution/LetterCombinationOfPhoneNumber.java deleted file mode 100644 index 3392e1c..0000000 --- a/solution/src/main/java/com/inuker/solution/LetterCombinationOfPhoneNumber.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.inuker.solution; - -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -public class LetterCombinationOfPhoneNumber { - - /** - * leetcode的测试用例中不包括包含"0"或"1"的情况 - */ - - private final String[] ARR = { - "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" - }; - - // 耗时3ms - public List letterCombinations(String digits) { - List list = new LinkedList<>(); - if (!digits.isEmpty()) { - helper(digits, 0, list, ""); - } - return list; - } - - private void helper(String digits, int start, List list, String s) { - if (start >= digits.length()) { - list.add(s); - return; - } - int n = digits.charAt(start) - '0'; - for (char c : ARR[n].toCharArray()) { - helper(digits, start + 1, list, s + c); - } - } - - /** - * 非递归法,BFS,耗时5ms - */ - public List letterCombinations2(String digits) { - LinkedList queue = new LinkedList(); - if (digits.length() == 0) { - return queue; - } - - Queue next = new LinkedList<>(); - queue.add(""); - - for (int i = 0; i < digits.length() && !queue.isEmpty(); ) { - String s = queue.poll(); - int n = digits.charAt(i) - '0'; - for (char c : ARR[n].toCharArray()) { - next.add(s + c); - } - if (queue.isEmpty()) { - queue.addAll(next); - next.clear(); - i++; - } - } - return queue; - } -} diff --git a/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostTwoDistinctCharacters.java b/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostTwoDistinctCharacters.java deleted file mode 100644 index 24e48b7..0000000 --- a/solution/src/main/java/com/inuker/solution/LongestSubstringWithAtMostTwoDistinctCharacters.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.inuker.solution; - -import java.util.HashMap; - -/** - * Created by dingjikerbo on 16/11/27. - */ - -public class LongestSubstringWithAtMostTwoDistinctCharacters { - - // 7ms - public int lengthOfLongestSubstringTwoDistinct2(String s) { - int[] count = new int[256]; - int distinct = 0, longest = 0; - - for (int i = 0, j = 0; j < s.length(); j++) { - if (count[s.charAt(j)]++ == 0) { - distinct++; - } - - for ( ; i < j && distinct > 2; ) { - if (--count[s.charAt(i++)] == 0) { - --distinct; - } - } - - longest = Math.max(longest, j - i + 1); - } - - return longest; - } -} diff --git a/solution/src/main/java/com/inuker/solution/LongestSubstringWithoutRepeatingCharacters.java b/solution/src/main/java/com/inuker/solution/LongestSubstringWithoutRepeatingCharacters.java deleted file mode 100644 index 4465e72..0000000 --- a/solution/src/main/java/com/inuker/solution/LongestSubstringWithoutRepeatingCharacters.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - -/** - * https://leetcode.com/articles/longest-substring-without-repeating-characters/ - */ -public class LongestSubstringWithoutRepeatingCharacters { - - // 耗时39ms,性能挺好 - public int lengthOfLongestSubstring(String s) { - int[] count = new int[256]; - - int maxLen = 0; - - for (int i = 0, j = 0; j < s.length(); ) { - if (count[s.charAt(j)] == 0) { - count[s.charAt(j)]++; - maxLen = Math.max(maxLen, j - i + 1); - j++; - } else { - --count[s.charAt(i++)]; - } - } - - return maxLen; - } -} diff --git a/solution/src/main/java/com/inuker/solution/MergeKSortedList.java b/solution/src/main/java/com/inuker/solution/MergeKSortedList.java deleted file mode 100644 index 72435cc..0000000 --- a/solution/src/main/java/com/inuker/solution/MergeKSortedList.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.ListNode; - -import java.util.Comparator; -import java.util.PriorityQueue; -import java.util.Queue; - -/** - * Created by dingjikerbo on 16/11/20. - * https://leetcode.com/articles/merge-k-sorted-list/ - */ - -public class MergeKSortedList { - - // 耗时19ms - // 时间复杂度为O(knlgn) - /** - * 这里要注意lists中可能有node为null - */ - public ListNode mergeKLists(ListNode[] lists) { - ListNode dummy = new ListNode(0), cur = dummy; - - PriorityQueue queue = new PriorityQueue<>(new Comparator() { - @Override - public int compare(ListNode node1, ListNode node2) { - return node1.val - node2.val; - } - }); - - for (ListNode node : lists) { - if (node != null) { - queue.offer(node); - } - } - - while (!queue.isEmpty()) { - ListNode node = queue.poll(); - cur.next = node; - cur = cur.next; - if (node.next != null) { - queue.offer(node.next); - } - } - - return dummy.next; - } -} diff --git a/solution/src/main/java/com/inuker/solution/PathSumII.java b/solution/src/main/java/com/inuker/solution/PathSumII.java deleted file mode 100644 index a83c583..0000000 --- a/solution/src/main/java/com/inuker/solution/PathSumII.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 2016/11/29. - */ - -public class PathSumII { - - public List> pathSum(TreeNode root, int sum) { - List> result = new LinkedList<>(); - pathSum(root, sum, result, new LinkedList()); - return result; - } - - /** - * 这里一定要拷贝一份链表再加到result - * 此时path中已经包含了root,sum中还不包含root - */ - private void pathSum(TreeNode root, int sum, List> result, List list) { - if (root == null) { - return; - } - - list.add(root.val); - - if (root.left == null && root.right == null && sum == root.val) { - result.add(new LinkedList<>(list)); - return; - } - - if (root.left != null) { - pathSum(root.left, sum - root.val, result, list); - list.remove(list.size() - 1); - } - - if (root.right != null) { - pathSum(root.right, sum - root.val, result, list); - list.remove(list.size() - 1); - } - } -} diff --git a/solution/src/main/java/com/inuker/solution/ProductOfArrayExceptSelf.java b/solution/src/main/java/com/inuker/solution/ProductOfArrayExceptSelf.java deleted file mode 100644 index fabd0a5..0000000 --- a/solution/src/main/java/com/inuker/solution/ProductOfArrayExceptSelf.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -public class ProductOfArrayExceptSelf { - - // 耗时2ms - public int[] productExceptSelf(int[] nums) { - if (nums.length == 0) { - return null; - } - int[] result = new int[nums.length]; - result[0] = 1; - for (int i = 1; i < nums.length; i++) { - result[i] = nums[i - 1] * result[i - 1]; - } - int right = 1; - for (int i = nums.length - 1; i >= 0; i--) { - result[i] *= right; - right *= nums[i]; - } - return result; - } -} diff --git a/solution/src/main/java/com/inuker/solution/RestoreIPAddresses.java b/solution/src/main/java/com/inuker/solution/RestoreIPAddresses.java deleted file mode 100644 index ef854b9..0000000 --- a/solution/src/main/java/com/inuker/solution/RestoreIPAddresses.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.inuker.solution; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by liwentian on 2017/9/6. - */ - -public class RestoreIPAddresses { - - /** - * 注意,0可以,但是00,01, 010这种是不允许的 - */ - public List restoreIpAddresses(String s) { - List list = new LinkedList<>(); - dfs(s, list, 0, 0, ""); - return list; - } - - private void dfs(String s, List list, int index, int count, String cur) { - if (index >= s.length()) { - if (count == 4) { - list.add(cur); - } - return; - } - - if (count == 4) { - return; - } - - int[][] RANGES = { - {0, 0}, {0, 9}, {10, 99}, {100, 255} - }; - for (int i = 1; i <= 3 && index + i <= s.length(); i++) { - String t = s.substring(index, index + i); - int n = Integer.parseInt(t); - if (n >= RANGES[i][0] && n <= RANGES[i][1]) { - dfs(s, list, index + i, count + 1, (cur.isEmpty() ? "" : cur + ".") + t); - } - } - } -} diff --git a/solution/src/main/java/com/inuker/solution/ReverseWordsInAString.java b/solution/src/main/java/com/inuker/solution/ReverseWordsInAString.java deleted file mode 100644 index 3dc4420..0000000 --- a/solution/src/main/java/com/inuker/solution/ReverseWordsInAString.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 17/8/14. - */ - -public class ReverseWordsInAString { - - - // 耗时10ms - public String reverseWords(String s) { - StringBuilder sb = new StringBuilder(); - - boolean inWord = false; - char[] cc = s.toCharArray(); - for (int i = cc.length - 1, idx = 0; i >= 0; i--) { - if (cc[i] != ' ') { - if (!inWord && sb.length() > 0) { - sb.append(' '); - } - inWord = true; - sb.insert(idx, cc[i]); - } else if (inWord) { - idx = sb.length() + 1; - inWord = false; - } - } - - return sb.toString(); - } - - // 耗时18ms - public String reverseWords2(String s) { - StringBuilder sb = new StringBuilder(); - - for (int i = 0, j = 0; i < s.length(); ) { - if (s.charAt(i) == ' ') { - i++; - j = i; - } else if (j >= s.length() || s.charAt(j) == ' ') { - sb.insert(0, s.substring(i, j) + " "); - i = j; - } else { - j++; - } - } - - if (sb.length() > 0) { - sb.setLength(sb.length() - 1); - } - - return sb.toString(); - } -} diff --git a/solution/src/main/java/com/inuker/solution/RotateImage.java b/solution/src/main/java/com/inuker/solution/RotateImage.java deleted file mode 100644 index 9e8a288..0000000 --- a/solution/src/main/java/com/inuker/solution/RotateImage.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ -public class RotateImage { - - // 耗时2ms - public void rotate(int[][] matrix) { - int n = matrix.length; - - for (int i = 0; i < n / 2; i++) { - for (int j = 0; j < n; j++) { - int t = matrix[i][j]; - matrix[i][j] = matrix[n - 1 - i][j]; - matrix[n - 1 - i][j] = t; - } - } - - for (int i = 0; i < n; i++) { - for (int j = 0; j < i; j++) { - int t = matrix[i][j]; - matrix[i][j] = matrix[j][i]; - matrix[j][i] = t; - } - } - } -} diff --git a/solution/src/main/java/com/inuker/solution/SearchForARange.java b/solution/src/main/java/com/inuker/solution/SearchForARange.java deleted file mode 100644 index c7114b7..0000000 --- a/solution/src/main/java/com/inuker/solution/SearchForARange.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/12/17. - */ - -public class SearchForARange { - - /** - * TestCase - * [1], 0 - * [1], 1 - */ - public int[] searchRange(int[] nums, int target) { - if (nums.length == 0) { - return new int[]{-1, -1}; - } - int first = firstHigherEqual(nums, target); - if (first == nums.length || nums[first] != target) { - return new int[] { - -1, -1 - }; - } - return new int[] { - first, - firstHigherEqual(nums, target + 1) - 1 - }; - } - - private int firstHigherEqual(int[] nums, int target) { - int left = 0, right = nums.length; - while (left < right) { - int mid = (left + right) / 2; - if (nums[mid] < target) { - left = mid + 1; - } else { - right = mid; - } - } - return left; - } - - public int[] searchRange2(int[] nums, int target) { - if (nums.length == 0) { - return new int[]{-1, -1}; - } - return new int[] { - lowerBound(nums, target), - upperBound(nums, target) - }; - } - - /** - * lowerBound和upperBound的TestCase - * [1,3],3 - * [1,3],1 - * [2,2],2 - */ - public static int lowerBound(int[] nums, int target) { - int left = 0, right = nums.length - 1; - - while (left < right) { - int mid = left + ((right - left) >> 1); - - if (target > nums[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - - return nums[left] == target ? left : -1; - } - - public static int upperBound(int[] nums, int target) { - int left = 0, right = nums.length - 1; - - while (left < right) { - int mid = left + ((right - left) >> 1) + 1; - - if (target < nums[mid]) { - right = mid - 1; - } else { - left = mid; - } - } - - return nums[right] == target ? right : -1; - } -} diff --git a/solution/src/main/java/com/inuker/solution/String2Integer.java b/solution/src/main/java/com/inuker/solution/String2Integer.java deleted file mode 100644 index 6ee927c..0000000 --- a/solution/src/main/java/com/inuker/solution/String2Integer.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 17/4/29. - */ - -/** - * 要求如下: - * 1. 过滤掉前面的空格 - * 2. 考虑正负号 - * 3. 如果溢出则返回上限或下限 - * 4. 解析时遇到非法字符则停止,返回当前结果 - * 5,防御空串 - */ - -/** - * TestCase: "" - */ -public class String2Integer { - - public int myAtoi(String str) { - long n = 0; - - str = str.trim(); - - // 这里要防御空串 - if (str.length() == 0) { - return 0; - } - - int sign = 1; - - switch (str.charAt(0)) { - case '-': - sign = -1; - case '+': - str = str.substring(1); - break; - } - - for (char c : str.toCharArray()) { - if (c >= '0' && c <= '9') { - n = n * 10 + (c - '0'); - - if (n * sign > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } else if (n * sign < Integer.MIN_VALUE) { - return Integer.MIN_VALUE; - } - - } else { - break; - } - } - - return (int) (n * sign); - } -} diff --git a/solution/src/main/java/com/inuker/solution/SumRootToLeafNumbers.java b/solution/src/main/java/com/inuker/solution/SumRootToLeafNumbers.java deleted file mode 100644 index 69fa5f9..0000000 --- a/solution/src/main/java/com/inuker/solution/SumRootToLeafNumbers.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/12/2. - */ - -public class SumRootToLeafNumbers { - - private int result; - - public int sumNumbers(TreeNode root) { - sumNumbers(root, 0); - return result; - } - - private void sumNumbers(TreeNode root, int sum) { - if (root == null) { - return; - } - - sum = sum * 10 + root.val; - - if (root.left == null && root.right == null) { - result += sum; - return; - } - - sumNumbers(root.left, sum); - sumNumbers(root.right, sum); - } -} diff --git a/solution/src/main/java/com/inuker/solution/SymmetricTree.java b/solution/src/main/java/com/inuker/solution/SymmetricTree.java deleted file mode 100644 index 6fffb8d..0000000 --- a/solution/src/main/java/com/inuker/solution/SymmetricTree.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -/** - * Created by dingjikerbo on 2016/11/29. - */ - -public class SymmetricTree { - - public boolean isSymmetric(TreeNode root) { - if (root == null) { - return true; - } - return isSymmetric(root.left, root.right); - } - - private boolean isSymmetric(TreeNode left, TreeNode right) { - if (left == null && right == null) { - return true; - } - if (left == null || right == null) { - return false; - } - return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); - } -} diff --git a/solution/src/main/java/com/inuker/solution/ThirdMaximumNumber.java b/solution/src/main/java/com/inuker/solution/ThirdMaximumNumber.java deleted file mode 100644 index 47c775a..0000000 --- a/solution/src/main/java/com/inuker/solution/ThirdMaximumNumber.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.inuker.solution; - -/** - * Created by liwentian on 17/8/12. - */ - -/** - * 这题注意边界情况 - */ -public class ThirdMaximumNumber { - - public int thirdMax(int[] nums) { - int count = 0; - - long first = (long) Integer.MIN_VALUE - 1; - long second = (long) Integer.MIN_VALUE - 1; - long third = (long) Integer.MIN_VALUE - 1; - - for (int n : nums) { - if (n == first || n == second || n == third) { - continue; - } - - if (n > first) { - count++; - third = second; - second = first; - first = n; - } else if (n > second) { - count++; - third = second; - second = n; - } else if (n >= third) { - count++; - third = n; - } - } - - return (int) (count >= 3 ? third : first); - } -} diff --git a/solution/src/main/java/com/inuker/solution/ThreeSum.java b/solution/src/main/java/com/inuker/solution/ThreeSum.java deleted file mode 100644 index 812d2aa..0000000 --- a/solution/src/main/java/com/inuker/solution/ThreeSum.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.inuker.solution; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 16/11/20. - */ - -/** - * TestCase - * [-4,-2,1,-5,-4,-4,4,-2,0,4,0,-2,3,1,-5,0] - * 这题重要的是查重 - */ -public class ThreeSum { - - /** - * 最底下那个for循环别给j < k掉了 - */ - - // 耗时30ms - public List> threeSum(int[] nums) { - Arrays.sort(nums); - - List> result = new LinkedList<>(); - - for (int i = 0; i < nums.length; i++) { - if (i > 0 && nums[i] == nums[i - 1]) { - continue; - } - for (int j = i + 1, k = nums.length - 1; j < k; ) { - int sum = nums[i] + nums[j] + nums[k]; - - if (sum > 0) { - k--; - } else if (sum < 0) { - j++; - } else { - result.add(Arrays.asList(nums[i], nums[j], nums[k])); - for (j++, k--; j < k && nums[j] == nums[j - 1]; j++); - } - } - } - - return result; - } -} diff --git a/solution/src/main/java/com/inuker/solution/ThreeSumClosest.java b/solution/src/main/java/com/inuker/solution/ThreeSumClosest.java deleted file mode 100644 index 2987dc5..0000000 --- a/solution/src/main/java/com/inuker/solution/ThreeSumClosest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.inuker.solution; - -import java.util.Arrays; - -/** - * Created by dingjikerbo on 17/5/5. - */ - -public class ThreeSumClosest { - - public int threeSumClosest(int[] nums, int target) { - Arrays.sort(nums); - - long dis = Integer.MAX_VALUE, result = 0; - - for (int i = 0; i < nums.length - 2; i++) { - int newTarget = target - nums[i]; - - for (int j = i + 1, k = nums.length - 1; j < k; ) { - int sum = nums[j] + nums[k]; - - if (sum > newTarget) { - k--; - } else if (sum < newTarget) { - j++; - } else { - return target; - } - - long delta = Math.abs(newTarget - sum); - if (delta < dis) { - dis = delta; - result = sum + nums[i]; - } - } - } - - return (int) result; - } -} diff --git a/solution/src/main/java/com/inuker/solution/TrappingRainWater.java b/solution/src/main/java/com/inuker/solution/TrappingRainWater.java deleted file mode 100644 index ceadca2..0000000 --- a/solution/src/main/java/com/inuker/solution/TrappingRainWater.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -/** - * 核心思路就是对于每根柱子,找到其左边最高的柱子和右边最高的柱子,构成一个桶,形成一个水平面,然后对该柱子形成的高度差就是能装的水 - */ -public class TrappingRainWater { - - // 耗时24ms - public int trap(int[] height) { - int len = height.length; - - if (len == 0) { - return 0; - } - - int[] left = new int[len]; - int[] right = new int[len]; - - left[0] = 0; - right[len - 1] = 0; - - for (int i = 1; i < len; i++) { - left[i] = Math.max(left[i - 1], height[i - 1]); - } - for (int i = len - 2; i>= 0; i--) { - right[i] = Math.max(right[i + 1], height[i + 1]); - } - int sum = 0; - for (int i = 0; i < len; i++) { - int high = Math.min(left[i], right[i]); - if (high > height[i]) { - sum += high - height[i]; - } - } - return sum; - } -} diff --git a/solution/src/main/java/com/inuker/solution/TwoSum.java b/solution/src/main/java/com/inuker/solution/TwoSum.java deleted file mode 100644 index 09b6d06..0000000 --- a/solution/src/main/java/com/inuker/solution/TwoSum.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.inuker.solution; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -/** - * https://leetcode.com/articles/two-sum/ - */ -public class TwoSum { - - /** - * 如果符合条件的不止一组呢?则找到一组就从map删除一组 - * @return - */ - public int[] twoSum(int[] nums, int target) { - HashMap map = new HashMap<>(); - for (int i = 0; i < nums.length; i++) { - map.put(nums[i], i); - } - for (int i = 0; i < nums.length; i++) { - Integer index = map.get(target - nums[i]); - if (index != null && index != i) { - return new int[] { - i, index - }; - } - } - return null; - } -} diff --git a/solution/src/main/java/com/inuker/solution/UniqueBinarySearchTreesII.java b/solution/src/main/java/com/inuker/solution/UniqueBinarySearchTreesII.java deleted file mode 100644 index 7ac877f..0000000 --- a/solution/src/main/java/com/inuker/solution/UniqueBinarySearchTreesII.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.inuker.solution; - -import com.leetcode.library.TreeNode; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by dingjikerbo on 16/12/1. - */ - -/** - * Dp的解法可以参考https://discuss.leetcode.com/topic/2940/java-solution-with-dp - */ -public class UniqueBinarySearchTreesII { - - public List generateTrees(int n) { - if (n < 1) { - return Collections.EMPTY_LIST; - } - return generateTrees(1, n); - } - - // 从start到end之间取一个数作为root,左边构成left,右边构成right - private List generateTrees(int start, int end) { - List list = new LinkedList(); - if (start > end) { - list.add(null); - return list; - } - for (int i = start; i <= end; i++) { - List lefts = generateTrees(start, i - 1); - List rights = generateTrees(i + 1, end); - for (TreeNode left : lefts) { - for (TreeNode right : rights) { - TreeNode root = new TreeNode(i); - root.left = left; - root.right = right; - list.add(root); - } - - } - } - return list; - } -} diff --git a/solution/src/main/java/com/inuker/solution/ValidParentheses.java b/solution/src/main/java/com/inuker/solution/ValidParentheses.java deleted file mode 100644 index 021d814..0000000 --- a/solution/src/main/java/com/inuker/solution/ValidParentheses.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.inuker.solution; - -/** - * Created by dingjikerbo on 2016/11/16. - */ - -/** - * 要注意栈判空 - */ -public class ValidParentheses { - - // 耗时5ms - public boolean isValid(String s) { - char[] stack = new char[s.length()]; - int top = -1; - - for (char c : s.toCharArray()) { - switch (c) { - case ')': - if (top >= 0 && stack[top] == '(') { - top--; - } else { - return false; - } - break; - case '}': - if (top >= 0 && stack[top] == '{') { - top--; - } else { - return false; - } - break; - case ']': - if (top >= 0 && stack[top] == '[') { - top--; - } else { - return false; - } - break; - default: - stack[++top] = c; - break; - } - } - - return top < 0; - } -} diff --git a/solution/src/main/java/com/inuker/solution/WordBreak.java b/solution/src/main/java/com/inuker/solution/WordBreak.java deleted file mode 100644 index 78ab17e..0000000 --- a/solution/src/main/java/com/inuker/solution/WordBreak.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.inuker.solution; - -import java.util.List; -import java.util.Set; - -/** - * Created by dingjikerbo on 2016/11/17. - */ - -/** - * https://leetcode.com/articles/word-break/ - */ -public class WordBreak { - - // 耗时8ms - public boolean wordBreak(String s, List wordDict) { - int n = s.length(); - - boolean[] dp = new boolean[n + 1]; - dp[0] = true; - - for (int i = 1; i <= s.length(); i++) { - for (String word : wordDict) { - int j = i - word.length(); - if (j >= 0 && dp[j] && s.substring(j, i).equals(word)) { - dp[i] = true; - break; - } - } - } - - return dp[n]; - } -} diff --git a/temp.txt b/temp.txt deleted file mode 100644 index 83ce2f2..0000000 --- a/temp.txt +++ /dev/null @@ -1 +0,0 @@ - [Java](https://github.com/dingjikerbo/leetcode/blob/master/solution/src/main/java/com/inuker/solution/) \ No newline at end of file diff --git a/test.txt b/test.txt deleted file mode 100644 index f8e54e9..0000000 --- a/test.txt +++ /dev/null @@ -1,12 +0,0 @@ -\section{title} %%%%%%%%%%%%%%%%%%%%%%

 - -\subsubsection{Description} - -\subsubsection{Solution} - -\begin{Code} - - -\end{Code} - -\newpage \ No newline at end of file diff --git a/test/.gitignore b/test/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/test/build.gradle b/test/build.gradle deleted file mode 100644 index b240b5b..0000000 --- a/test/build.gradle +++ /dev/null @@ -1,10 +0,0 @@ -apply plugin: 'java-library' - -dependencies { - implementation fileTree(include: ['*.jar'], dir: 'libs') - compile project(':library') - compile project(':solution') -} - -sourceCompatibility = "1.8" -targetCompatibility = "1.8" diff --git a/test/src/main/java/com/inuker/test/Test.java b/test/src/main/java/com/inuker/test/Test.java deleted file mode 100644 index 39009b8..0000000 --- a/test/src/main/java/com/inuker/test/Test.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.inuker.test; - -/** - * Created by liwentian on 2017/12/4. - */ - -public class Test { - - Caller mCaller; - - void call(String name) { - if (mCaller == null) { - mCaller = new Caller() { - @Override - public void call() { - System.out.println(name); - } - }; - } - mCaller.call(); - } - - interface Caller { - void call(); - } -} diff --git a/test/src/main/java/com/inuker/test/Test2.java b/test/src/main/java/com/inuker/test/Test2.java deleted file mode 100644 index 9ebf802..0000000 --- a/test/src/main/java/com/inuker/test/Test2.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.inuker.test; - -import com.leetcode.library.TreeNode; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Set; -import java.util.TreeMap; - -/** - * Created by liwentian on 2017/12/5. - */ - -public class Test2 { - -} diff --git a/test/src/main/java/com/inuker/test/main.java b/test/src/main/java/com/inuker/test/main.java deleted file mode 100644 index 594f846..0000000 --- a/test/src/main/java/com/inuker/test/main.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.inuker.test; - -import com.inuker.solution.FindAllNumbersDisappearedInAnArray; -import com.inuker.solution.MinimumSizeSubarraySum; -import com.inuker.solution.NextPermutation; -import com.inuker.solution.SearchForARange; -import com.leetcode.library.ListNode; -import com.leetcode.library.RandomListNode; -import com.leetcode.library.TreeNode; -import com.leetcode.library.UndirectedGraphNode; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Random; -import java.util.Set; -import java.util.Stack; -import java.util.TreeMap; -import java.util.TreeSet; - -public class main { - - public static void main(String[] args) { - String s = findLongestWord("abpcplea", Arrays.asList("ale","apple","monkey","plea")); - System.out.println(s); - } - - - public static String findLongestWord(String s, List d) { - String longest = ""; - for (String dictWord : d) { - int i = 0; - for (char c : s.toCharArray()) { - if (i < dictWord.length() && c == dictWord.charAt(i)) i++; - } - - if (i == dictWord.length() && dictWord.length() >= longest.length()) { - if (dictWord.length() > longest.length() || dictWord.compareTo(longest) < 0) { - longest = dictWord; - } - } - } - return longest; - } - - -} diff --git a/test/test.iml b/test/test.iml deleted file mode 100644 index cca439b..0000000 --- a/test/test.iml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tools/.gitignore b/tools/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/tools/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/tools/src/main/main3.iml b/tools/src/main/main3.iml new file mode 100644 index 0000000..908ad4f --- /dev/null +++ b/tools/src/main/main3.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file