├── README.md ├── cpp ├── 01-Matrix │ └── README.md ├── 3Sum-Closest │ └── 3Sum-Closest.cpp ├── 3Sum │ └── 3Sum.cpp ├── 4Sum │ └── 4Sum.cpp ├── Add-Strings │ ├── Add-Strings.cpp │ └── README.md ├── Add-Two-Numbers-II │ └── README.md ├── Add_Two_Numbers │ └── Add_Two_Numbers.cpp ├── As-Far-From-Land-As-Possible │ └── README.md ├── Assign-Cookies │ └── README.md ├── Available-Captures-For-Rook │ └── README.md ├── Balanced-Binary-Tree │ ├── Balanced-Binary-Tree.cpp │ └── README.md ├── Best-Sightseeing-Pair │ └── README.md ├── Best-Time-To-Buy-And-Sell-Stock-II │ ├── Best-Time-To-Buy-And-Sell-Stock-II.cpp │ └── README.md ├── Best-Time-To-Buy-And-Sell-Stock-Series │ └── README.md ├── Best-Time-To-Buy-And-Sell-Stock │ ├── Best-Time-To-Buy-And-Sell-Stock.cpp │ └── README.md ├── Binary-Tree-Inorder-Traversal │ ├── Binary-Tree-Inorder-Traversal.cpp │ └── README.md ├── Binary-Tree-Level-Order-Traversal │ ├── Binary-Tree-Level-Order-Traversal.cpp │ └── README.md ├── Binary-Tree-Maximum-Path-Sum │ └── README.md ├── Binary-Tree-Paths │ └── README.md ├── Binary-Tree-Postorder-Traversal │ ├── Binary-Tree-Postorder-Traversal.cpp │ └── README.md ├── Binary-Tree-Preorder-Traversal │ ├── Binary-Tree-Preorder-Traversal.cpp │ └── README.md ├── Binary-Tree-Right-Side-View │ └── README.md ├── Binary-Tree-Tilt │ └── README.md ├── Binary-Tree-Zigzag-Level-Order-Traversal │ ├── Binary-Tree-Zigzag-Level-Order-Traversal.cpp │ └── README.md ├── Can-Place-Flowers │ └── README.md ├── Clone-Graph │ └── README.md ├── Coin-Change-II │ └── README.md ├── Coin-Change │ ├── Coin-Change.cpp │ └── README.md ├── Combination-Sum-II │ ├── Combination-Sum-II.cpp │ ├── Images │ │ └── DFS2.png │ └── README.md ├── Combination-Sum-III │ └── README.md ├── Combination-Sum │ ├── Combination-Sum.cpp │ ├── Images │ │ └── DFS.png │ └── README.md ├── Combinations │ └── README.md ├── Compress-String-Lcci │ └── README.md ├── Construct-Binary-Tree-From-Ineorder-And-Postorder-Traversal │ ├── Construct-Binary-Tree-From-Ineorder-And-Postorder-Traversal.cpp │ └── README.md ├── Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal │ ├── Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal.cpp │ ├── Images │ │ ├── 1.jpg │ │ └── 2.jpg │ └── README.md ├── Container-With-Most-Water │ ├── Container-With-Most-Water.cpp │ └── README.md ├── Contains-Duplicate │ └── README.md ├── Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List │ ├── Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List.cpp │ └── README.md ├── Convert-Sorted-Array-To-Binary-Search-Tree │ └── README.md ├── Convert-Sorted-List-To-Binary-Search-Tree │ └── README.md ├── Count-And-Say │ ├── Count-And-Say.cpp │ └── README.md ├── Count-Binary-Substrings │ └── README.md ├── Count-Number-Of-Nice-Subarrays │ └── README.md ├── Count-Of-Smaller-Numbers-After-Self │ └── README.md ├── Count-Primes │ └── README.md ├── Count-The-Repetitions │ └── README.md ├── Course-Schedule-II │ └── README.md ├── Crash_Stones │ └── README.md ├── Create-Maximum-Number │ └── README.md ├── Daily-Temperatures │ └── README.md ├── Decode-String │ └── README.md ├── Delete-Node-In-A-Linked-List │ ├── Delete-Node-In-A-Linked-List.cpp │ └── README.md ├── Design-Twitter │ └── README.md ├── Diameter-Of-Binary-Tree │ └── README.md ├── Distribute-Candies-To-People │ ├── Distribute-Candies-To-People.cpp │ └── README.md ├── Divide-Two-Integers │ └── Divide-Two-Integers.cpp ├── Diving-Board │ └── README.md ├── Divisor-Game │ └── README.md ├── Dota2-Senate │ └── README.md ├── Edit-Distance │ └── README.md ├── Evaluate-Reverse-Polish-Notation │ └── README.md ├── Extract_Unique_Integers │ ├── Extract_Unique_Integers.cpp │ └── README.md ├── Find-All-Anagrams-In-A-String │ └── README.md ├── Find-First-And-Last-Position-Of-Element-In-Sorted-Array │ ├── BinarySearch.md │ ├── Find-First-And-Last-Position-Of-Element-In-Sorted-Array.cpp │ ├── Images │ │ ├── left.png │ │ └── right.png │ └── README.md ├── Find-In-Mountain-Array │ └── README.md ├── Find-Majority-Element-Lccii │ └── README.md ├── Find-Median-From-Data-Stream │ ├── Find-Median-From-Data-Stream.cpp │ └── README.md ├── Find-Minimum-In-Rotated-Sorted-Array-II │ └── README.md ├── Find-Minimum-In-Rotated-Sorted-Array │ ├── Find-Minimum-In-Rotated-Sorted-Array.cpp │ └── README.md ├── Find-Mode-In-Binary-Search-Tree │ └── README.md ├── Find-Peak-Element │ └── README.md ├── Find-The-Difference │ └── README.md ├── Find-The-Duplicate-Number │ ├── Find-The-Duplicate-Number.cpp │ └── README.md ├── Find-The-Longest-Substring-Containing-Vowels-In-Even-Counts │ └── README.md ├── Find-Words-That-Can-Be-Formed-By-Characters │ └── README.md ├── First-Missing-Positive │ ├── First-Missing-Positive.cpp │ └── README.md ├── First-Unique-Character-In-A-String │ ├── First-Unique-Character-In-A-String.cpp │ └── README.md ├── Flatten-Binary-Tree-To-Linked-List │ └── README.md ├── Flood-Fill │ └── README.md ├── Four-Divisors │ └── README.md ├── Game-Of-Life │ └── README.md ├── Generate-Parentheses │ └── Generate-Parentheses.cpp ├── Greatest-Common-Divisor-Of-Strings │ └── README.md ├── Group-Anagrams-Lcci │ └── README.md ├── Group-Anagrams │ ├── Group-Anagrams.cpp │ └── README.md ├── Guess-Number-Higher-Or-Lower │ └── README.md ├── H-Index-II │ └── README.md ├── Hand-Of-Straights │ ├── Hand-Of-Straights.cpp │ └── README.md ├── Happy-Number │ └── README.md ├── House-Robber-II │ └── README.md ├── House-Robber-III │ └── README.md ├── House-Robber │ └── README.md ├── How-Many-Numbers-Are-Smaller-Than-The-Current-Number │ └── README.md ├── Implement-Rand10-Using-Rand7 │ └── README.md ├── Implement-Stack-Using-Queues │ ├── Implement-Stack-Using-Queues.cpp │ └── README.md ├── Implement-Strstr │ └── Implement-Strstr.cpp ├── Insert-Intervals │ ├── Insert-Intervals.cpp │ └── README.md ├── Integer-To-Roman │ └── Integer-To-Roman.cpp ├── Intersection-Of-Two-Arrays-II │ └── README.md ├── Intersection-Of-Two-Arrays │ └── README.md ├── Intersection-Of-Two-Linked-Lists │ ├── Intersection-Of-Two-Linked-Lists.cpp │ └── README.md ├── Intersection │ └── README.md ├── Interval-List-Intersections │ └── README.md ├── Invert-Binary-Tree │ ├── Invert-Binary-Tree.cpp │ └── README.md ├── Island-Perimeter │ └── README.md ├── Isomorphic-Strings │ └── README.md ├── Jewels-And-Stones │ └── README.md ├── Jump-Game-II │ └── README.md ├── Jump-Game │ ├── Jump-Game.cpp │ └── README.md ├── Kids-With-The-Greatest-Number-Of-Candies │ └── README.md ├── Kth-Largest-Element-In-A-Stream │ └── README.md ├── Kth-Largest-Element-In-An-Array │ ├── Kth-Largest-Element-In-An-Array.cpp │ └── README.md ├── Kth-Smallest-Element-In-A-Sorted-Matrix │ └── README.md ├── LFU-Cache │ └── README.md ├── LRU-Cache │ └── README.md ├── Largest-Number │ ├── Largest-Number.cpp │ └── README.md ├── Largest-Rectangle-In-Histogram │ └── README.md ├── Last-Stone-Weight-II │ └── README.md ├── Last-Stone-Weight │ └── README.md ├── Lemonade-Change │ └── README.md ├── Length-Of-Last-Word │ ├── Length-Of-Last-Word.cpp │ └── README.md ├── Letter-Combinations-Of-A-Phone-Number │ └── Letter-Combinations-Of-A-Phone-Number.cpp ├── Linked-List-Cycle │ └── README.md ├── Longest-Common-Prefix │ └── Longest-Common-Prefix.cpp ├── Longest-Common-Subsequence │ └── README.md ├── Longest-Consecutive-Sequence │ └── README.md ├── Longest-Continuous-Increasing-Subsequence │ └── README.md ├── Longest-Increasing-Subsequence │ └── README.md ├── Longest-Palindrome │ └── README.md ├── Longest-Palindromic-Subsequence │ └── README.md ├── Longest-Palindromic-Substring │ ├── Longest-Palindromic-Substring.cpp │ └── README.md ├── Longest-Valid-Parentheses │ ├── Longest-Valid-Parentheses.cpp │ └── README.md ├── Longest_Substring_Without_Repeating_Characters │ ├── Longest_Substring_Without_Repeating_Characters.cpp │ └── README.md ├── Lowest-Common-Ancestor-Of-A-Binary-Search-Tree │ └── README.md ├── Lowest-Common-Ancestor-Of-A-Binary-Tree │ └── README.md ├── Majority-Element │ ├── Majority-Element.cpp │ └── README.md ├── Max-Area-Of-Island │ └── README.md ├── Maximal-Rectangle │ └── README.md ├── Maximal-Square │ └── README.md ├── Maximum-Depth-Of-Binary-Tree │ ├── Maximum-Depth-Of-Binary-Tree.cpp │ └── README.md ├── Maximum-Product-Subarray │ └── README.md ├── Maximum-Subarray │ ├── Maximum-Subarray.cpp │ └── README.md ├── Median_Of_Two_Sorted_Arrays │ └── Median_Of_Two_Sorted_Arrays.cpp ├── Merge-Intervals │ ├── Merge-Intervals.cpp │ └── README.md ├── Merge-K-Sorted-Lists │ ├── Merge-K-Sorted-Lists.cpp │ └── README.md ├── Merge-Two-Sorted-Lists │ ├── Merge-Two-Sorted-Lists.cpp │ └── README.md ├── Middle-Of-The-Linked-List │ └── README.md ├── Min-Stack │ ├── Min-Stack.cpp │ └── README.md ├── Minimum-Cost-For-Tickets │ └── README.md ├── Minimum-Depth-Of-Binary-Tree │ └── README.md ├── Minimum-Increment-To-Make-Array-Unique │ └── README.md ├── Minimum-Path-Sum │ └── README.md ├── Minimum-Size-Subarray-Sum │ └── README.md ├── Minimum-Window-Substring │ └── README.md ├── Missing-Number │ ├── Missing-Number.cpp │ └── README.md ├── Monotone-Stack │ └── README.md ├── Move-Zeroes │ ├── Move-Zeroes.cpp │ └── README.md ├── Multiply-Strings │ ├── Image │ │ └── multiply.png │ ├── Multiply-Strings.cpp │ └── README.md ├── N-Queens │ └── README.md ├── Next-Greater-Element-I │ └── README.md ├── Next-Greater-Element-II │ └── README.md ├── Next-Greater-Element-III │ └── README.md ├── Next-Permutation │ ├── Next-Permutation.cpp │ └── README.md ├── Non-Overlapping-Intervals │ └── README.md ├── Number-Of-1-Bits │ ├── Number-Of-1-Bits.cpp │ └── README.md ├── Number-Of-Days-Between-Two-Dates │ ├── Number-Of-Days-Between-Two-Dates.cpp │ └── README.md ├── Number-Of-Digit-One │ ├── Number-Of-Digit-One.cpp │ └── README.md ├── Number-Of-Islands │ └── README.md ├── Palindrome-Linked-List │ └── README.md ├── Palindrome-Number │ └── Palindrome-Number.cpp ├── Palindromic-Substrings │ └── README.md ├── Partition-Array-Into-Three-Parts-With-Equal-Sum │ └── README.md ├── Pascals-Triangle │ └── README.md ├── Path-Sum-II │ ├── Path-Sum-II.cpp │ └── README.md ├── Path-Sum │ ├── Path-Sum.cpp │ └── README.md ├── Peak-Index-In-A-Mountain-Array │ └── README.md ├── Perfect-Squares │ └── README.md ├── Permutation-In-String │ └── README.md ├── Permutation-Sequence │ ├── Permutation-Sequence.cpp │ └── README.md ├── Permutations-II │ ├── Image │ │ └── DFS.png.png │ ├── Permutations-II.cpp │ └── README.md ├── Permutations │ ├── Permutations.cpp │ └── README.md ├── Plus-One │ └── README.md ├── Positions-Of-Large-Groups │ └── README.md ├── PowX-N │ ├── PowX-N.cpp │ └── README.md ├── Product-Of-Array-Except-Self │ └── README.md ├── Rank-Teams-By-Votes │ ├── README.md │ └── Rank-Teams-By-Votes.cpp ├── Recover-A-Tree-From-Preorder-Traversal │ └── README.md ├── Rectangle-Overlap │ └── README.md ├── Regular-Expression-Matching │ ├── README.md │ └── Regular-Expression-Matching.cpp ├── Remove-Boxes │ └── README.md ├── Remove-Duplicate-Letters │ └── README.md ├── Remove-Duplicate-Node │ └── README.md ├── Remove-Duplicates-From-Sorted-Array │ └── Remove-Duplicates-From-Sorted-Array.cpp ├── Remove-Duplicates-From-Sorted-List-II │ ├── README.md │ └── Remove-Duplicates-From-Sorted-List-II.cpp ├── Remove-Duplicates-From-Sorted-List │ ├── README.md │ └── Remove-Duplicates-From-Sorted-List.cpp ├── Remove-Element │ └── Remove-Element.cpp ├── Remove-K-Digits │ └── README.md ├── Remove-Linked-List-Elements │ ├── Images │ │ ├── 1.png │ │ ├── 2.jpg │ │ └── 3.jpg │ ├── README.md │ └── Remove-Linked-List-Elements.cpp ├── Remove-Nth-Node-From-End-Of-List │ ├── README.md │ └── Remove-Nth-Node-From-End-Of-List.cpp ├── Repeated-Substring-Pattern │ └── README.md ├── Restore-Ip-Addresses │ └── README.md ├── Reverse-Integer │ └── Reverse-Integer.cpp ├── Reverse-Linked-List │ ├── README.md │ └── Reverse-Linked-List.cpp ├── Reverse-Nodes-In-K-Group │ ├── README.md │ └── Reverse-Nodes-In-K-Group.cpp ├── Reverse-Words-In-A-String-III │ └── README.md ├── Reverse-Words-In-A-String │ ├── README.md │ └── Reverse-Words-In-A-String.cpp ├── Robot-Return-To-Origin │ └── README.md ├── Roman-To-Integer │ └── Roman-To-Integer.cpp ├── Rotate-Array │ └── README.md ├── Rotate-Image │ ├── Images │ │ └── guilv.JPG │ ├── README.md │ └── Rotate-Image.cpp ├── Rotate-List │ ├── README.md │ └── Rotate-List.cpp ├── Rotate-String │ ├── README.md │ └── Rotate-String.cpp ├── Rotting-Oranges │ ├── README.md │ └── Rotting-Oranges.cpp ├── Russian-Doll-Envelopes │ └── README.md ├── Same-Tree │ └── README.md ├── Score-After-Flipping-Matrix │ └── README.md ├── Search-A-2D-Matrix-II │ ├── README.md │ └── Search-A-2D-Matrix-II.cpp ├── Search-A-2D-Matrix │ ├── README.md │ └── Search-A-2D-Matrix.cpp ├── Search-In-Rotated-Sorted-Array-II │ └── README.md ├── Search-In-Rotated-Sorted-Array │ ├── README.md │ └── Search-In-Rotated-Sorted-Array.cpp ├── Search-Insert-Position │ ├── README.md │ └── Search-Insert-Position.cpp ├── Serialize-And-Deserialize-Binary-Tree │ ├── README.md │ └── Serialize-And-Deserialize-Binary-Tree.cpp ├── Short-Encoding-Of-Words │ └── README.md ├── Single-Number-III │ ├── README.md │ └── Single-Number-III.cpp ├── Single-Number │ ├── README.md │ └── Single-Number.cpp ├── Sort-An-Array │ └── README.md ├── Sorted-Merge-Lcci │ ├── README.md │ └── Sorted-Merge-Lcci.cpp ├── Spiral-Matrix-II │ ├── README.md │ └── Spiral-Matrix-II.cpp ├── Spiral-Matrix │ ├── README.md │ └── Spiral-Matrix.cpp ├── Split-Array-Into-Consecutive-Subsequences │ └── README.md ├── Split-Array-Into-Fibonacci-Sequence │ └── README.md ├── Split-Array-Largest-Sum │ └── README.md ├── Sqrtx │ └── README.md ├── Squares-Of-A-Sorted-Array │ └── README.md ├── String-To-Integer-Atoi │ ├── README.md │ └── String-To-Integer-Atoi.cpp ├── Subarray-Sum-Equals-K │ └── README.md ├── Subarray-Sums-Divisible-By-K │ └── README.md ├── Subsets-II │ └── README.md ├── Subsets │ └── README.md ├── Substring-With-Concatenation-Of-All-Words │ └── Substring-With-Concatenation-Of-All-Words.cpp ├── Subtree-Of-Another-Tree │ └── README.md ├── Sudoku-Solver │ └── README.md ├── Sum-Of-Mutated-Array-Closest-To-Target │ └── README.md ├── Summary-Ranges │ └── README.md ├── Super-Egg-Drop │ ├── 1.jpg │ └── README.md ├── Surface-Area-Of-3D-Shapes │ └── README.md ├── Surrounded-Regions │ └── README.md ├── Swap-Nodes-In-Pairs │ └── Swap-Nodes-In-Pairs.cpp ├── Symmetric-Tree │ ├── README.md │ └── Symmetric-Tree.cpp ├── Task-Scheduler │ └── README.md ├── Test_Calc_Score │ └── README.md ├── The-Masseuse-Lcci │ └── README.md ├── Top-K-Frequent-Elements │ └── README.md ├── Trapping-Rain-Water │ ├── Image │ │ ├── 1.png │ │ ├── 2.png │ │ ├── 3.png │ │ ├── 4.png │ │ ├── 5.png │ │ ├── 6.png │ │ ├── 7.png │ │ ├── 8.png │ │ ├── 9.png │ │ └── rainwatertrap.png │ ├── README.md │ └── Trapping-Rain-Water.cpp ├── Triangle │ └── README.md ├── Two-Sum-II-Input-Array-Is-Sorted │ ├── README.md │ └── Two-Sum-II-Input-Array-Is-Sorted.cpp ├── TwoSum │ └── TwoSum.cpp ├── Ugly-Number-II │ ├── README.md │ └── Ugly-Number-II.cpp ├── Ugly-Number │ ├── README.md │ └── Ugly-Number.cpp ├── Unique-Paths-II │ └── README.md ├── Unique-Paths │ └── README.md ├── Valid-Mountain-Array │ └── README.md ├── Valid-Number │ ├── README.md │ └── Valid-Number.cpp ├── Valid-Palindrome │ └── README.md ├── Valid-Parentheses │ └── Valid-Parentheses.cpp ├── Valid-Sudoku │ └── README.md ├── Validate-Binary-Search-Tree │ └── README.md ├── Validate-Stack-Sequences │ ├── README.md │ └── Validate-Stack-Sequences.cpp ├── Water-And-Jug-Problem │ └── README.md ├── Wiggle-Subsequence │ └── README.md ├── Wildcard-Matching │ ├── README.md │ └── Wildcard-Matching.cpp ├── Word-Break │ └── README.md ├── Word-Ladder-II │ └── README.md ├── Word-Pattern │ └── README.md ├── X-Of-A-Kind-In-A-Deck-Of-Cards │ └── README.md └── Zigzag-Conversion │ └── Zigzag-Conversion.cpp └── python ├── 3Sum-Closest └── 3Sum-Closest.py ├── 3Sum └── 3Sum.py ├── 4Sum └── 4Sum.py ├── Add-Strings └── Add-Strings.py ├── Add_Two_Numbers └── Add_Two_Numbers.py ├── Balanced-Binary-Tree └── Balanced-Binary-Tree.py ├── Binary-Tree-Inorder-Traversal └── Binary-Tree-Inorder-Traversal.py ├── Binary-Tree-Level-Order-Traversal └── Binary-Tree-Level-Order-Traversal.py ├── Binary-Tree-Postorder-Traversal └── Binary-Tree-Postorder-Traversal.py ├── Binary-Tree-Preorder-Traversal └── Binary-Tree-Preorder-Traversal.py ├── Binary-Tree-Zigzag-Level-Order-Traversal └── Binary-Tree-Zigzag-Level-Order-Traversal.py ├── Coin-Change └── Coin-Change.py ├── Combination-Sum-II └── Combination-Sum-II.py ├── Combination-Sum └── Combination-Sum.py ├── Construct-Binary-Tree-From-Ineorder-And-Postorder-Traversal └── Construct-Binary-Tree-From-Ineorder-And-Postorder-Traversal.py ├── Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal └── Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal.py ├── Container-With-Most-Water └── Container-With-Most-Water.py ├── Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List └── Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List.py ├── Count-And-Say └── Count-And-Say.py ├── Delete-Node-In-A-Linked-List └── Delete-Node-In-A-Linked-List.py ├── Diameter-Of-Binary-Tree └── Diameter-Of-Binary-Tree.py ├── Distribute-Candies-To-People └── Distribute-Candies-To-People.py ├── Divide-Two-Integers └── Divide-Two-Integers.py ├── Find-First-And-Last-Position-Of-Element-In-Sorted-Array └── Find-First-And-Last-Position-Of-Element-In-Sorted-Array.py ├── Find-Median-From-Data-Stream └── Find-Median-From-Data-Stream.py ├── Find-Minimum-In-Rotated-Sorted-Array └── Find-Minimum-In-Rotated-Sorted-Array.py ├── Find-The-Duplicate-Number └── Find-The-Duplicate-Number.py ├── First-Missing-Positive └── First-Missing-Positive.py ├── First-Unique-Character-In-A-String └── First-Unique-Character-In-A-String.py ├── Generate-Parentheses └── Generate-Parentheses.py ├── Group-Anagrams └── Group-Anagrams.py ├── Hand-Of-Straights └── Hand-Of-Straights.py ├── Implement-Stack-Using-Queues └── Implement-Stack-Using-Queues.py ├── Implement-Strstr └── Implement-Strstr.py ├── Insert-Intervals └── Insert-Intervals.py ├── Integer-To-Roman └── Integer-To-Roman.py ├── Intersection-Of-Two-Linked-Lists └── Intersection-Of-Two-Linked-Lists.py ├── Invert-Binary-Tree └── Invert-Binary-Tree.py ├── Jump-Game └── Jump-Game.py ├── Kth-Largest-Element-In-An-Array └── Kth-Largest-Element-In-An-Array.py ├── Largest-Number └── Largest-Number.py ├── Length-Of-Last-Word └── Length-Of-Last-Word.py ├── Letter-Combinations-Of-A-Phone-Number └── Letter-Combinations-Of-A-Phone-Number.py ├── Longest-Common-Prefix └── Longest-Common-Prefix.py ├── Longest-Palindromic-Substring └── Longest-Palindromic-Substring.py ├── Longest-Valid-Parentheses └── Longest-Valid-Parentheses.py ├── Longest_Substring_Without_Repeating_Characters └── Longest_Substring_Without_Repeating_Characters.py ├── Majority-Element └── Majority-Element.py ├── Maximum-Depth-Of-Binary-Tree └── Maximum-Depth-Of-Binary-Tree.py ├── Maximum-Subarray └── Maximum-Subarray.py ├── Median_Of_Two_Sorted_Arrays └── Median_Of_Two_Sorted_Arrays.py ├── Merge-Intervals └── Merge-Intervals.py ├── Merge-K-Sorted-Lists └── Merge-K-Sorted-Lists.py ├── Merge-Two-Sorted-Lists └── Merge-Two-Sorted-Lists.py ├── Min-Stack └── Min-Stack.py ├── Missing-Number └── Missing-Number.py ├── Move-Zeroes └── Move-Zeroes.py ├── Multiply-Strings └── Multiply-Strings.py ├── Next-Permutation └── Next-Permutation.py ├── Nth-Digit └── Nth-Digit.py ├── Number-Of-1-Bits └── Number-Of-1-Bits.py ├── Number-Of-Digit-One └── Number-Of-Digit-One.py ├── Palindrome-Number └── Palindrome-Number.py ├── Path-Sum-II └── Path-Sum-II.py ├── Path-Sum └── Path-Sum.py ├── Permutation-Sequence └── Permutation-Sequence.py ├── Permutations-II └── Permutations-II.py ├── Permutations └── Permutations.py ├── PowX-N └── PowX-N.py ├── Regular-Expression-Matching └── Regular-Expression-Matching.py ├── Remove-Duplicates-From-Sorted-Array └── Remove-Duplicates-From-Sorted-Array.py ├── Remove-Duplicates-From-Sorted-List-II └── Remove-Duplicates-From-Sorted-List-II.py ├── Remove-Duplicates-From-Sorted-List └── Remove-Duplicates-From-Sorted-List.py ├── Remove-Element └── Remove-Element.py ├── Remove-Linked-List-Elements └── Remove-Linked-List-Elements.py ├── Remove-Nth-Node-From-End-Of-List └── Remove-Nth-Node-From-End-Of-List.py ├── Reverse-Integer └── Reverse-Integer.py ├── Reverse-Linked-List └── Reverse-Linked-List.py ├── Reverse-Nodes-In-K-Group └── Reverse-Nodes-In-K-Group.py ├── Reverse-Words-In-A-String └── Reverse-Words-In-A-String.py ├── Roman-To-Integer └── Roman-To-Integer.py ├── Rotate-Image └── Rotate-Image.py ├── Rotate-List └── Rotate-List.py ├── Rotate-String └── Rotate-String.py ├── Rotting-Oranges └── Rotting-Oranges.py ├── Search-A-2D-Matrix-II └── Search-A-2D-Matrix-II.py ├── Search-A-2D-Matrix └── Search-A-2D-Matrix.py ├── Search-In-Rotated-Sorted-Array └── Search-In-Rotated-Sorted-Array.py ├── Search-Insert-Position └── Search-Insert-Position.py ├── Serialize-And-Deserialize-Binary-Tree └── Serialize-And-Deserialize-Binary-Tree.py ├── Single-Number-III └── Single-Number-III.py ├── Single-Number └── Single-Number.py ├── Sorted-Merge-Lcci └── Sorted-Merge-Lcci.py ├── Spiral-Matrix-II └── Spiral-Matrix-II.py ├── Spiral-Matrix └── Spiral-Matrix.py ├── String-To-Integer-Atoi └── String-To-Integer-Atoi.py ├── Substring-With-Concatenation-Of-All-Words └── Substring-With-Concatenation-Of-All-Words.py ├── Swap-Nodes-In-Pairs └── Swap-Nodes-In-Pairs.py ├── Symmetric-Tree └── Symmetric-Tree.py ├── Trapping-Rain-Water └── Trapping-Rain-Water.py ├── Two-Sum-II-Input-Array-Is-Sorted └── Two-Sum-II-Input-Array-Is-Sorted.py ├── Two_Sum └── Two_Sum.py ├── Ugly-Number-II └── Ugly-Number-II.py ├── Ugly-Number └── Ugly-Number.py ├── Valid-Number └── Valid-Number.py ├── Valid-Parentheses └── Valid-Parentheses.py ├── Validate-Stack-Sequences └── Validate-Stack-Sequences.py ├── Wildcard-Matching └── Wildcard-Matching.py └── Zigzag-Conversion └── Zigzag-Conversion.py /cpp/3Sum-Closest/3Sum-Closest.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/3sum-closest/ 2 | /// Author : bryce 3 | /// Time : 2019-11-07 4 | 5 | 6 | /* 7 | 与上一题三个数求和类似,需要定义一个变量记录差的绝对值,再将数组排序,然后开始遍历数组,先确定一个数, 8 | 然后剩下两个从左右两端,滑动来寻找另外两个数,每确定两个数,求出三个数之和,然后算和给定值的差的绝对值存在新的变量中,然后在和之前比较更新差值和结果 9 | */ 10 | 11 | class Solution { 12 | public: 13 | int threeSumClosest(vector& nums, int target) { 14 | int res = nums[0] + nums[1] + nums[2]; 15 | int diff = abs(res - target); 16 | int n = nums.size(); 17 | sort(nums.begin(),nums.end()); 18 | for (int k = 0; k < n - 2; k++) 19 | { 20 | int i = k + 1; int j = n - 1; 21 | while(i < j) 22 | { 23 | int sum = nums[k] + nums[i] + nums[j]; 24 | int newDiff = abs(sum - target); 25 | if (diff > newDiff) 26 | { 27 | diff = newDiff; 28 | res = sum; 29 | } 30 | if (sum > target) 31 | j--; 32 | else 33 | i++; 34 | } 35 | } 36 | return res; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /cpp/Add-Strings/Add-Strings.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode.com/problems/add-two-numbers/description/ 2 | /// Author : bryce 3 | /// Time : 2019-12-5 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | 11 | class Solution { 12 | public: 13 | string addStrings(string num1, string num2) { 14 | int i = num1.size()-1; 15 | int j = num2.size()-1; 16 | int carry = 0; 17 | string res; 18 | while (i>=0 || j>=0) 19 | { 20 | int temp = 0; 21 | if (i<0) 22 | temp = num2[j]-'0'+carry; 23 | if (j<0) 24 | temp = num1[i]-'0'+carry; 25 | else 26 | temp = num1[i] - '0' + num2[j] -'0' + carry; 27 | carry = temp / 10; 28 | res.insert(res.begin(),temp%10+'0'); 29 | i--; 30 | j--; 31 | } 32 | if (carry>0) 33 | res.insert(res.begin(),carry+'0'); 34 | return res; 35 | } 36 | }; 37 | 38 | { 39 | string num1 = "9"; 40 | string num2 = "9"; 41 | string res; 42 | res = Solution().multiply(num1,num2); 43 | cout << res << endl; 44 | system ("pause"); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /cpp/Assign-Cookies/README.md: -------------------------------------------------------------------------------- 1 | ### 分发饼干 2 | 3 | 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 4 | 5 | 对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 6 | 7 | 示例: 8 | 9 | ``` 10 | 输入: g = [1,2,3], s = [1,1] 11 | 输出: 1 12 | 解释: 13 | 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 14 | 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 15 | 所以你应该输出1。 16 | 17 | 输入: g = [1,2], s = [1,2,3] 18 | 输出: 2 19 | 解释: 20 | 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 21 | 你拥有的饼干数量和尺寸都足以让所有孩子满足。 22 | 所以你应该输出2. 23 | ``` 24 | 25 | 26 | ```c++ 27 | class Solution { 28 | public: 29 | int findContentChildren(vector& g, vector& s) { 30 | int res = 0; 31 | int m = g.size(), n = s.size(); 32 | if (n == 0 || m == 0) return res; 33 | sort(g.begin(), g.end()); 34 | sort(s.begin(), s.end()); 35 | int i = 0, j = 0; 36 | while (i < m && j < n) { 37 | if (s[j] >= g[i]) { 38 | res++; 39 | i++; 40 | } 41 | j++; 42 | } 43 | return res; 44 | } 45 | }; 46 | ``` 47 | -------------------------------------------------------------------------------- /cpp/Balanced-Binary-Tree/Balanced-Binary-Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isBalanced(TreeNode* root) { 4 | if (root == NULL) 5 | return true; 6 | int left = TreeDepth(root->left); 7 | int right = TreeDepth(root->right); 8 | if (left - right >1 || left -right < -1) 9 | return false; 10 | return isBalanced(root->left) && isBalanced(root->right); 11 | } 12 | int TreeDepth(TreeNode* root) 13 | { 14 | if (root==NULL) 15 | return 0; 16 | int left = TreeDepth(root->left); 17 | int right = TreeDepth(root->right); 18 | return max(left, right) +1; 19 | } 20 | }; 21 | 22 | 23 | class Solution { 24 | public: 25 | bool isBalanced(TreeNode* root) { 26 | if (root == NULL) 27 | return true; 28 | int depth = 0; 29 | return helper(root, depth); 30 | } 31 | bool helper(TreeNode* root, int & depth) 32 | { 33 | if (root==NULL) 34 | { 35 | depth = 0; 36 | return true; 37 | } 38 | int left,right; 39 | if (helper(root->left, left) && helper(root->right, right) && abs(left-right) <=1) 40 | { 41 | depth = max(left, right) +1; 42 | return true; 43 | } 44 | return false; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /cpp/Best-Sightseeing-Pair/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 最佳观光组合 2 | 3 | 给定正整数数组 A,A[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的距离为 j - i。 4 | 5 | 一对景点(i < j)组成的观光组合的得分为(A[i] + A[j] + i - j):景点的评分之和减去它们两者之间的距离。 6 | 7 | 返回一对观光景点能取得的最高分。 8 | 9 | **示例 :** 10 | ``` 11 | 输入:[8,1,5,2,6] 12 | 输出:11 13 | 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 14 | ``` 15 | 16 | - 2 <= A.length <= 50000 17 | - 1 <= A[i] <= 1000 18 | 19 | # 解题思路: 20 | 21 | 注意i& A) { 49 | int res = 0; 50 | int n = A.size(); 51 | int pre_max = A[0] + 0; 52 | for (int j=1;j& prices) { 4 | int n = prices.size(); 5 | if (n<=1) return 0; 6 | int res = 0; 7 | int min_price = prices[0]; 8 | for (int i=0;i inorderTraversal(TreeNode* root) { 4 | vector res; 5 | if (root==NULL) 6 | return res; 7 | helper(root,res); 8 | return res; 9 | } 10 | void helper(TreeNode* root, vector &res) 11 | { 12 | if (root==NULL) 13 | return; 14 | helper(root->left,res); 15 | res.push_back(root->val); 16 | helper(root->right,res); 17 | } 18 | }; 19 | 20 | 21 | class Solution { 22 | public: 23 | vector inorderTraversal(TreeNode* root) { 24 | vector res; 25 | if (root==NULL) 26 | return res; 27 | stack s; 28 | TreeNode* p = root; 29 | while (!s.empty()||p!=NULL) 30 | { 31 | while(p!=NULL) 32 | { 33 | s.push(p); 34 | p = p->left; 35 | } 36 | p = s.top(); 37 | s.pop(); 38 | res.push_back(p->val); 39 | p = p->right; 40 | } 41 | return res; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /cpp/Binary-Tree-Paths/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 二叉树的所有路径 2 | 3 | 给定一个二叉树,返回所有从根节点到叶子节点的路径。 4 | 5 | 说明: 叶子节点是指没有子节点的节点。 6 | 7 | **示例 :** 8 | ``` 9 | 输入: 10 | 11 | 1 12 | / \ 13 | 2 3 14 | \ 15 | 5 16 | 17 | 输出: ["1->2->5", "1->3"] 18 | 19 | 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 20 | ``` 21 | 22 | # 解题思路: 23 | 24 | 前序遍历即可 25 | 26 | # 时间复杂度: 27 | O(n) 28 | 29 | # 空间复杂度 30 | O(1) 31 | 32 | # 代码 33 | 34 | ### 方法一: 注意out不要加引用,右值引用 35 | ```c++ 36 | /** 37 | * Definition for a binary tree node. 38 | * struct TreeNode { 39 | * int val; 40 | * TreeNode *left; 41 | * TreeNode *right; 42 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 43 | * }; 44 | */ 45 | class Solution { 46 | public: 47 | vector binaryTreePaths(TreeNode* root) { 48 | vector path; 49 | string out = ""; 50 | dfs(root, out, path); 51 | return path; 52 | } 53 | void dfs(TreeNode* root, string out, vector &path) 54 | { 55 | if (root==NULL) return; 56 | out+=to_string(root->val); 57 | if (root->left==NULL && root->right==NULL) // 叶子节点 58 | { 59 | path.push_back(out); 60 | return; 61 | } 62 | dfs(root->left,out + "->",path); 63 | dfs(root->right,out + "->",path); 64 | } 65 | }; 66 | ``` 67 | -------------------------------------------------------------------------------- /cpp/Binary-Tree-Postorder-Traversal/Binary-Tree-Postorder-Traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector postorderTraversal(TreeNode* root) { 4 | vector res; 5 | if (root==NULL) 6 | return res; 7 | helper(root,res); 8 | return res; 9 | } 10 | void helper(TreeNode* root, vector &res) 11 | { 12 | if (root==NULL) 13 | return; 14 | helper(root->left,res); 15 | helper(root->right,res); 16 | res.push_back(root->val); 17 | } 18 | }; 19 | 20 | 21 | class Solution { 22 | public: 23 | vector postorderTraversal(TreeNode* root) { 24 | vector res; 25 | if (root==NULL) 26 | return res; 27 | stack s; 28 | s.push(root); 29 | while (!s.empty()) 30 | { 31 | TreeNode* node = s.top(); 32 | s.pop(); 33 | if (node->left) 34 | s.push(node->left); 35 | if (node->right) 36 | s.push(node->right); 37 | res.push_back(node->val); 38 | } 39 | reverse(res.begin(),res.end()); 40 | return res; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /cpp/Binary-Tree-Tilt/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 二叉树的坡度 2 | 3 | 一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。 4 | 5 | 整个树的坡度就是其所有节点的坡度之和。 6 | 7 | ## 题目描述: 8 | 给定一个二叉树,计算整个树的坡度。 9 | 10 | **示例:** 11 | 给定二叉树 12 | ``` 13 | 输入: 14 | 1 15 | / \ 16 | 2 3 17 | 输出:1 18 | 解释: 19 | 结点 2 的坡度: 0 20 | 结点 3 的坡度: 0 21 | 结点 1 的坡度: |2-3| = 1 22 | 树的坡度 : 0 + 0 + 1 = 1 23 | ``` 24 | 25 | # 解题思路: 26 | 27 | 此题与二叉树的直径类似,需要灵活运用dfs 28 | 29 | # 时间复杂度: 30 | O(n) 31 | # 空间复杂度 32 | O(n) 33 | # 代码 34 | 35 | ### 36 | ```c++ 37 | /** 38 | * Definition for a binary tree node. 39 | * struct TreeNode { 40 | * int val; 41 | * TreeNode *left; 42 | * TreeNode *right; 43 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 44 | * }; 45 | */ 46 | class Solution { 47 | public: 48 | int findTilt(TreeNode* root) { 49 | if (root == NULL) return 0; 50 | dfs(root); 51 | return res; 52 | } 53 | int dfs(TreeNode* root) { 54 | if (root == NULL) return 0; 55 | int left =dfs(root->left); 56 | int right = dfs(root->right); 57 | res += abs(left - right); 58 | return root->val + left + right; // 坡度的定义,左右子树节点的和 59 | } 60 | private: 61 | int res = 0; 62 | }; 63 | ``` 64 | -------------------------------------------------------------------------------- /cpp/Can-Place-Flowers/README.md: -------------------------------------------------------------------------------- 1 | #### 种花问题 2 | 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 3 | 4 | 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。 5 | 6 | 示例 1: 7 | 8 | ``` 9 | 输入: flowerbed = [1,0,0,0,1], n = 1 10 | 输出: True 11 | 12 | 输入: flowerbed = [1,0,0,0,1], n = 2 13 | 输出: False 14 | ``` 15 | 16 | 17 | ### 思路: 18 | 在 flowerbed 数组两端各增加一个 0, 这样处理的好处在于不用考虑边界条件,任意位置处只要连续出现三个 0 就可以栽上一棵花。 19 | ```c++ 20 | class Solution { 21 | public: 22 | bool canPlaceFlowers(vector& flowerbed, int n) { 23 | vector tmp; 24 | tmp.push_back(0); 25 | for(int a : flowerbed){ 26 | tmp.push_back(a); 27 | } 28 | tmp.push_back(0); 29 | int res = 0; 30 | for (int i=1;i=n; 37 | } 38 | }; 39 | ``` 40 | -------------------------------------------------------------------------------- /cpp/Coin-Change/Coin-Change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | int res = -1; 5 | vector dp(amount+1, amount+1); 6 | dp[0] = 0; 7 | int n = dp.size(); 8 | for (int i = 0;icoin(面值)的时候才有解 13 | if (i - coin < 0) 14 | { 15 | continue; 16 | } 17 | dp[i] = min(dp[i], 1+dp[i-coin]); 18 | } 19 | } 20 | if (dp[amount] == amount+1) 21 | return -1; 22 | else 23 | res = dp[amount]; 24 | return res; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /cpp/Combination-Sum-II/Images/DFS2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Combination-Sum-II/Images/DFS2.png -------------------------------------------------------------------------------- /cpp/Combination-Sum-III/README.md: -------------------------------------------------------------------------------- 1 | ## 题目描述 组合总和 III 2 | 3 | 4 | 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。 5 | 6 | 说明: 7 | 8 | - 所有数字都是正整数。 9 | - 解集不能包含重复的组合。 10 | 11 | 12 | 示例: 13 | ``` 14 | 输入: k = 3, n = 7 15 | 输出: [[1,2,4]] 16 | 17 | 输入: k = 3, n = 9 18 | 输出: [[1,2,6], [1,3,5], [2,3,4]] 19 | ``` 20 | 21 | 思路:标准的dfs模板 22 | 23 | ```c++ 24 | class Solution { 25 | public: 26 | vector> combinationSum3(int k, int n) { 27 | if (k == 0) return res; 28 | dfs(n,0,1,k); 29 | return res; 30 | } 31 | void dfs(int num, int u, int start, int k) { 32 | if (num < 0) return; 33 | if (num==0 && u==k) { 34 | res.push_back(out); 35 | return; 36 | } 37 | for (int i = start; i <= 9; i++) { 38 | out.push_back(i); 39 | dfs(num - i, u+1, i + 1, k); 40 | out.pop_back(); 41 | } 42 | } 43 | private: 44 | vector> res; 45 | vector out; 46 | }; 47 | ``` 48 | -------------------------------------------------------------------------------- /cpp/Combination-Sum/Combination-Sum.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/combination-sum/ 2 | /// Author : bryce 3 | /// Time : 2019-11-30 4 | 5 | 6 | #include 7 | #include 8 | using namespace std; 9 | class Solution { 10 | public: 11 | vector> combinationSum(vector& candidates, int target) { 12 | vector> res; 13 | vector out; 14 | if (candidates.empty()) 15 | return res; 16 | DFS(candidates, target, 0, out, res); 17 | return res; 18 | } 19 | 20 | void DFS(vector& candidates, int target, int start, vector& out, vector>& res) 21 | { 22 | if (target < 0) return; 23 | if (target == 0) 24 | { 25 | res.push_back(out); 26 | return; 27 | } 28 | int n = candidates.size(); 29 | for (int i = start; i candidates = {2,3,6,7}; 42 | vector> res = Solution().combinationSum(candidates,target); 43 | cout << res[0][0]<> combine(int n, int k) { 23 | if (n < k || k <=0 ) return res; 24 | dfs(n, k, 1); 25 | return res; 26 | } 27 | void dfs(int n, int k, int start) { 28 | if (path.size() == k) { 29 | res.push_back(path); 30 | } 31 | for (int i = start; i <= n; i++) { 32 | path.push_back(i); 33 | dfs(n, k, i+1); 34 | path.pop_back(); 35 | } 36 | } 37 | private: 38 | vector> res; 39 | vector path; 40 | }; 41 | ``` 42 | -------------------------------------------------------------------------------- /cpp/Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal/Images/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal/Images/1.jpg -------------------------------------------------------------------------------- /cpp/Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal/Images/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal/Images/2.jpg -------------------------------------------------------------------------------- /cpp/Container-With-Most-Water/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 盛最多水的容器 2 | 3 | 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 4 | 5 | 说明:你不能倾斜容器,且 n 的值至少为 2。 6 | 7 | ![](https://aliyun-lc-upload.oss-cn-hangzhou.aliyuncs.com/aliyun-lc-upload/uploads/2018/07/25/question_11.jpg) 8 | 图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 9 | 10 | # 解题思路: 11 | - 暴力法 12 | 13 | - 双指针 14 | 15 | # 时间复杂度: 16 | 最优O(n) 17 | # 空间复杂度 18 | O(1) 19 | 20 | # 代码 21 | 22 | ## [C++](https://github.com/bryceustc/LeetCode_Note/blob/master/cpp/Container-With-Most-Water/Container-With-Most-Water.cpp): 23 | 24 | ### 双指针 25 | ```c++ 26 | class Solution { 27 | public: 28 | int maxArea(vector& height) { 29 | int n = height.size(); 30 | if (n<2) return 0; 31 | int res = 0; 32 | int i=0,j=n-1; 33 | while(i& nums) { 30 | set s; 31 | for (int &num: nums) { 32 | if(s.count(num)) return true; 33 | s.insert(num); 34 | } 35 | return false; 36 | } 37 | }; 38 | ``` 39 | -------------------------------------------------------------------------------- /cpp/Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List/Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* treeToDoublyList(Node* root) { 4 | if (root==NULL) 5 | return NULL; 6 | Node* pre = NULL; 7 | helper(root, pre); 8 | Node* head =pre; 9 | while(head && head->left) 10 | { 11 | head = head->left; 12 | } 13 | pre -> right = head; 14 | head->left = pre; 15 | return head; 16 | } 17 | void helper(Node* cur, Node* &pre) 18 | { 19 | if (cur==NULL) 20 | return; 21 | helper(cur->left, pre); 22 | cur->left = pre; 23 | if (pre!=NULL) 24 | pre->right = cur; 25 | pre = cur; 26 | helper(cur->right, pre); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /cpp/Convert-Sorted-Array-To-Binary-Search-Tree/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 将有序数组转换为二叉搜索树 2 | 3 | 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。 4 | 5 | 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 6 | 7 | 8 | **示例 :** 9 | ``` 10 | 给定有序数组: [-10,-3,0,5,9], 11 | 12 | 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树: 13 | 14 | 0 15 | / \ 16 | -3 9 17 | / / 18 | -10 5 19 | ``` 20 | 21 | # 解题思路: 22 | 1. 将合并 k个链表的问题转化成合并 2 个链表 k-1次 23 | 24 | 2. 归并排序的思想,分治。 25 | 26 | - 将 k个链表配对并将同一对中的链表合并 27 | - 第一轮合并以后, k 个链表被合并成了 k/2个链表,平均长度为 2N/k ,然后是 k/4个链表, k/8个链表等等 28 | - 重复这一过程,直到我们得到了最终的有序链表 29 | 30 | 因此,我们在每一次配对合并的过程中都会遍历几乎全部N个节点,并重复这一过程 31 | # 时间复杂度: 32 | O(n) 33 | # 空间复杂度 34 | O(logn) 递归需要O(logn)栈空间 35 | 36 | # 代码 37 | ```c++ 38 | /** 39 | * Definition for a binary tree node. 40 | * struct TreeNode { 41 | * int val; 42 | * TreeNode *left; 43 | * TreeNode *right; 44 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 45 | * }; 46 | */ 47 | class Solution { 48 | public: 49 | TreeNode* sortedArrayToBST(vector& nums) { 50 | int n = nums.size(); 51 | return helper(nums, 0, n - 1); 52 | } 53 | 54 | TreeNode* helper(vector &nums, int l , int r) { 55 | if (l > r) return NULL; 56 | int mid = l + (r - l ) / 2; 57 | TreeNode* root = new TreeNode(nums[mid]); 58 | root->left = helper(nums, l, mid - 1); 59 | root->right = helper(nums, mid + 1, r); 60 | return root; 61 | } 62 | }; 63 | ``` 64 | -------------------------------------------------------------------------------- /cpp/Count-And-Say/Count-And-Say.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/count-and-say/ 2 | /// Author : bryce 3 | /// Time : 2019-11-29 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | string countAndSay(int n) { 12 | if (n==0) return ""; 13 | string res = "1"; 14 | while(--n) 15 | { 16 | string temp = ""; 17 | for (int i=0;i isPrime(n, 1); 58 | // 从二开始,0 和 1 都不算是质数 59 | for (int i = 2; i < n; i++) { 60 | if (isPrime[i]) { 61 | res++; 62 | // 把i的倍数的数排除,比如i = 2, 4,6,8,10...都要排除 63 | for (int j = i + i; j < n; j+=i) { 64 | // 排除当前质数的倍数 65 | isPrime[j] = 0; 66 | } 67 | } 68 | } 69 | return res; 70 | } 71 | }; 72 | ``` 73 | -------------------------------------------------------------------------------- /cpp/Daily-Temperatures/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 每日温度 2 | 3 | 根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。 4 | 5 | 6 | 例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。 7 | 8 | 9 | # 解题思路: 10 | 单调不增栈 11 | 12 | # 代码 13 | 14 | ### 单调不增栈 15 | ```c++ 16 | class Solution { 17 | public: 18 | vector dailyTemperatures(vector& T) { 19 | int n = T.size(); 20 | int i =0; 21 | vector res(n,0); 22 | stack s; 23 | while(i distributeCandies(int candies, int num_people) { 4 | vector res(num_people,0); 5 | int i =0; 6 | while (candies>i) 7 | { 8 | res[i%num_people] += i+1; 9 | candies-=i+1; 10 | i++; 11 | } 12 | res[i%num_people] += candies; 13 | return res; 14 | } 15 | }; 16 | 17 | class Solution { 18 | public: 19 | vector distributeCandies(int candies, int num_people) { 20 | int n = num_people; 21 | // how many people received complete gifts 22 | int p = (int)(sqrt(2 * candies + 0.25) - 0.5); 23 | int remaining = (int)(candies - (p + 1) * p * 0.5); 24 | int rows = p / n, cols = p % n; 25 | 26 | vector d(n, 0); 27 | for (int i = 0; i < n; ++i) { 28 | // complete rows 29 | d[i] = (i + 1) * rows + (int)(rows * (rows - 1) * 0.5) * n; 30 | // cols in the last row 31 | if (i < cols) d[i] += i + 1 + rows * n; 32 | } 33 | // remaining candies 34 | d[cols] += remaining; 35 | return d; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /cpp/Diving-Board/README.md: -------------------------------------------------------------------------------- 1 | 注意k=0和shorter==longer这两种特殊情况 2 | 3 | 最短: shorter * k 4 | 5 | 第二短: shorter * k + (longer - shorter) * 1 6 | 7 | 第三短: shorter * k + (longer - shorter) * 2 8 | 9 | ... 10 | 11 | 最长:shorter * k + (longer - shorter) * k 12 | 13 | 结束 14 | ```c++ 15 | class Solution { 16 | public: 17 | vector divingBoard(int shorter, int longer, int k) { 18 | if (k==0) return {}; 19 | if (shorter==longer) return {shorter*k}; 20 | vector res(k+1, 0); 21 | res[0] = shorter*k; 22 | for (int i = 1; i < k+1; ++i) { 23 | res[i] = res[i-1] + longer - shorter; 24 | } 25 | return res; 26 | } 27 | }; 28 | ``` 29 | -------------------------------------------------------------------------------- /cpp/Divisor-Game/README.md: -------------------------------------------------------------------------------- 1 | ### 题目描述 2 | 3 | 除数博弈 4 | 5 | 爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。 6 | 7 | 最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作: 8 | 9 | 选出任一 x,满足 0 < x < N 且 N % x == 0 。 10 | 用 N - x 替换黑板上的数字 N 。 11 | 如果玩家无法执行这些操作,就会输掉游戏。 12 | 13 | 只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 False。假设两个玩家都以最佳状态参与游戏。 14 | 15 | 示例1: 16 | ``` 17 | 输入:2 18 | 输出:true 19 | 解释:爱丽丝选择 1,鲍勃无法进行操作。 20 | ``` 21 | 22 | 示例2: 23 | ``` 24 | 输入:3 25 | 输出:false 26 | 解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。 27 | ``` 28 | 29 | 代码: 30 | ```c++ 31 | class Solution { 32 | public: 33 | bool divisorGame(int N) { 34 | return (N & 1) == 0; 35 | } 36 | }; 37 | ``` 38 | -------------------------------------------------------------------------------- /cpp/Extract_Unique_Integers/Extract_Unique_Integers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int input; 5 | scanf("%d", &input); 6 | int res = 0; 7 | int m[10] = {0}; 8 | int n = 0; 9 | while(input) 10 | { 11 | n = input%10; 12 | if (m[n]==0) 13 | { 14 | m[n]++; 15 | res = res*10 + n; 16 | } 17 | input/=10; 18 | } 19 | printf("%d",res); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /cpp/Find-First-And-Last-Position-Of-Element-In-Sorted-Array/Images/left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Find-First-And-Last-Position-Of-Element-In-Sorted-Array/Images/left.png -------------------------------------------------------------------------------- /cpp/Find-First-And-Last-Position-Of-Element-In-Sorted-Array/Images/right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Find-First-And-Last-Position-Of-Element-In-Sorted-Array/Images/right.png -------------------------------------------------------------------------------- /cpp/Find-Majority-Element-Lccii/README.md: -------------------------------------------------------------------------------- 1 | ## 题目描述 2 | 数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案。 3 | 4 | 示例1: 5 | ``` 6 | 输入:[1,2,5,9,5,9,5,5,5] 7 | 输出:5 8 | ``` 9 | 10 | 示例2: 11 | ``` 12 | 输入:[3,2] 13 | 输出:-1 14 | ``` 15 | 16 | ## 解题思路 17 | 摩尔投票法 18 | 由于题目要求时间复杂度 O(n)和空间复杂度 O(1),因此符合要求的解法只有 Boyer-Moore投票算法。 19 | 20 | Boyer-Moore投票算法的基本思想是:在每一轮投票过程中,从数组中删除两个不同的元素,直到投票过程无法继续,此时数组为空或者数组中剩下的元素都相等。 21 | 22 | - 如果数组为空,则数组中不存在主要元素; 23 | - 如果数组中剩下的元素都相等,则数组中剩下的元素可能为主要元素。 24 | 25 | ## 代码 26 | 27 | ```c++ 28 | class Solution { 29 | public: 30 | int majorityElement(vector& nums) { 31 | int res = -1; 32 | int cnt = 0; 33 | for (int num : nums) { 34 | if (cnt == 0) { 35 | res = num; 36 | } 37 | if (num == res) { 38 | cnt++; 39 | } else { 40 | cnt--; 41 | } 42 | } 43 | cnt = 0; 44 | for (int num : nums) { 45 | if (num == res) { 46 | cnt++; 47 | } 48 | } 49 | if (cnt > nums.size() / 2) return res; 50 | return -1; 51 | } 52 | }; 53 | ``` 54 | -------------------------------------------------------------------------------- /cpp/Find-Minimum-In-Rotated-Sorted-Array-II/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 寻找旋转排序数组中的最小值 II 2 | 3 | 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 4 | 5 | ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 6 | 7 | 请找出其中最小的元素。 8 | 9 | 注意数组中可能存在重复的元素。 10 | 11 | **示例 1:** 12 | ``` 13 | 输入: [3,4,5,1,2] 14 | 输出: 1 15 | ``` 16 | 17 | **示例 2:** 18 | ``` 19 | 输入: [4,5,6,7,0,1,2] 20 | 输出: 0 21 | ``` 22 | 23 | 24 | # 解题思路: 25 | 26 | 使用二分查找,如果中间元素大于尾元素,``l=mid+1``,时间复杂度为O(logn) 27 | 28 | # 时间复杂度: 29 | 30 | O(logn) 31 | 32 | # 空间复杂度 33 | O(1) 34 | 35 | # 代码 36 | ```c++ 37 | class Solution { 38 | public: 39 | int findMin(vector& nums) { 40 | int n = nums.size(); 41 | int l = 0; 42 | int r = n - 1; 43 | while (l < r) { 44 | int mid = l + (r -l) / 2; 45 | if (nums[mid] > nums[r]) { 46 | l = mid + 1; 47 | } else if (nums[mid] < nums[r]) { 48 | r = mid; 49 | } else { 50 | r--; 51 | } 52 | } 53 | return nums[l]; 54 | } 55 | }; 56 | ``` 57 | -------------------------------------------------------------------------------- /cpp/Find-Mode-In-Binary-Search-Tree/README.md: -------------------------------------------------------------------------------- 1 | ###题目描述 寻找二叉搜索树的众数 2 | 3 | 暴力方法: 4 | ```c++ 5 | /** 6 | * Definition for a binary tree node. 7 | * struct TreeNode { 8 | * int val; 9 | * TreeNode *left; 10 | * TreeNode *right; 11 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | vector findMode(TreeNode* root) { 17 | if (root == NULL) return res; 18 | dfs(root); 19 | int cnt = 1; 20 | int count = 0; 21 | unordered_map m; 22 | int a = nums[0]; 23 | m[nums[0]] = 1; 24 | for (int i = 1; i < nums.size(); i++) { 25 | if (nums[i] == a) { 26 | cnt++; 27 | } 28 | else { 29 | a = nums[i]; 30 | count = max(count, cnt); 31 | cnt = 1; 32 | } 33 | m[nums[i]]++; 34 | } 35 | count = max(count, cnt); 36 | for (auto &p : m) { 37 | if (p.second == count) res.push_back(p.first); 38 | } 39 | return res; 40 | } 41 | void dfs(TreeNode* root) { 42 | if (root == NULL) return; 43 | dfs(root->left); 44 | nums.push_back(root->val); 45 | dfs(root->right); 46 | } 47 | private: 48 | vector nums; 49 | vector res; 50 | }; 51 | ``` 52 | -------------------------------------------------------------------------------- /cpp/Find-The-Difference/README.md: -------------------------------------------------------------------------------- 1 | ### 找不同 2 | 3 | 给定两个字符串 s 和 t,它们只包含小写字母。 4 | 5 | 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 6 | 7 | 请找出在 t 中被添加的字母。 8 | 9 | 示例1: 10 | ``` 11 | 输入:s = "abcd", t = "abcde" 12 | 输出:"e" 13 | 解释:'e' 是那个被添加的字母。 14 | ``` 15 | 16 | ```c++ 17 | class Solution { 18 | public: 19 | char findTheDifference(string s, string t) { 20 | char res; 21 | map m; 22 | for (char &c : t) { 23 | m[c]++; 24 | } 25 | for (char &c : s) { 26 | m[c]--; 27 | } 28 | for (auto &p : m) { 29 | if (p.second > 0) { 30 | res = p.first; 31 | } 32 | } 33 | return res; 34 | } 35 | }; 36 | ``` 37 | -------------------------------------------------------------------------------- /cpp/Find-The-Longest-Substring-Containing-Vowels-In-Even-Counts/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /cpp/First-Missing-Positive/First-Missing-Positive.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/first-missing-positive/ 2 | /// Author : bryce 3 | /// Time : 2019-12-2 4 | -------------------------------------------------------------------------------- /cpp/First-Unique-Character-In-A-String/First-Unique-Character-In-A-String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstUniqChar(string s) { 4 | int res = -1; 5 | int n = s.size(); 6 | if (n==0) return res; 7 | unordered_map m; 8 | for (int i=0;i left); 19 | //将根节点的右子树变成链表 20 | flatten(root -> right); 21 | 22 | TreeNode* temp = root->right; 23 | //把树的右边换成左边的链表 24 | root->right = root->left; 25 | //记得要将左边置空 26 | root->left = NULL; 27 | //找到树的最右边的节点 28 | while (root->right != NULL) root = root->right; 29 | //把右边的链表接到刚才树的最右边的节点 30 | root->right =temp; 31 | return ; 32 | } 33 | }; 34 | ``` 35 | -------------------------------------------------------------------------------- /cpp/Generate-Parentheses/Generate-Parentheses.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/generate-parentheses/ 2 | /// Author : bryce 3 | /// Time : 2019-11-12 4 | 5 | /* 6 | 思路: 7 | 这种生成括号的规则,其实隐含了一条信息:那就是始终左括号的数量要大于或等于右括号的数量。也就是说,剩余的左括号的数量要始终小于等于右括号。左括号只要有, 8 | 就可以打印;而只 有当剩余的右括号数量比左括号大时,才能打印右括号。为了方便理解,假设n = 2,那么根据刚才的隐含信息,逻辑应该是这样的: 9 | 10 | 1. 肯定要先取一个左括号,此时左括号剩余的数量变为1,右括号剩余数量还是2 11 | 12 | 2. 第二位取左括号也行,取右括号也行。如果取左括号,那么此时右括号剩余数量为2,左括号剩余数量为0,长成了这个样子"((";如果取右括号,左右剩余数量都是1, 13 | 长成这个样子"()" 14 | 15 | 3. 第三位,如果剩余左括号没了,就只能跟进右括号了,连续两个,最终变成"(())";而如果现在是"()"的,那么要先左后右,最终变成"()()". 16 | 17 | 发现,每一步都有两种选择:左或者右,当然不一定都可行,如果可行,那么往后继续,不可行,终止。 18 | 19 | 例如当n=2时,二叉树应该是这个样子: 20 | 1: ( 21 | / \ 22 | 2: ( ) 23 | / \ / \ 24 | 3:cut ) ( cut 25 | / \ \ 26 | 4: cut ) ) 27 | 28 | 可以用DFS求解此题。 29 | */ 30 | 31 | // C++ Solution 1: 32 | class Solution { 33 | public: 34 | vector generateParenthesis(int n) { 35 | vector res; 36 | if (n==0) return res; 37 | DFS = (n,n,"",res); 38 | return res; 39 | } 40 | void( int l, int r, string out, vector &res){ //res前记得加&符号,改变实参 41 | if (l==0 && r==0) // 相当于节点为空,也就是深搜不能再深入了 42 | res.push_back(out); 43 | if (l > 0) DFS(l-1,r,out+'(',res); // 相当于左节点还存在 44 | if (r > 0 && r > l) DFS(l,r-1,out+')',res); // 相当于右节点还存在 45 | } 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /cpp/Group-Anagrams-Lcci/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 面试题 10.02. 变位词组 2 | 3 | 编写一种方法,对字符串数组进行排序,将所有变位词组合在一起。变位词是指字母相同,但排列不同的字符串。 4 | 5 | 6 | **示例 :** 7 | ``` 8 | 输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 9 | 输出: 10 | [ 11 | ["ate","eat","tea"], 12 | ["nat","tan"], 13 | ["bat"] 14 | ] 15 | ``` 16 | 17 | **说明:** 18 | - 所有输入均为小写字母。 19 | - 不考虑答案输出的顺序。 20 | 21 | # 解题思路: 22 | 哈希表模拟法 23 | # 时间复杂度: 24 | O(nklogk) n是数组长度,k是字符串中最长的字符串长度 25 | # 空间复杂度 26 | O(nk) 27 | 28 | # 代码 29 | ### 模拟法 30 | ```c++ 31 | class Solution { 32 | public: 33 | vector> groupAnagrams(vector& strs) { 34 | vector> res ; 35 | unordered_map> mp; 36 | for (string str : strs) { 37 | string key = str; 38 | sort(key.begin(), key.end()); 39 | mp[key].push_back(str); 40 | } 41 | for (auto it = mp.begin(); it != mp.end(); ++it) { 42 | res.push_back(it->second); 43 | } 44 | return res; 45 | } 46 | }; 47 | ``` 48 | -------------------------------------------------------------------------------- /cpp/Guess-Number-Higher-Or-Lower/README.md: -------------------------------------------------------------------------------- 1 | 2 | 猜数字游戏的规则如下: 3 | 4 | 每轮游戏,系统都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。 5 | 6 | 如果你猜错了,系统会告诉你这个数字比系统选出的数字是大了还是小了。 7 | 8 | 你可以通过调用一个预先定义好的接口 guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或 0) 9 | 10 | ```c++ 11 | /** 12 | * Forward declaration of guess API. 13 | * @param num your guess 14 | * @return -1 if num is lower than the guess number 15 | * 1 if num is higher than the guess number 16 | * otherwise return 0 17 | * int guess(int num); 18 | */ 19 | 20 | class Solution { 21 | public: 22 | int guessNumber(int n) { 23 | int l = 1; 24 | int r = n; 25 | while (l <= r) { 26 | int mid = l + (r - l) / 2; 27 | if (guess(mid) == 0) 28 | { 29 | return mid; 30 | } 31 | else if (guess(mid) == 1) { 32 | l = mid + 1; 33 | } else { 34 | r = mid -1; 35 | } 36 | } 37 | return 0; 38 | } 39 | }; 40 | ``` 41 | -------------------------------------------------------------------------------- /cpp/H-Index-II/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class Solution { 3 | public: 4 | int hIndex(vector& citations) { 5 | int n = citations.size(); 6 | for (int i = 0; i = h) { 9 | return h; 10 | } 11 | } 12 | return 0; 13 | } 14 | } 15 | ``` 16 | 17 | 18 | 19 | logn 20 | ```c++ 21 | class Solution { 22 | public: 23 | int hIndex(vector& citations) { 24 | int n = citations.size(); 25 | int l = 0; 26 | int r = n -1; 27 | while (l <= r) { 28 | int mid = l + (r -l + 1) / 2; 29 | int h = n - mid; 30 | if (citations[mid] == h) { 31 | return h; 32 | } else if (citations[mid] < h) { 33 | l = mid + 1; 34 | } else { 35 | r = mid - 1; 36 | } 37 | } 38 | return n - l; 39 | } 40 | }; 41 | ``` 42 | -------------------------------------------------------------------------------- /cpp/Hand-Of-Straights/Hand-Of-Straights.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isNStraightHand(vector& hand, int W) { 4 | int n = hand.size(); 5 | if (n%W!=0 || W<1 || W>n || hand.empty()) 6 | return false; 7 | map m; // 有序哈希表 8 | for (auto card : hand) 9 | m[card]++; 10 | while (!m.empty()) 11 | { 12 | int start = m.begin()->first;// map 返回开始的关键值,也就是card的值 13 | for (int i = 0; i < W;i++) 14 | { 15 | if (m.find(start + i)==m.end()) // 寻找start开始后的w个序列 16 | return false; 17 | m[start+i]--; 18 | if (m[start + i] == 0) // 每找到一个满足的数字就删除 19 | m.erase(start + i); 20 | } 21 | } 22 | return true; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /cpp/Happy-Number/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 快乐数 2 | 3 | 编写一个算法来判断一个数 n 是不是快乐数。 4 | 5 | 「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。 6 | 7 | 如果 n 是快乐数就返回 True ;不是,则返回 False 。 8 | 9 | 10 | **示例 :** 11 | ``` 12 | 输入:19 13 | 输出:true 14 | 解释: 15 | 12 + 92 = 82 16 | 82 + 22 = 68 17 | 62 + 82 = 100 18 | 12 + 02 + 02 = 1 19 | ``` 20 | 21 | # 解题思路: 22 | 方法:使用“快慢指针”思想找出循环:“快指针”每次走两步,“慢指针”每次走一步,当二者相等时,即为一个循环周期。此时,判断是不是因为1引起的循环,是的话就是快乐数,否则不是快乐数。 23 | 24 | 注意:此题不建议用集合记录每次的计算结果来判断是否进入循环,因为这个集合可能大到无法存储;另外,也不建议使用递归,同理,如果递归层次较深,会直接导致调用栈崩溃。不要因为这个题目给出的整数是int型而投机取巧。 25 | 26 | # 时间复杂度: 27 | O(log(n)) 28 | # 空间复杂度 29 | O(1) 30 | 31 | # 代码 32 | 33 | ### 快慢指针法 34 | ```c++ 35 | class Solution { 36 | public: 37 | bool isHappy(int n) { 38 | int slow = n, fast = bitSuqareSum(fast); 39 | while(slow!=fast) 40 | { 41 | slow = bitSuqareSum(slow); 42 | fast = bitSuqareSum(fast); 43 | fast = bitSuqareSum(fast); 44 | } 45 | return slow==1; 46 | } 47 | 48 | int bitSuqareSum(int n) 49 | { 50 | int res = 0; 51 | while(n) 52 | { 53 | int bit = n%10; 54 | res += bit*bit; 55 | n/=10; 56 | } 57 | return res; 58 | } 59 | }; 60 | ``` 61 | # 参考 62 | 63 | - [题解](https://leetcode-cn.com/problems/happy-number/solution/kuai-le-de-zhi-shi-dian-zeng-jia-liao-by-sweetiee/) 64 | -------------------------------------------------------------------------------- /cpp/Insert-Intervals/Insert-Intervals.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /cpp/Intersection-Of-Two-Arrays-II/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class Solution { 3 | public: 4 | vector intersect(vector& nums1, vector& nums2) { 5 | sort(nums1.begin(), nums1.end()); 6 | sort(nums2.begin(), nums2.end()); 7 | int m = nums1.size(); 8 | int n = nums2.size(); 9 | int i = 0, j = 0; 10 | vector res; 11 | while (i < m && j < n) { 12 | if (nums1[i] < nums2[j]) { 13 | i++; 14 | } else if (nums1[i] > nums2[j]) { 15 | j++; 16 | } else { 17 | res.push_back(nums1[i]); 18 | i++; 19 | j++; 20 | } 21 | } 22 | return res; 23 | } 24 | }; 25 | ``` 26 | 27 | ```c++ 28 | class Solution { 29 | public: 30 | vector intersect(vector& nums1, vector& nums2) { 31 | int m = nums1.size(); 32 | int n = nums2.size(); 33 | unordered_map mp; 34 | for (int num : nums1) { 35 | mp[num]++; 36 | } 37 | vector res; 38 | for (int &num : nums2) { 39 | if(mp.count(num)) { 40 | res.push_back(num); 41 | mp[num]--; 42 | if (mp[num] == 0) { 43 | mp.erase(num); 44 | } 45 | } 46 | } 47 | return res; 48 | } 49 | }; 50 | ``` 51 | -------------------------------------------------------------------------------- /cpp/Intersection-Of-Two-Arrays/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class Solution { 3 | public: 4 | vector intersection(vector& nums1, vector& nums2) { 5 | vector res; 6 | int n = nums2.size(); 7 | unordered_set s(nums1.begin(), nums1.end()); 8 | unordered_set st; 9 | for (int &num : nums2) { 10 | if (s.count(num) && !st.count(num)) { 11 | res.push_back(num); 12 | st.insert(num); 13 | } 14 | } 15 | return res; 16 | } 17 | }; 18 | ``` 19 | -------------------------------------------------------------------------------- /cpp/Intersection-Of-Two-Linked-Lists/Intersection-Of-Two-Linked-Lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 | if (headA==NULL || headB==NULL) return NULL; 13 | ListNode* p = headA; 14 | ListNode* q = headB; 15 | int n=0,m=0; 16 | while(p) 17 | { 18 | n++; 19 | p=p->next; 20 | } 21 | while(q) 22 | { 23 | m++; 24 | q=q->next; 25 | } 26 | p = headA; 27 | q = headB; 28 | int k = 0; 29 | if (n>=m) 30 | { 31 | k=n-m; 32 | } 33 | else 34 | { 35 | k=m-n; 36 | p=headB; 37 | q=headA; 38 | } 39 | for (int i=0;inext; 42 | } 43 | while(p && q && p!=q) 44 | { 45 | p = p->next; 46 | q = q->next; 47 | } 48 | ListNode* res = p; 49 | return res; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /cpp/Interval-List-Intersections/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 区间列表的交集 2 | 3 | 给定两个由一些 闭区间 组成的列表,每个区间列表都是成对不相交的,并且已经排序。 4 | 5 | 返回这两个区间列表的交集。 6 | 7 | (形式上,闭区间 [a, b](其中 a <= b)表示实数 x 的集合,而 a <= x <= b。两个闭区间的交集是一组实数,要么为空集,要么为闭区间。例如,[1, 3] 和 [2, 4] 的交集为 [2, 3]。) 8 | 9 | **示例:** 10 | ``` 11 | 输入:A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]] 12 | ``` 13 | 14 | # 解题思路: 15 | 16 | 猿辅导的面试题,利用双指针来做, 17 | 18 | 19 | # 时间复杂度: 20 | O(n) 21 | 22 | # 空间复杂度 23 | O(n) 24 | 25 | # 代码 26 | 27 | ### 双指针法 28 | ```c++ 29 | class Solution { 30 | public: 31 | vector> intervalIntersection(vector>& A, vector>& B) { 32 | vector> res; 33 | int n = A.size(); 34 | int m = B.size(); 35 | int i = 0, j = 0; 36 | while (i < n && j < m) { 37 | int start = max(A[i][0], B[j][0]); 38 | int end = min(A[i][1], B[j][1]); 39 | if (start <= end) { 40 | res.push_back({start, end}); 41 | } 42 | // 较长的区间还有可能和后边的区间有交集的 43 | // 较短的区间移动 44 | if (A[i][1] < B[j][1]) { 45 | i++; 46 | } 47 | else { 48 | j++; 49 | } 50 | } 51 | return res; 52 | } 53 | }; 54 | ``` 55 | -------------------------------------------------------------------------------- /cpp/Invert-Binary-Tree/Invert-Binary-Tree.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | /** 3 | * Definition for a binary tree node. 4 | * struct TreeNode { 5 | * int val; 6 | * TreeNode *left; 7 | * TreeNode *right; 8 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | TreeNode* invertTree(TreeNode* root) { 14 | if (root==NULL) 15 | return root; 16 | TreeNode* temp = root->left; 17 | root->left = invertTree(root->right); 18 | root->right = invertTree(temp); 19 | return root; 20 | } 21 | }; 22 | // C++ Solution 2: 23 | class Solution { 24 | public: 25 | TreeNode* invertTree(TreeNode* root) { 26 | if (root==NULL) 27 | return root; 28 | queue q; 29 | //将二叉树中的节点逐层放入队列中,再迭代处理队列中的元素 30 | q.push(root); 31 | while (!q.empty()) 32 | { 33 | //每次都从队列中拿一个节点,并交换这个节点的左右子树 34 | TreeNode* cur = q.front(); 35 | q.pop(); 36 | TreeNode* temp = cur->left; 37 | cur->left = cur->right; 38 | cur->right = temp; 39 | //如果当前节点的左子树不为空,则放入队列等待后续处理 40 | if (cur->left!=NULL) 41 | q.push(cur->left); 42 | //如果当前节点的右子树不为空,则放入队列等待后续处理 43 | if (cur->right!=NULL) 44 | q.push(cur->right); 45 | } 46 | return root; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /cpp/Island-Perimeter/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 岛屿的周长 2 | 3 | ## 题目描述: 4 | 给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。 5 | 6 | 网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。 7 | 8 | 岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。 9 | 10 | **示例:** 11 | ![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/island.png) 12 | ``` 13 | 输入: 14 | [[0,1,0,0], 15 | [1,1,1,0], 16 | [0,1,0,0], 17 | [1,1,0,0]] 18 | 19 | 输出: 16 20 | 21 | 解释: 它的周长是下面图片中的 16 个黄色的边: 22 | ``` 23 | 24 | # 解题思路: 25 | 关注前面遍历过得方格,如果之前有相邻方格,就-2; 26 | 27 | # 时间复杂度: 28 | O(mn) 29 | # 空间复杂度 30 | O(mn) 31 | # 代码 32 | 33 | # C++: 34 | ### 35 | ```c++ 36 | class Solution { 37 | public: 38 | int islandPerimeter(vector>& grid) { 39 | int res = 0; 40 | int m = grid.size(); 41 | int n = grid[0].size(); 42 | //重点关注前面遍历过得方格,如果之前有相邻方格,就-2; 43 | for (int i = 0; i < m; i++) { 44 | for (int j = 0; j < n; j++) { 45 | if (grid[i][j] == 1) { 46 | res += 4; 47 | if (i > 0 && grid[i-1][j] == 1) { 48 | res -= 2; 49 | } 50 | if (j > 0 && grid[i][j-1] == 1) { 51 | res -= 2; 52 | } 53 | } 54 | } 55 | } 56 | return res; 57 | } 58 | }; 59 | ``` 60 | -------------------------------------------------------------------------------- /cpp/Isomorphic-Strings/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class Solution { 3 | public: 4 | bool isIsomorphic(string s, string t) { 5 | int n = s.size(); 6 | if (n == 0) return true; 7 | int i = 0; 8 | while (i < n) { 9 | if (s.find(s[i]) != t.find(t[i])) { 10 | return false; 11 | } 12 | i++; 13 | } 14 | return true; 15 | } 16 | }; 17 | ``` 18 | -------------------------------------------------------------------------------- /cpp/Jewels-And-Stones/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class Solution { 3 | public: 4 | int numJewelsInStones(string J, string S) { 5 | int res = 0; 6 | unordered_map m; 7 | for (char &c : S) { 8 | m[c]++; 9 | } 10 | for (char &c : J) { 11 | res += m[c]; 12 | } 13 | return res; 14 | } 15 | }; 16 | ``` 17 | -------------------------------------------------------------------------------- /cpp/Jump-Game-II/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 跳跃游戏 II 2 | 3 | 给定一个非负整数数组,你最初位于数组的第一个位置。 4 | 5 | 数组中的每个元素代表你在该位置可以跳跃的最大长度。 6 | 7 | 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 8 | 9 | 假设你总是可以到达数组的最后一个位置。 10 | 11 | **示例 1:** 12 | ``` 13 | 输入: [2,3,1,1,4] 14 | 输出: 2 15 | 解释: 跳到最后一个位置的最小跳跃数是 2。 16 |   从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 17 | ``` 18 | 19 | 20 | # 解题思路: 21 | 贪心算法 22 | # 时间复杂度: 23 | O(n) 24 | # 空间复杂度 25 | O(1) 26 | 27 | # 代码 28 | 29 | ### 贪心算法 30 | ```c++ 31 | class Solution { 32 | public: 33 | int jump(vector& nums) { 34 | int n = nums.size(); 35 | // 记录能够到达的最远距离 36 | int reach = 0; 37 | // 记录上一步step跳的最远距离 38 | int end = 0; 39 | int res =0; 40 | for (int i=0;i=n-1) return res+1; 44 | // 当到达上一步的最远距离的时候,那么意味着我们需要进行一次新的起跳,那么步数 + 1 45 | // 并且更新最远距离 46 | if (i==end) 47 | { 48 | end = reach; 49 | res++; 50 | } 51 | } 52 | return res; 53 | } 54 | }; 55 | ``` 56 | -------------------------------------------------------------------------------- /cpp/Jump-Game/Jump-Game.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 动态规划 2 | class Solution { 3 | public: 4 | bool canJump(vector& nums) 5 | { 6 | int n=nums.size(); 7 | if (nums.empty()) return 0; 8 | vector dp(n,0); 9 | for (int i=1;i& nums) 23 | { 24 | int reach=0; 25 | int n=nums.size(); 26 | for (int i=0;ireach || reach==n-1) break; 29 | reach = max(reach,i+nums[i]); 30 | } 31 | return reach>=n-1; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /cpp/Kids-With-The-Greatest-Number-Of-Candies/README.md: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector kidsWithCandies(vector& candies, int extraCandies) { 4 | int n = candies.size(); 5 | vector res(n,0); 6 | 7 | for (int i=0;i=c) res[i] =1; 13 | } 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /cpp/LRU-Cache/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class LRUCache{ 3 | private: 4 | //LRU数据结构 5 | struct Node{ 6 | int key; 7 | int value; 8 | Node(int k,int v):key(k),value(v){} 9 | }; 10 | public: 11 | LRUCache(int c):capacity(c) {} 12 | 13 | int get(int key){ 14 | if (cacheMap.find(key) == cacheMap.end()) 15 | return -1; //这里产生缺页中断,根据页表将页面调入内存,然后set(key, value) 16 | //将key移到第一个,并更新cacheMap 17 | cacheList.splice(cacheList.begin(),cacheList,cacheMap[key]); 18 | cacheMap[key] = cacheList.begin(); 19 | return cacheMap[key]->value; 20 | } 21 | void put(int key, int value){ 22 | if (cacheMap.find(key) == cacheMap.end()) 23 | { 24 | //淘汰最后一个,然后将其加到第一个位置 25 | if (cacheList.size() == capacity) 26 | { 27 | cacheMap.erase(cacheList.back().key); 28 | cacheList.pop_back(); 29 | } 30 | cacheList.push_front(Node(key,value)); 31 | cacheMap[key] = cacheList.begin(); 32 | } 33 | else 34 | { 35 | //更新节点的值,并将其加到第一个位置 36 | cacheMap[key]->value = value; 37 | cacheList.splice(cacheList.begin(),cacheList,cacheMap[key]); 38 | cacheMap[key] = cacheList.begin(); 39 | } 40 | } 41 | private: 42 | int capacity; 43 | list cacheList; 44 | unordered_map::iterator> cacheMap; 45 | }; 46 | ``` 47 | -------------------------------------------------------------------------------- /cpp/Largest-Number/Largest-Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | string largestNumber(vector& nums) 4 | { 5 | string res; 6 | int n = nums.size(); 7 | sort(nums.begin(),nums.end(),compare); // compare 自定义比较规则,不设置默认是从小到大 8 | for (int i=0;i (sb + sa); 28 | // 两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇’\0’为止。 29 | // 当两个数的位数一样,则直接可以应用字符串的比较。如 "1346" > "1111" == true 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /cpp/Lemonade-Change/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 860. 柠檬水找零 2 | 3 | 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 4 | 5 | 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 6 | 7 | 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 8 | 9 | 注意,一开始你手头没有任何零钱。 10 | 11 | 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 12 | 13 | 14 | **示例 1:** 15 | ``` 16 | 输入:[5,5,5,10,20] 17 | 输出:true 18 | 解释: 19 | 前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。 20 | 第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。 21 | 第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。 22 | 由于所有客户都得到了正确的找零,所以我们输出 true。 23 | ``` 24 | 25 | **示例 2:** 26 | ``` 27 | 输入:[5,5,10] 28 | 输出:true 29 | 30 | 输入:[5,5,10,10,20] 31 | 输出:false 32 | 解释: 33 | 前 2 位顾客那里,我们按顺序收取 2 张 5 美元的钞票。 34 | 对于接下来的 2 位顾客,我们收取一张 10 美元的钞票,然后返还 5 美元。 35 | 对于最后一位顾客,我们无法退回 15 美元,因为我们现在只有两张 10 美元的钞票。 36 | 由于不是每位顾客都得到了正确的找零,所以答案是 false。 37 | ``` 38 | 39 | # 解题思路: 40 | 41 | 模拟+贪心 42 | 43 | 44 | # 时间复杂度: 45 | O(n) 46 | # 代码 47 | ```c++ 48 | class Solution { 49 | public: 50 | bool lemonadeChange(vector& bills) { 51 | if (bills.empty()) return true; 52 | int five = 0, ten = 0; 53 | for (int &i : bills) { 54 | if (i == 5) five++; 55 | else if (i == 10) {five--; ten++;} 56 | // 贪心尽可能用10元找零 57 | else if (ten > 0) {ten--, five--;} 58 | else five-=3; 59 | if (five < 0) return false; 60 | } 61 | return true; 62 | } 63 | }; 64 | ``` 65 | -------------------------------------------------------------------------------- /cpp/Length-Of-Last-Word/Length-Of-Last-Word.cpp: -------------------------------------------------------------------------------- 1 | // C++ Solution 1: 2 | class Solution { 3 | public: 4 | int lengthOfLastWord(string s) { 5 | int res = 0; 6 | if (s.empty()) return res; 7 | int n = s.size(); 8 | int m=n-1; 9 | while(m>=0 && s[m]==' ') 10 | { 11 | m--; 12 | } 13 | for (int i=m;i>=0;i--) 14 | { 15 | if (s[i]==' ') break; 16 | res+=1; 17 | } 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /cpp/Linked-List-Cycle/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 环形链表 2 | 3 | 给定一个链表,判断链表中是否有环。 4 | 5 | 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 6 | 7 | **示例 :** 8 | ``` 9 | 输入:head = [3,2,0,-4], pos = 1 10 | 输出:true 11 | 解释:链表中有一个环,其尾部连接到第二个节点。 12 | ``` 13 | ![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png) 14 | 15 | # 解题思路: 16 | 快慢指针:快指针每次走2步,慢指针每次走1步,当两者相遇说明一定有环。 17 | 18 | # 代码 19 | 20 | ### 快慢指针 21 | ```c++ 22 | /** 23 | * Definition for singly-linked list. 24 | * struct ListNode { 25 | * int val; 26 | * ListNode *next; 27 | * ListNode(int x) : val(x), next(NULL) {} 28 | * }; 29 | */ 30 | class Solution { 31 | public: 32 | bool hasCycle(ListNode *head) { 33 | if (head==NULL || head->next==NULL) return false; 34 | ListNode *p = head; 35 | ListNode *q = head; 36 | while(q!=NULL && q->next!=NULL) 37 | { 38 | p = p->next; 39 | q = q->next->next; 40 | if (p==q) 41 | { 42 | return true; 43 | } 44 | } 45 | return false; 46 | } 47 | }; 48 | ``` 49 | -------------------------------------------------------------------------------- /cpp/Longest_Substring_Without_Repeating_Characters/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 无重复字符的最长子串 2 | 3 | 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 4 | 5 | **示例 :** 6 | ``` 7 | 输入: "abcabcbb" 8 | 输出: 3 9 | 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 10 | ``` 11 | 12 | # 解题思路: 13 | 滑动窗口+哈希表,碰到子串问题,首先考虑滑动窗口 14 | 15 | # 时间复杂度: 16 | O(n) 17 | # 空间复杂度 18 | O(n) 19 | 20 | # 代码 21 | 22 | ### 滑动窗口 23 | ```c++ 24 | int lengthOfLongestSubstring(string s) 25 | { 26 | unordered_map m; 27 | 28 | int left = 0, right = 0; 29 | int res = 0; // 记录结果 30 | while (right < s.size()) 31 | { 32 | char c = s[right++]; 33 | // 进行窗口内数据的一系列更新 34 | m[c]++; 35 | // 判断左侧窗口是否要收缩 36 | while (m[c] > 1) 37 | { 38 | char d = s[left++]; 39 | // 进行窗口内数据的一系列更新 40 | m[d]--; 41 | } 42 | // 在这里更新答案 43 | res = max(res, right - left); 44 | } 45 | return res; 46 | } 47 | ``` 48 | ### 参考 49 | 50 | - [滑动窗口总结](https://bryceustc.github.io/2020/04/22/%E5%8F%8C%E6%8C%87%E9%92%88%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E7%AE%97%E6%B3%95%E6%80%BB%E7%BB%93/#more) 51 | -------------------------------------------------------------------------------- /cpp/Lowest-Common-Ancestor-Of-A-Binary-Search-Tree/README.md: -------------------------------------------------------------------------------- 1 | ### 题目描述 二叉搜索树的最近公共祖先 2 | 3 | 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 4 | 5 | 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 6 | 7 | 例如,给定如下二叉搜索树:  root = [6,2,8,0,4,7,9,null,null,3,5] 8 | 9 | ![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/14/binarysearchtree_improved.png) 10 | 11 | ```c++ 12 | class Solution { 13 | public: 14 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 15 | if (root == NULL) return root; 16 | if (root->val > p->val && root->val > q->val) { 17 | return lowestCommonAncestor(root->left, p, q); 18 | } 19 | if (root->val < p->val && root->val < q->val) { 20 | return lowestCommonAncestor(root->right, p ,q); 21 | } 22 | return root; 23 | } 24 | }; 25 | ``` 26 | -------------------------------------------------------------------------------- /cpp/Maximal-Rectangle/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class Solution { 3 | public: 4 | int maximalRectangle(vector>& matrix) { 5 | int m = matrix.size(); 6 | if (m==0) return 0; 7 | int n = matrix[0].size(); 8 | vector> dp(m,vector(n,0)); 9 | for (int i = 0; i < m; i++) { 10 | if (matrix[i][0] == '1') dp[i][0] = 1; 11 | } 12 | for (int i = 0; i < m; i++) { 13 | for (int j = 1; j < n; j++) { 14 | if (matrix[i][j]=='1') { 15 | dp[i][j] = dp[i][j-1] + 1; 16 | } 17 | } 18 | } 19 | 20 | int res = 0; 21 | for (int i = 0; i < m; i++) { 22 | for (int j = 0; j < n; j++) { 23 | int w = INT_MAX; 24 | for (int k = i; k >=0; k--){ 25 | int h = i - k + 1; 26 | w = min (w, dp[k][j]); 27 | res = max(res, h*w); 28 | } 29 | } 30 | } 31 | return res; 32 | } 33 | }; 34 | ``` 35 | -------------------------------------------------------------------------------- /cpp/Maximal-Square/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 最大正方形 2 | 3 | 在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。 4 | 5 | **示例 :** 6 | ``` 7 | 输入: 8 | 9 | 1 0 1 0 0 10 | 1 0 1 1 1 11 | 1 1 1 1 1 12 | 1 0 0 1 0 13 | 14 | 输出: 4 15 | ``` 16 | 17 | # 解题思路: 18 | dp 19 | 20 | 若某格子值为 1 ,则以此为右下角的正方形的、最大边长为:上面的正方形、左面的正方形或左上的正方形中,最小的那个,再加上此格。 21 | 22 | # 时间复杂度: 23 | O(n) 24 | # 空间复杂度 25 | O(n) 26 | 27 | # 代码 28 | 29 | ### dp 30 | ```c++ 31 | class Solution { 32 | public: 33 | int maximalSquare(vector>& matrix) { 34 | int res = 0;//正方形的边长 35 | if (matrix.empty()) return 0; 36 | int row = matrix.size(); 37 | int col = matrix[0].size(); 38 | // dp[i][j] 表示以矩阵中第i行j列为右下角构成最大正方形的边长,即matrix[i-1][j-1] 39 | vector> dp (row+1,vector(col+1,0)); 40 | // 相当于已经预处理新增第一行、第一列均为0 41 | for (int i=1;i<=row;i++) 42 | { 43 | for (int j=1; j<=col;j++) 44 | { 45 | if (matrix[i-1][j-1]=='1') 46 | { 47 | // 状态转移方程 48 | dp[i][j] = min(dp[i-1][j], min(dp[i][j-1], dp[i-1][j-1]))+1; 49 | res = max(res, dp[i][j]); 50 | } 51 | } 52 | } 53 | return res*res; 54 | } 55 | }; 56 | ``` 57 | -------------------------------------------------------------------------------- /cpp/Maximum-Depth-Of-Binary-Tree/Maximum-Depth-Of-Binary-Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(TreeNode* root) { 4 | if (root == NULL) 5 | return 0; 6 | int left = maxDepth(root->left); 7 | int right = maxDepth(root->right); 8 | return max(left, right) + 1; 9 | } 10 | }; 11 | class Solution { 12 | public: 13 | int maxDepth(TreeNode* root) { 14 | int depth = 0; 15 | if (root == NULL) 16 | return depth; 17 | queue q; 18 | q.push(root); 19 | while(!q.empty()) 20 | { 21 | int count = q.size(); 22 | while (count>0) 23 | { 24 | TreeNode* node = q.front(); 25 | q.pop(); 26 | if (node->left) 27 | q.push(node->left); 28 | if (node->right) 29 | q.push(node->right); 30 | count--; 31 | } 32 | depth++; 33 | } 34 | return depth; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/Maximum-Product-Subarray/README.md: -------------------------------------------------------------------------------- 1 | ### 题目描述:乘积最大子数组 2 | 3 | 给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。 4 | 5 | 示例1: 6 | ``` 7 | 输入: [2,3,-2,4] 8 | 输出: 6 9 | 解释: 子数组 [2,3] 有最大乘积 6。 10 | ``` 11 | 12 | 动态规划 13 | 14 | 代码 15 | ```c++ 16 | class Solution { 17 | public: 18 | int maxProduct(vector& nums) { 19 | int n = nums.size(); 20 | vector> dp(n, vector (2,0)); 21 | dp[0][0] = nums[0]; // dp[i][0] 表示以nums[i] 结尾的乘积的最小值 22 | dp[0][1] = nums[0]; // dp[i][1] 表示以nums[i] 结尾的乘积的最大值 23 | int res = nums[0]; 24 | for (int i = 1; i < n; i++) { 25 | if (nums[i] >= 0) { 26 | dp[i][0] = min(nums[i], dp[i-1][0] * nums[i]); 27 | dp[i][1] = max(nums[i], dp[i-1][1] * nums[i]); 28 | } else { 29 | dp[i][0] = min(nums[i], dp[i-1][1] * nums[i]); 30 | dp[i][1] = max(nums[i], dp[i-1][0] * nums[i]); 31 | } 32 | res = max(res, dp[i][1]); 33 | } 34 | return res; 35 | } 36 | }; 37 | ``` 38 | -------------------------------------------------------------------------------- /cpp/Min-Stack/Min-Stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | /** initialize your data structure here. */ 4 | MinStack() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | stack1.push(x); 10 | if (stack2.empty() || x < stack2.top()) 11 | { 12 | stack2.push(x); 13 | } 14 | else 15 | { 16 | int y = stack2.top(); 17 | stack2.push(y); 18 | } 19 | } 20 | 21 | void pop() { 22 | if (stack1.size()>0 && stack2.size()>0) 23 | { 24 | stack1.pop(); 25 | stack2.pop(); 26 | } 27 | } 28 | 29 | int top() { 30 | return stack1.top(); 31 | } 32 | 33 | int getMin() { 34 | return stack2.top(); 35 | } 36 | private: 37 | stack stack1; 38 | stack stack2; 39 | }; 40 | 41 | /** 42 | * Your MinStack object will be instantiated and called as such: 43 | * MinStack* obj = new MinStack(); 44 | * obj->push(x); 45 | * obj->pop(); 46 | * int param_3 = obj->top(); 47 | * int param_4 = obj->getMin(); 48 | */ 49 | -------------------------------------------------------------------------------- /cpp/Minimum-Size-Subarray-Sum/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 长度最小的子数组 2 | 3 | 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 4 | 5 | **示例:** 6 | ``` 7 | 输入:s = 7, nums = [2,3,1,2,4,3] 8 | 输出:2 9 | 解释:子数组 [4,3] 是该条件下的长度最小的连续子数组。 10 | `` 11 | # 解题思路: 12 | 滑动窗口 13 | 14 | # 时间复杂度: 15 | O(n) 16 | # 空间复杂度 17 | O(1) 18 | 19 | # 代码 20 | 21 | ### 滑动窗口 22 | ```c++ 23 | class Solution { 24 | public: 25 | int minSubArrayLen(int s, vector& nums) { 26 | int n = nums.size(); 27 | int sum = 0; 28 | int left = 0, right = 0; 29 | int total = accumulate(nums.begin(), nums.end(),0); 30 | if (total < s) return 0; 31 | int res = n; 32 | while (right < n) { 33 | sum += nums[right++]; 34 | if (sum < s) { 35 | continue; 36 | } else { 37 | while (sum >= s) { 38 | sum -= nums[left]; 39 | left++; 40 | res = min(res, right - left +1); 41 | } 42 | } 43 | } 44 | return res; 45 | } 46 | }; 47 | ``` 48 | # 参考 49 | 50 | - [双指针滑动窗口](https://bryceustc.github.io/2020/04/22/%E5%8F%8C%E6%8C%87%E9%92%88%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E7%AE%97%E6%B3%95%E6%80%BB%E7%BB%93/) 51 | -------------------------------------------------------------------------------- /cpp/Multiply-Strings/Image/multiply.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Multiply-Strings/Image/multiply.png -------------------------------------------------------------------------------- /cpp/Multiply-Strings/Multiply-Strings.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/multiply-strings/ 2 | /// Author : bryce 3 | /// Time : 2019-12-4 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | string multiply(string num1, string num2) { 13 | int n1=num1.size(); 14 | int n2=num2.size(); 15 | string res(n1+n2,'0'); 16 | for(int i=n2-1;i>=0;i--) 17 | { 18 | for(int j=n1-1;j>=0;j--) 19 | { 20 | int temp=(res[i+j+1]-'0')+(num1[j]-'0')*(num2[i]-'0'); 21 | res[i+j+1]=temp%10+'0';//当前位 22 | res[i+j]+=temp/10; //前一位加上进位,res[i+j]已经初始化为'0',加上int类型自动转化为char,所以此处不加'0' 23 | } 24 | } 25 | 26 | //去除首位'0' 27 | for(int i=0;i digits(int n) { 25 | vector res; 26 | while (n > 0) { 27 | res.push_back(n % 10); 28 | n /= 10; 29 | } 30 | reverse(res.begin(), res.end()); 31 | return res; 32 | } 33 | int nextGreaterElement(int n) { 34 | vector nums = digits(n); 35 | int N = nums.size(); 36 | int l = -1; 37 | for (int i = 1; i < N; ++i) { 38 | if (nums[i] > nums[i - 1]) { 39 | l = i - 1; 40 | } 41 | } 42 | if (l == -1) return -1; 43 | reverse(nums.begin() + l + 1, nums.end()); 44 | int r = upper_bound(nums.begin() + l + 1, nums.end(), nums[l]) - nums.begin(); 45 | swap(nums[l], nums[r]); 46 | long res = 0; 47 | for (int i = 0; i < N; ++i) { 48 | res = 10 * res + (long)nums[i]; 49 | } 50 | return res > INT_MAX ? -1 : res; 51 | } 52 | }; 53 | ``` 54 | -------------------------------------------------------------------------------- /cpp/Next-Permutation/Next-Permutation.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/next-permutation/ 2 | /// Author : bryce 3 | /// Time : 2019-11-22 4 | 5 | /* 6 | 思路: 7 | 1. 8 | 9 | 时间复杂度: 10 | 11 | */ 12 | class Solution { 13 | public: 14 | void nextPermutation(vector &num) { 15 | int i, j, n = num.size(); 16 | for (i = n - 2; i >= 0; --i) { 17 | if (num[i + 1] > num[i]) { 18 | for (j = n - 1; j > i; --j) { 19 | if (num[j] > num[i]) break; 20 | } 21 | swap(num[i], num[j]); 22 | reverse(num.begin() + i + 1, num.end()); 23 | return; 24 | } 25 | } 26 | reverse(num.begin(), num.end()); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /cpp/Next-Permutation/README.md: -------------------------------------------------------------------------------- 1 | ### 下一个排列 2 | 3 | ![](https://pic.leetcode-cn.com/e56a66ed318d1761cd8c8f9d1521f82a30c71ecc84f551912b90d8fe254c8f3d-image.png) 4 | 5 | - 从后往前找到第一个【相邻升序对】,即A[i]& nums) { 18 | int n = nums.size(); 19 | int i = n - 2, j = n - 1; 20 | for (i = n - 2; i >= 0; i--) { 21 | // 第一个相邻的升序对 22 | if (nums[i+1] > nums[i]) { 23 | // 从后向前找第一个大的 24 | for (j = n - 1; j > i; j--) { 25 | if (nums[j] > nums[i]) { 26 | break; 27 | } 28 | } 29 | // 交换 30 | swap(nums[i], nums[j]); 31 | // 重新排序,因为是降序,所以直接反转就可以 32 | reverse(nums.begin() + i + 1, nums.end()); 33 | return; 34 | } 35 | } 36 | // 没有逆序对,直接反转 37 | reverse(nums.begin(), nums.end()); 38 | } 39 | }; 40 | ``` 41 | -------------------------------------------------------------------------------- /cpp/Non-Overlapping-Intervals/README.md: -------------------------------------------------------------------------------- 1 | ### 435. 无重叠区间 2 | 3 | 给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。 4 | 5 | 注意: 6 | 7 | 可以认为区间的终点总是大于它的起点。 8 | 区间 [1,2] 和 [2,3] 的边界相互“接触”,但没有相互重叠。 9 | 10 | 示例: 11 | 输入: [ [1,2], [2,3], [3,4], [1,3] ] 12 | 13 | 输出: 1 14 | 15 | 解释: 移除 [1,3] 后,剩下的区间没有重叠。 16 | 17 | 贪心策略 18 | ```c++ 19 | class Solution { 20 | public: 21 | static bool cmp(vector &a, vector &b){ 22 | return a[1]>& intervals) { 25 | int n = intervals.size(); 26 | if(intervals.empty()) return 0; 27 | sort(intervals.begin(),intervals.end(),cmp); 28 | int num = 1; 29 | int end = intervals[0][1]; 30 | for(int i = 1; i < n; i++){ 31 | if(intervals[i][0]>=end){//找到与前一个不交叉&&右边界最小的 32 | end = intervals[i][1]; 33 | num++; 34 | } 35 | } 36 | return n-num; 37 | } 38 | }; 39 | ``` 40 | -------------------------------------------------------------------------------- /cpp/Number-Of-1-Bits/Number-Of-1-Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int res = 0; 5 | while(n!=0) 6 | { 7 | res++; 8 | n = (n-1)&n; 9 | } 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /cpp/Number-Of-Days-Between-Two-Dates/Number-Of-Days-Between-Two-Dates.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int daysBetweenDates(string date1, string date2) { 4 | return abs(get(date1) - get(date2)); // 两次日期绝对值之差 5 | } 6 | bool is_leap(int year) 7 | { 8 | return year%100!=0 && year % 4==0 || year % 400==0; // 闰年定义 9 | } 10 | int get(string date) 11 | { 12 | int year, month, day; 13 | sscanf(date.c_str(), "%d-%d-%d", &year, &month, &day); //sscanf() - 从一个字符串中读进与指定格式相符的数据. 14 | int m_days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 15 | int days = 0; 16 | for (int i=1971;i>& grid) { 37 | if (grid.empty()) return 0; 38 | int m = grid.size(); 39 | int n = grid[0].size(); 40 | int res = 0; 41 | for (int i=0;i> &grid, int i, int j) 56 | { 57 | if (i<0 || i>=grid.size() || j<0 || j>=grid[0].size() || grid[i][j] == '0') 58 | return; 59 | grid[i][j] = '0'; 60 | dfs(grid,i-1,j); 61 | dfs(grid,i+1,j); 62 | dfs(grid,i,j-1); 63 | dfs(grid,i,j+1); 64 | } 65 | }; 66 | ``` 67 | 68 | -------------------------------------------------------------------------------- /cpp/Palindrome-Number/Palindrome-Number.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/palindrome-number/ 2 | /// Author : bryce 3 | /// Time : 2019-10-31 4 | class Solution { 5 | public: 6 | bool isPalindrome(int x) { 7 | int a = x; 8 | int n = 0; 9 | if (a < 0) 10 | return false; 11 | while (a != 0) 12 | { 13 | int m = a % 10; 14 | a/=10; 15 | if (n < INT_MAX/10 || (n == INT_MAX/10 && m <= 7)) 16 | n = n * 10 + m; 17 | else 18 | return false; 19 | } 20 | return x == n; 21 | } 22 | }; 23 | 24 | class Solution2 { 25 | public: 26 | bool isPalindrome(int x) { 27 | int a = x; 28 | long long n = 0; 29 | if (a < 0) 30 | return false; 31 | while (a != 0) 32 | { 33 | int m = a % 10; 34 | a/=10; 35 | n = n * 10 + m; 36 | } 37 | return x == n; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Pascals-Triangle/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 118. 杨辉三角 2 | 3 | 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 4 | 5 | ![](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) 6 | 7 | 在杨辉三角中,每个数是它左上方和右上方的数的和。 8 | 9 | **示例 :** 10 | ``` 11 | 输入: 5 12 | 输出: 13 | [ 14 | [1], 15 | [1,1], 16 | [1,2,1], 17 | [1,3,3,1], 18 | [1,4,6,4,1] 19 | ] 20 | ``` 21 | 22 | 23 | # 解题思路: 24 | 数学规律 25 | # 时间复杂度: 26 | O(n^2) 27 | # 空间复杂度 28 | O(1) 29 | 30 | # 代码 31 | 32 | ### 数学模拟zhao 33 | ```c++ 34 | class Solution { 35 | public: 36 | vector> generate(int n) { 37 | vector> res; 38 | if (n <= 0) return res; 39 | for (int i = 0; i < n; i++) { 40 | vector out(i+1,1); 41 | for (int j = 1; j < i; j++) { 42 | out[j] = res[i-1][j-1] + res[i-1][j]; 43 | } 44 | res.push_back(out); 45 | } 46 | return res; 47 | } 48 | }; 49 | ``` 50 | -------------------------------------------------------------------------------- /cpp/Path-Sum-II/Path-Sum-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> pathSum(TreeNode* root, int sum) { 4 | vector> res; 5 | if (root == NULL) 6 | return res; 7 | vector path; 8 | dfs(root, res, path, sum); 9 | return res; 10 | } 11 | void dfs(TreeNode* root, vector> &res, vector &path, int sum) 12 | { 13 | if (root == NULL) 14 | return; 15 | path.push_back(root->val); 16 | bool isLeaf = (root->left == NULL) && (root->right == NULL); 17 | if (sum == root->val && isLeaf) 18 | { 19 | res.push_back(path); 20 | } 21 | dfs(root->left, res, path, sum - root->val); 22 | dfs(root->right, res, path,sum - root->val); 23 | path.pop_back(); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /cpp/Path-Sum/Path-Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasPathSum(TreeNode* root, int sum) { 4 | bool res = false; 5 | if (root == NULL) 6 | return res; 7 | helper(root, sum, res); 8 | return res; 9 | } 10 | void helper(TreeNode* root, int expectNumber, bool &res) 11 | { 12 | if (root == NULL) 13 | return; 14 | bool isLeaf = root->left == NULL && root->right == NULL; 15 | if (expectNumber == root->val && isLeaf) 16 | { 17 | res = true; 18 | } 19 | helper(root->left, expectNumber-root->val, res); 20 | helper(root->right, expectNumber-root->val, res); 21 | } 22 | }; 23 | 24 | 25 | // Solution 2: 26 | class Solution { 27 | public: 28 | bool hasPathSum(TreeNode* root, int sum) { 29 | if (root==NULL) 30 | return false; 31 | sum -= root->val; 32 | bool isLeaf = (root->left==NULL) && (root->right==NULL); 33 | if (isLeaf) 34 | { 35 | return sum==0; 36 | } 37 | return hasPathSum(root->left, sum) || hasPathSum(root->right, sum); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Peak-Index-In-A-Mountain-Array/README.md: -------------------------------------------------------------------------------- 1 | O(n) 2 | ```c++ 3 | class Solution { 4 | public: 5 | int peakIndexInMountainArray(vector& A) { 6 | int n = A.size(); 7 | int res = 0; 8 | for (int i = 1; i < n; i++) { 9 | if (A[i] < A[i-1]){ 10 | res = i -1; 11 | break; 12 | } 13 | } 14 | return res; 15 | } 16 | }; 17 | ``` 18 | 19 | O(logn) 20 | ```c++ 21 | class Solution { 22 | public: 23 | int peakIndexInMountainArray(vector& A) { 24 | int n = A.size(); 25 | int l = 0; 26 | int r = n -1; 27 | while (l < r) { 28 | int mid = l + (r-l + 1) / 2; 29 | if (A[mid] > A[mid-1]) { 30 | l = mid; 31 | } else { 32 | r = mid - 1; 33 | } 34 | } 35 | return l; 36 | } 37 | }; 38 | ``` 39 | -------------------------------------------------------------------------------- /cpp/Perfect-Squares/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 完全平方数 2 | 3 | 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 4 | 5 | **示例 :** 6 | ``` 7 | 输入: n = 12 8 | 输出: 3 9 | 解释: 12 = 4 + 4 + 4. 10 | 11 | 输入: n = 13 12 | 输出: 2 13 | 解释: 13 = 4 + 9. 14 | ``` 15 | 16 | # 解题思路: 17 | 与零钱兑换那道题比较类似,利用dp来求解 18 | 19 | **定义状态:** 20 | - dp[i]表示组成和i的最少完全平方数个数 21 | 22 | **状态转移方程:** 23 | - dp[i] = min(dp[i], dp[i-j*j]+1]; 24 | 25 | **初始化:** 26 | - 初始化长度为n+1的数组dp,每个位置都为0 27 | 28 | **返回结果:** 29 | - dp[n] 30 | 31 | # 时间复杂度: 32 | O(n ^ 1.5) 33 | # 空间复杂度 34 | O(n) 35 | 36 | # 代码 37 | 38 | ### dp 39 | ```c++ 40 | class Solution { 41 | public: 42 | int numSquares(int n) { 43 | // 定义状态,dp[i]表示组成和i的最少完全平方数个数 44 | vector dp(n+1,0); // dp[0] = 0; 45 | for (int i=1;i<=n;i++) 46 | { 47 | dp[i] = i; // 最坏情况就是i个1组成 48 | for(int j=1;j*j<=i;j++) 49 | { 50 | // 状态转移方程 51 | dp[i] = min(dp[i], 1 + dp[i-j*j]); 52 | } 53 | } 54 | return dp[n]; 55 | } 56 | }; 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /cpp/Permutation-Sequence/Permutation-Sequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /cpp/Permutations-II/Image/DFS.png.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Permutations-II/Image/DFS.png.png -------------------------------------------------------------------------------- /cpp/Permutations-II/Permutations-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permuteUnique(vector& nums) { 4 | vector> res; 5 | vector out; 6 | int n = nums.size(); 7 | vector visited (n,0); 8 | if (nums.empty()) 9 | return res; 10 | sort(nums.begin(),nums.end()); 11 | DFS(nums,0,visited,out,res); 12 | return res; 13 | } 14 | void DFS(vector& nums, int level, vector& visited, vector& out, vector>& res) 15 | { 16 | int n = nums.size(); 17 | if (level==n) 18 | { 19 | res.push_back(out); 20 | return; 21 | } 22 | 23 | for (int i=0;i0 && nums[i]==nums[i-1] && visited[i-1]==0) //判断num[i]==nums[i-1]前提是有序,相同的数字才回相邻 26 | continue; 27 | if (visited[i]==1) 28 | continue; 29 | visited[i]=1; 30 | out.push_back(nums[i]); 31 | DFS(nums,level+1,visited, out, res); 32 | out.pop_back(); 33 | visited[i]=0; 34 | } 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /cpp/Permutations/Permutations.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | vector> permute(vector& nums) { 5 | vector> res; 6 | if (nums.empty()) return res; 7 | vector out; 8 | int n =nums.size(); 9 | vector visited(n,0); 10 | DFS(nums,0,visited,out,res); 11 | return res; 12 | } 13 | 14 | void DFS(vector& nums, int level, vector& visited, vector& out, vector>& res) 15 | { 16 | if (level == nums.size()) 17 | { 18 | res.push_back(out); 19 | return; 20 | } 21 | for (int i=0; i plusOne(vector& digits) { 30 | int n = digits.size(); 31 | for (int i=n-1;i>=0;--i) 32 | { 33 | digits[i]++; 34 | digits[i]%=10; 35 | if (digits[i]!=0) return digits; 36 | } 37 | digits.insert(digits.begin(),1); 38 | return digits; 39 | } 40 | }; 41 | ``` 42 | -------------------------------------------------------------------------------- /cpp/Positions-Of-Large-Groups/README.md: -------------------------------------------------------------------------------- 1 | ### 830. 较大分组的位置 2 | 3 | 在一个由小写字母构成的字符串 s 中,包含由一些连续的相同字符所构成的分组。 4 | 5 | 例如,在字符串 s = "abbxxxxzyy" 中,就含有 "a", "bb", "xxxx", "z" 和 "yy" 这样的一些分组。 6 | 7 | 分组可以用区间 [start, end] 表示,其中 start 和 end 分别表示该分组的起始和终止位置的下标。上例中的 "xxxx" 分组用区间表示为 [3,6] 。 8 | 9 | 我们称所有包含大于或等于三个连续字符的分组为 较大分组 。 10 | 11 | 找到每一个 较大分组 的区间,按起始位置下标递增顺序排序后,返回结果。 12 | 13 | 示例1: 14 | ``` 15 | 输入:s = "abbxxxxzzy" 16 | 输出:[[3,6]] 17 | 解释:"xxxx" 是一个起始于 3 且终止于 6 的较大分组。 18 | ``` 19 | 20 | ```c++ 21 | class Solution { 22 | public: 23 | vector> largeGroupPositions(string s) { 24 | vector> res; 25 | int n = s.size(); 26 | for (int i = 0; i < n; i++) { 27 | int count = 1; 28 | char c = s[i]; 29 | int j = i + 1; 30 | while (j < n && s[j] == c) { 31 | j++; 32 | count++; 33 | } 34 | if (count >= 3) { 35 | vector tmp; 36 | tmp.push_back(i); 37 | tmp.push_back(i + count - 1); 38 | res.push_back(tmp); 39 | } 40 | i = i + count - 1; 41 | } 42 | return res; 43 | } 44 | }; 45 | ``` 46 | -------------------------------------------------------------------------------- /cpp/PowX-N/PowX-N.cpp: -------------------------------------------------------------------------------- 1 | //Solution 1: 暴力求解法 2 | class Solution { 3 | public: 4 | double myPow(double x, int n) { 5 | double res=x; 6 | if (x==0) return 0; 7 | if (x==1) return 1; 8 | if (x==-1 && n%2==0) return 1; 9 | if (x==-1 && n%2!=0) return -1; 10 | if (n==-2147483648 && x>1) 11 | { 12 | res = 0.0; 13 | return res; 14 | } 15 | if (n==2147483647 && x<-1) 16 | { 17 | res = 0.0; 18 | return res; 19 | } 20 | if (n>0) 21 | { 22 | for (int i=1;in;i--) 30 | { 31 | res=res*x; 32 | } 33 | res = 1/res; 34 | } 35 | if (n==0) 36 | res = 1; 37 | return res; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Product-Of-Array-Except-Self/README.md: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | int n = nums.size(); 5 | vector res(n,1); 6 | int left = 1, right = 1; //left:从左边累乘,right:从右边累乘 7 | for (int i=0;i& votes) { 4 | string res = votes[0]; 5 | int n = votes[0].size(); 6 | map> m; 7 | for (auto s : votes) 8 | { 9 | for (int i=0;ibool 16 | { 17 | for (int i=0;i m[b][i]) return true; 20 | if (m[a][i] < m[b][i]) return false; 21 | } 22 | return a& rec1, vector& rec2) { 24 | if (rec2[0]>=rec1[2] || rec2[1]>=rec1[3] || rec2[2]<=rec1[0] || rec2[3]<=rec1[1]) 25 | return false; 26 | return true; 27 | } 28 | }; 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /cpp/Remove-Boxes/README.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | class Solution { 3 | public: 4 | int dp[100][100][100]; 5 | 6 | int removeBoxes(vector& boxes) { 7 | memset(dp, 0, sizeof dp); 8 | return calculatePoints(boxes, 0, boxes.size() - 1, 0); 9 | } 10 | 11 | int calculatePoints(vector& boxes, int l, int r, int k) { 12 | if (l > r) return 0; 13 | if (dp[l][r][k] != 0) return dp[l][r][k]; 14 | while (r > l && boxes[r] == boxes[r - 1]) { 15 | r--; 16 | k++; 17 | } 18 | dp[l][r][k] = calculatePoints(boxes, l, r - 1, 0) + (k + 1) * (k + 1); 19 | for (int i = l; i < r; i++) { 20 | if (boxes[i] == boxes[r]) { 21 | dp[l][r][k] = max(dp[l][r][k], calculatePoints(boxes, l, i, k + 1) + calculatePoints(boxes, i + 1, r - 1, 0)); 22 | } 23 | } 24 | return dp[l][r][k]; 25 | } 26 | }; 27 | ``` 28 | -------------------------------------------------------------------------------- /cpp/Remove-Duplicate-Letters/README.md: -------------------------------------------------------------------------------- 1 | ## 316. 去除重复字母 2 | 3 | 给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。 4 | 5 | #### 示例: 6 | ``` 7 | 输入:s = "bcabc" 8 | 输出:"abc" 9 | 10 | 输入:s = "cbacdcbc" 11 | 输出:"acdb" 12 | ``` 13 | ### 思路: 14 | 15 | 单调栈来求解, 16 | 17 | 具体算法: 18 | 19 | - 建立一个字典。其中 key 为 字符 c,value 为其出现的剩余次数。 20 | - 从左往右遍历字符串,每次遍历到一个字符,其剩余出现次数 - 1. 21 | - 对于每一个字符,如果其对应的剩余出现次数大于 1,我们可以选择丢弃(也可以选择不丢弃),否则不可以丢弃。 22 | - 是否丢弃的标准和上面题目类似。如果栈中相邻的元素字典序更大,那么我们选择丢弃相邻的栈中的元素。 23 | 24 | ### 代码: 25 | ```c++ 26 | class Solution { 27 | public: 28 | string removeDuplicateLetters(string s) { 29 | stack stk; 30 | int n = s.size(); 31 | unordered_map m; 32 | for (char &c : s) { 33 | m[c]++; 34 | } 35 | unordered_set st; 36 | for (char &c : s) { 37 | if (!st.count(c)) { 38 | while(!stk.empty() && c < stk.top() && m[stk.top()] > 0) { 39 | st.erase(stk.top()); 40 | stk.pop(); 41 | } 42 | st.insert(c); 43 | stk.push(c); 44 | } 45 | m[c] -= 1; 46 | } 47 | string res; 48 | while(!stk.empty()) { 49 | char c = stk.top(); 50 | stk.pop(); 51 | res += c; 52 | } 53 | reverse(res.begin(), res.end()); 54 | return res; 55 | } 56 | }; 57 | ``` 58 | -------------------------------------------------------------------------------- /cpp/Remove-Duplicate-Node/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 移除重复节点 2 | 3 | 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。 4 | 5 | **示例1 :** 6 | ``` 7 | 输入:[1, 2, 3, 3, 2, 1] 8 | 输出:[1, 2, 3] 9 | ``` 10 | **示例1 :** 11 | ``` 12 | 输入:[1, 1, 1, 1, 2] 13 | 输出:[1, 2] 14 | ``` 15 | 16 | # 解题思路: 17 | 一开始理解错题意了,利用哈希来做,链表题注意画图帮助理解. 18 | 19 | 利用哈希表,依次遍历每一个节点,如果这个节点的值不在于哈希表中,将该节点的值添加到哈希表中,否则将该节点删除 20 | # 时间复杂度: 21 | O(n) 22 | # 空间复杂度 23 | O(n) 24 | # 代码 25 | ### 哈希 26 | ```c++ 27 | /** 28 | * Definition for singly-linked list. 29 | * struct ListNode { 30 | * int val; 31 | * ListNode *next; 32 | * ListNode(int x) : val(x), next(NULL) {} 33 | * }; 34 | */ 35 | class Solution { 36 | public: 37 | ListNode* removeDuplicateNodes(ListNode* head) { 38 | if (head == NULL || head->next == NULL) return head; 39 | ListNode* dummyHead = new ListNode(-1); 40 | dummyHead->next = head; 41 | ListNode* pre = dummyHead; 42 | ListNode* cur = head; 43 | unordered_set s; 44 | while(cur != NULL) { 45 | if (s.count(cur->val)){ 46 | cur = cur->next; 47 | } 48 | else { 49 | s.insert(cur->val); 50 | pre->next = cur; 51 | pre = cur; 52 | cur = cur->next; 53 | } 54 | } 55 | pre->next = NULL; 56 | ListNode* res = dummyHead->next; 57 | delete dummyHead; 58 | return res; 59 | } 60 | }; 61 | ``` 62 | -------------------------------------------------------------------------------- /cpp/Remove-Duplicates-From-Sorted-List/Remove-Duplicates-From-Sorted-List.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /cpp/Remove-K-Digits/README.md: -------------------------------------------------------------------------------- 1 | ### 题目描述 移掉K位数字 2 | 3 | 给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。 4 | 5 | 注意: 6 | 7 | - num 的长度小于 10002 且 ≥ k。 8 | - num 不会包含任何前导零。 9 | 10 | **示例1:** 11 | ``` 12 | 输入: num = "1432219", k = 3 13 | 输出: "1219" 14 | 解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。 15 | ``` 16 | **示例2:** 17 | ``` 18 | 输入: num = "10200", k = 1 19 | 输出: "200" 20 | 解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。 21 | ``` 22 | **示例3:** 23 | ``` 24 | 输入: num = "10", k = 2 25 | 输出: "0" 26 | 解释: 从原数字移除所有的数字,剩余为空就是0。 27 | ``` 28 | 29 | ### 思路 30 | 31 | 本质还是单调栈的应用 32 | 33 | ```c++ 34 | 35 | ``` 36 | -------------------------------------------------------------------------------- /cpp/Remove-Linked-List-Elements/Images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Remove-Linked-List-Elements/Images/1.png -------------------------------------------------------------------------------- /cpp/Remove-Linked-List-Elements/Images/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Remove-Linked-List-Elements/Images/2.jpg -------------------------------------------------------------------------------- /cpp/Remove-Linked-List-Elements/Images/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Remove-Linked-List-Elements/Images/3.jpg -------------------------------------------------------------------------------- /cpp/Remove-Linked-List-Elements/Remove-Linked-List-Elements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* removeElements(ListNode* head, int val) { 12 | ListNode* p = new ListNode(-1); 13 | p->next = head; 14 | ListNode* prev = p; 15 | ListNode* cur = head; 16 | ListNode* del = NULL; 17 | while(cur) 18 | { 19 | if (cur->val==val) 20 | { 21 | prev->next = cur->next; 22 | del = cur; 23 | } 24 | else 25 | { 26 | prev = cur; 27 | } 28 | cur = cur->next; 29 | if (del) 30 | { 31 | delete del; 32 | del = NULL; 33 | } 34 | } 35 | ListNode* res = p->next; 36 | delete p; 37 | return res; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Repeated-Substring-Pattern/README.md: -------------------------------------------------------------------------------- 1 | ### 题目描述: 重复的子字符串 2 | 3 | 给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。 4 | 5 | i为子串的长度,对于任意的 i∈[n′,n),有 s[i]=s[i−n′] 6 | 7 | ```c++ 8 | class Solution { 9 | public: 10 | bool repeatedSubstringPattern(string s) { 11 | int n = s.size(); 12 | for (int i = 1; i * 2 <= n; i++) { 13 | if (n % i == 0) { 14 | bool flag = true; 15 | for (int j = i; j < n; j++) { 16 | if (s[j] != s[j-i]) { 17 | flag = false; 18 | break; 19 | } 20 | } 21 | if (flag) return true; 22 | } 23 | } 24 | return false; 25 | } 26 | }; 27 | ``` 28 | 当 s 没有循环节时: 29 | 30 | 如果 s 中没有循环节,那么 ss 中必然有且只有两个 s,此时从 ss[1] 处开始寻找 s ,必然只能找到第二个,所以此时返回值为 s.size()。 31 | 32 | 33 | 当 s 有循环节时: 34 | 35 | 当 s 中有循环节时,设循环节为 r,其长度为 l,那么 ss 中必然有 s.size()/l + 1 个 s。 36 | 因为去掉了第一个 S 的第一个字符 (代码中,(s+s).find(s, 1), 是从 ss[1] 处开始 find ) 37 | 所以此时必回找到第二个 s 的起点。 38 | 39 | ```c++ 40 | class Solution { 41 | public: 42 | bool repeatedSubstringPattern(string s) { 43 | return (s+s).find(s, 1) != s.size(); 44 | } 45 | }; 46 | ``` 47 | -------------------------------------------------------------------------------- /cpp/Reverse-Words-In-A-String-III/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 反转字符串中的单词 III 2 | 3 | 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 4 | 5 | **示例 1:** 6 | ``` 7 | 输入:"Let's take LeetCode contest" 8 | 输出:"s'teL ekat edoCteeL tsetnoc" 9 | ``` 10 | 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 11 | 12 | # 解题思路: 13 | 原地修改 14 | 15 | # 时间复杂度: 16 | O(n) 17 | # 空间复杂度 18 | O(1) 19 | 20 | # 代码 21 | ```c++ 22 | class Solution { 23 | public: 24 | string reverseWords(string s) { 25 | if (s.empty()) return s; 26 | int n = s.size(); 27 | int start = 0; 28 | for (int i = 0; i < n+1; i++) { 29 | if (s[i] == ' ' || s[i] == '\0') { 30 | int end = i - 1; 31 | while (start < end) { 32 | swap(s[start++], s[end--]); 33 | } 34 | start = i + 1; 35 | } 36 | } 37 | return s; 38 | } 39 | }; 40 | ``` 41 | -------------------------------------------------------------------------------- /cpp/Robot-Return-To-Origin/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ```c++ 4 | class Solution { 5 | public: 6 | bool judgeCircle(string moves) { 7 | int n = moves.size(); 8 | if (n & 1) return false; 9 | unordered_map m; 10 | for (char &c : moves) { 11 | m[c]++; 12 | } 13 | return m['L'] == m['R'] && m['U'] == m['D']; 14 | } 15 | }; 16 | ``` 17 | -------------------------------------------------------------------------------- /cpp/Rotate-Array/README.md: -------------------------------------------------------------------------------- 1 | # 题目: 旋转数组 2 | 3 | ## 题目描述: 4 | 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 5 | 6 | **示例1:** 7 | ``` 8 | 输入: [1,2,3,4,5,6,7] 和 k = 3 9 | 输出: [5,6,7,1,2,3,4] 10 | 解释: 11 | 向右旋转 1 步: [7,1,2,3,4,5,6] 12 | 向右旋转 2 步: [6,7,1,2,3,4,5] 13 | 向右旋转 3 步: [5,6,7,1,2,3,4] 14 | ``` 15 | 16 | **示例2:** 17 | ``` 18 | 输入: [-1,-100,3,99] 和 k = 2 19 | 输出: [3,99,-1,-100] 20 | 解释: 21 | 向右旋转 1 步: [99,-1,-100,3] 22 | 向右旋转 2 步: [3,99,-1,-100] 23 | ``` 24 | 25 | # 解题思路: 26 | 翻转:YX=(XT YT)T 27 | # 时间复杂度: 28 | O(n) 29 | # 空间复杂度 30 | O(1) 31 | # 代码 32 | ### 33 | ```c++ 34 | class Solution { 35 | public: 36 | void rotate(vector& nums, int k) { 37 | int n = nums.size(); 38 | int m = n-k%n; 39 | reverse(nums.begin(),nums.begin()+m);//reverse函数反转的范围是[first,last) 40 | reverse(nums.begin()+m,nums.end()); 41 | reverse(nums.begin(),nums.end()); 42 | } 43 | }; 44 | ``` 45 | 46 | ```c++ 47 | class Solution { 48 | public: 49 | void reverse(vector& nums, int i, int j) { 50 | while(i < j) { 51 | swap(nums[i++], nums[j--]); 52 | } 53 | } 54 | 55 | void rotate(vector& nums, int k) { 56 | int n = nums.size(); 57 | if (k <= 0) return; 58 | k = k % n; 59 | reverse(nums, n - k, n - 1); 60 | reverse(nums, 0, n - k - 1); 61 | reverse(nums, 0, n - 1); 62 | } 63 | }; 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /cpp/Rotate-Image/Images/guilv.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Rotate-Image/Images/guilv.JPG -------------------------------------------------------------------------------- /cpp/Rotate-Image/Rotate-Image.cpp: -------------------------------------------------------------------------------- 1 | //Solution 1: 2 | class Solution { 3 | public: 4 | void rotate(vector>& matrix) { 5 | int n = matrix.size(); 6 | 7 | //矩阵转置 8 | for (int i=0;i>& matrix) { 36 | int n = matrix.size(); 37 | for (int i=0;ival != q->val) return false; 45 | return isSameTree(p->left,q->left) && isSameTree(p->right, q->right); 46 | } 47 | }; 48 | ``` 49 | -------------------------------------------------------------------------------- /cpp/Single-Number-III/Single-Number-III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | vector res (2,0); 5 | int number = 0; 6 | int n = nums.size(); 7 | for (int i=0;i& nums) { 5 | int res =0; 6 | unordered_map map; 7 | int n=nums.size(); 8 | for (int i=0;i& nums) { 29 | int res=0; 30 | unordered_set st; 31 | for (int num : nums) 32 | { 33 | if (st.find(num)!=st.end()) // if (st.count(num)) 34 | st.erase(num); 35 | else 36 | st.insert(num); 37 | } 38 | res = *st.begin(); 39 | return res; 40 | } 41 | }; 42 | // C++ Solution 2: 43 | class Solution { 44 | public: 45 | int singleNumber(vector& nums) { 46 | int res=0; 47 | unordered_set st; 48 | for (int num : nums) 49 | { 50 | if (st.find(num)!=st.end()) // if (st.count(num)) 51 | st.erase(num); 52 | else 53 | st.insert(num); 54 | } 55 | res = *st.begin(); 56 | return res; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /cpp/Sort-An-Array/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 排序数组 2 | 3 | 给你一个整数数组 nums,将该数组升序排列。 4 | 5 | **示例 :** 6 | ``` 7 | 输入:nums = [5,2,3,1] 8 | 输出:[1,2,3,5] 9 | ``` 10 | 11 | # 解题思路: 12 | 各类排序算法 13 | 14 | # 时间复杂度: 15 | O(nlogn) 16 | # 空间复杂度 17 | O(1) 18 | # 代码 19 | 20 | ### 快排 21 | ```c++ 22 | class Solution { 23 | public: 24 | vector sortArray(vector& nums) { 25 | int n = nums.size(); 26 | quicksort(nums, 0, n-1); 27 | return nums; 28 | } 29 | void quicksort(vector &nums, int low, int high) 30 | { 31 | if (low>=high) return; 32 | int l=low, r=high, pivot = nums[l]; 33 | while(l= pivot) 36 | { 37 | r--; 38 | } 39 | nums[l] = nums[r]; 40 | while(l& A, int m, vector& B, int n) { 4 | int i = m-1; 5 | int j = n-1; 6 | int index = m+n-1; 7 | while (i>=0 && j>=0) 8 | { 9 | if(A[i]>=B[j]) 10 | { 11 | A[index--] = A[i--]; 12 | } 13 | else 14 | { 15 | A[index--] = B[j--]; 16 | } 17 | } 18 | // 下面这个while没必要写,这时候index 和i是相等的。 19 | // while (i>=0) A[index--] = A[i--]; 20 | while (j>=0) A[index--] = B[j--]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /cpp/Spiral-Matrix/Spiral-Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector spiralOrder(vector>& matrix) { 4 | vector res; 5 | if (matrix.empty()) return res; 6 | int m = matrix.size(); 7 | int n = matrix[0].size(); 8 | int u = 0; 9 | int d = m-1; 10 | int l = 0; 11 | int r = n-1; 12 | while(true) 13 | { 14 | for (int i=l;i<=r;i++) res.push_back(matrix[u][i]);//向右移动至最右 15 | if (++u > d) break;//重新定义上边界 16 | for (int i=u;i<=d;i++) res.push_back(matrix[i][r]);//向下 17 | if (--r < l) break;//重新定义右边界 18 | for (int i=r;i>=l;i--) res.push_back(matrix[d][i]);//向左 19 | if (--d < u) break;//重新定义下边界 20 | for (int i=d;i>=u;i--) res.push_back(matrix[i][l]);//向上 21 | if (++l > r) break;//重新定义左边界 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /cpp/Sqrtx/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 平方根 2 | 3 | 4 | 实现 int sqrt(int x) 函数。 5 | 6 | 计算并返回 x 的平方根,其中 x 是非负整数。 7 | 8 | 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 9 | 10 | **示例 :** 11 | ``` 12 | 输入: 8 13 | 输出: 2 14 | 说明: 8 的平方根是 2.82842..., 15 | 由于返回类型是整数,小数部分将被舍去。 16 | ``` 17 | # 解题思路: 18 | 二分法 19 | # 时间复杂度: 20 | O(logn) 21 | 22 | # 空间复杂度 23 | O(1) 24 | 25 | # 代码 26 | 27 | ### 二分法 28 | ```c++ 29 | class Solution { 30 | public: 31 | int mySqrt(int x) { 32 | if (x<=1) return x; 33 | long left = 0; 34 | long right = x; 35 | int res = 0; 36 | while(left<=right) 37 | { 38 | long mid = left + (right-left)/2; 39 | if (mid*mid<=x) 40 | { 41 | res = mid; 42 | left = mid+1; 43 | } 44 | else 45 | { 46 | right = mid -1; 47 | } 48 | } 49 | return res; 50 | } 51 | }; 52 | ``` 53 | 54 | ### 最优解法 考虑溢出 55 | ```c++ 56 | class Solution { 57 | public: 58 | int mySqrt(int x) { 59 | if (x==0) return 0; 60 | long l = 0; 61 | long r = x; 62 | while (l < r) { 63 | long mid = l + r + 1>> 1; 64 | if (x / mid >= mid) { 65 | l = mid; 66 | } else { 67 | r = mid - 1; 68 | } 69 | } 70 | return l; 71 | } 72 | }; 73 | ``` 74 | 75 | -------------------------------------------------------------------------------- /cpp/Subarray-Sum-Equals-K/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 和为K的子数组 2 | 3 | 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 4 | 5 | **示例 :** 6 | ``` 7 | 输入:nums = [1,1,1], k = 2 8 | 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 9 | ``` 10 | 11 | # 解题思路: 12 | 前缀和+哈希表 13 | 14 | 前缀和,最关键的思路是想到将连续的子序列转换为从头开始计算的两个队列和之差 15 | 16 | 17 | # 时间复杂度: 18 | O(n) 19 | # 空间复杂度 20 | O(n) 21 | # 代码 22 | 23 | ### 前缀和+哈希表 24 | ```c++ 25 | class Solution { 26 | public: 27 | int subarraySum(vector& nums, int k) { 28 | int res = 0; 29 | int n = nums.size(); 30 | unordered_map m; 31 | // 注意这里前缀和多了一个0,防止漏掉数组的前缀和刚好等于k的情况 32 | // 前缀和,最关键的思路是想到将连续的子序列转换为从头开始计算的两个队列和之差 33 | // sum = nums[0] + nums[1]+...nums[i] 34 | // nums[0]+..nums[j] = sum-k; 35 | // nums[j+1] +...+ nums[i] = k 36 | m[0]=1; 37 | int sum = 0; 38 | for (int i=0;i& A, int K) { 5 | unordered_map record = {{0, 1}}; 6 | int sum = 0, ans = 0; 7 | for (int elem: A) { 8 | sum += elem; 9 | // 注意 C++ 取模的特殊性,当被除数为负数时取模结果为负数,需要纠正 10 | int modulus = (sum % K + K) % K; 11 | if (record.count(modulus)) { 12 | ans += record[modulus]; 13 | } 14 | ++record[modulus]; 15 | } 16 | return ans; 17 | } 18 | }; 19 | 20 | /* 21 | 22 | A = [4,5,0,-2,-3,1] 23 | 24 | 循环A 25 | i = 0, preSum = (0 + 4) % 5 = 4, map中不存在4 => map[4] = 1 26 | i = 1, preSum = (4 + 5) % 5 = 4, map中存在4 => count += map[4] => count = 1, map[4] = map[4] + 1 = 2 27 | i = 2, preSum = (4 + 0) % 5 = 4, map中存在4 => count += map[4] => count = 3, map[4] = 3 28 | i = 3, preSum = (4 - 2) % 5 = 2, map中不存在2 => map[2] = 1 29 | i = 4, preSum = (2 - 3) % 5 = -1 小于0 => preSum = -1 + 5 = 4, map中存在4 => count += map[4] => count = 6, map[4] = 4 30 | i = 5, preSum = (4 + 1) % 5 = 0, map中存在0 => count += map[0] => count = 7, map[0] = 2 31 | */ 32 | ``` 33 | -------------------------------------------------------------------------------- /cpp/Subsets-II/README.md: -------------------------------------------------------------------------------- 1 | ### 题目描述 子集 2 | 3 | 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 4 | 5 | 说明:解集不能包含重复的子集。 6 | 7 | 示例: 8 | ``` 9 | 输入: [1,2,2] 10 | 输出: 11 | [ 12 | [2], 13 | [1], 14 | [1,2,2], 15 | [2,2], 16 | [1,2], 17 | [] 18 | ] 19 | ``` 20 | ### 解题思路 21 | 这种有重复的元素,一般套路是先排序,然后在dfs循环中再去判断。 22 | 23 | ```c++ 24 | class Solution { 25 | public: 26 | vector> subsetsWithDup(vector& nums) { 27 | if (nums.empty()) return res; 28 | int n = nums.size(); 29 | // 注意要先排序 30 | sort(nums.begin(), nums.end()); 31 | dfs(nums, n, 0); 32 | return res; 33 | } 34 | void dfs(vector &nums, int n, int start) { 35 | res.push_back(out); 36 | for (int i = start ; i < n; i++) { 37 | // 关键点 38 | if (i > start && nums[i] == nums[i-1]) continue; 39 | out.push_back(nums[i]); 40 | dfs(nums, n, i + 1); 41 | out.pop_back(); 42 | } 43 | } 44 | private: 45 | vector out; 46 | vector> res; 47 | }; 48 | ``` 49 | -------------------------------------------------------------------------------- /cpp/Subtree-Of-Another-Tree/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 另一个树的子树 2 | 3 | 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。 4 | 5 | 6 | **示例 :** 7 | 给定的树 s: 8 | ``` 9 | 3 10 | / \ 11 | 4 5 12 | / \ 13 | 1 2 14 | 给定的树 t: 15 | 4 16 | / \ 17 | 1 2 18 | ``` 19 | # 解题思路: 20 | 判断镜像二叉树类似 21 | 22 | 一个树是另一个树的子树 则 23 | 24 | - 要么这两个树相等 25 | - 要么这个树是左树的子树 26 | - 要么这个树hi右树的子树 27 | # 时间复杂度: 28 | O(n) 29 | 30 | # 空间复杂度 31 | O(n) 32 | 33 | # 代码 34 | 35 | ### 36 | ```c++ 37 | /** 38 | * Definition for a binary tree node. 39 | * struct TreeNode { 40 | * int val; 41 | * TreeNode *left; 42 | * TreeNode *right; 43 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 44 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 45 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 46 | * }; 47 | */ 48 | class Solution { 49 | public: 50 | bool isSubtree(TreeNode* s, TreeNode* t) { 51 | if (s==nullptr&&t==nullptr) return true; 52 | if (s==nullptr&&t!=nullptr) return false; 53 | return isSametree(s,t) || isSubtree(s->left,t)||isSubtree(s->right,t); 54 | } 55 | bool isSametree(TreeNode*s, TreeNode* t) 56 | { 57 | if(s==nullptr && t==nullptr) return true; 58 | return s&&t && s->val==t->val && isSametree(s->left, t->left) && isSametree(s->right,t->right); 59 | } 60 | }; 61 | ``` 62 | -------------------------------------------------------------------------------- /cpp/Summary-Ranges/README.md: -------------------------------------------------------------------------------- 1 | ### 汇总区间 2 | 给定一个无重复元素的有序整数数组 nums 。 3 | 4 | 返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x 。 5 | 6 | 列表中的每个区间范围 [a,b] 应该按如下格式输出: 7 | ``` 8 | "a->b" ,如果 a != b 9 | "a" ,如果 a == b 10 | ``` 11 | 示例1: 12 | ``` 13 | 输入:nums = [0,1,2,4,5,7] 14 | 输出:["0->2","4->5","7"] 15 | 解释:区间范围是: 16 | [0,2] --> "0->2" 17 | [4,5] --> "4->5" 18 | [7,7] --> "7" 19 | ``` 20 | ### 思路 21 | 模拟法,给定数组是有序的,直接寻找到第一个不是连续递增+1的即可。 22 | ```c++ 23 | class Solution { 24 | public: 25 | vector summaryRanges(vector& nums) { 26 | vector res; 27 | int n = nums.size(); 28 | for (int i = 0; i < n; i++) { 29 | int j = i; 30 | while (i + 1 < n && nums[i+1] == nums[i] +1) { 31 | i++; 32 | } 33 | string a = to_string(nums[j]); 34 | string b = to_string(nums[i]); 35 | if (a != b) { 36 | string tmp = a + "->" + b; 37 | res.push_back(tmp); 38 | } else { 39 | res.push_back(a); 40 | } 41 | } 42 | return res; 43 | } 44 | }; 45 | ``` 46 | -------------------------------------------------------------------------------- /cpp/Super-Egg-Drop/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Super-Egg-Drop/1.jpg -------------------------------------------------------------------------------- /cpp/Top-K-Frequent-Elements/README.md: -------------------------------------------------------------------------------- 1 | ## 前 K 个高频元素 2 | 3 | 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 4 | 5 | 示例1: 6 | ``` 7 | 输入: nums = [1,1,1,2,2,3], k = 2 8 | 输出: [1,2] 9 | ``` 10 | 11 | 12 | 前k大,用小顶堆,前k小用大顶堆 13 | ```c++ 14 | class Solution { 15 | public: 16 | vector topKFrequent(vector& nums, int k) { 17 | vector res; 18 | if (nums.empty()) return res; 19 | unordered_map m; 20 | for (int num : nums) m[num]++; 21 | priority_queue, vector>, greater>> heap; 22 | for (auto p : m) { 23 | heap.push({p.second, p.first}); 24 | if (heap.size() > k) { 25 | heap.pop(); 26 | } 27 | } 28 | while(!heap.empty()) { 29 | res.push_back(heap.top().second); 30 | heap.pop(); 31 | } 32 | reverse(res.begin(), res.end()); 33 | return res; 34 | } 35 | }; 36 | ``` 37 | -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/1.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/2.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/3.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/4.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/5.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/6.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/7.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/8.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/9.png -------------------------------------------------------------------------------- /cpp/Trapping-Rain-Water/Image/rainwatertrap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bryceustc/LeetCode_Note/d3ee37d7257583b03c7d2ab37ffb52dacc5f41d2/cpp/Trapping-Rain-Water/Image/rainwatertrap.png -------------------------------------------------------------------------------- /cpp/Ugly-Number/Ugly-Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int num) { 4 | if (num<1) 5 | return false; 6 | while(num%5==0) 7 | { 8 | num/=5; 9 | } 10 | while(num%3==0) 11 | { 12 | num/=3; 13 | } 14 | while(num%2==0) 15 | { 16 | num/=2; 17 | } 18 | return num==1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /cpp/Valid-Mountain-Array/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 有效的山脉数组 2 | 3 | 给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false。 4 | 5 | 让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组: 6 | 7 | - A.length >= 3 8 | - 在 0 < i < A.length - 1 条件下,存在 i 使得: 9 | - A[0] < A[1] < ... A[i-1] < A[i] 10 | - A[i] > A[i+1] > ... > A[A.length - 1] 11 | 12 | **示例 1:** 13 | ``` 14 | 输入:[2,1] 15 | 输出:false 16 | ``` 17 | 18 | **示例 2:** 19 | ``` 20 | 输入:[3,5,5] 21 | 输出:false 22 | ``` 23 | 24 | 25 | # 解题思路: 26 | 27 | 二分查找 28 | 29 | # 时间复杂度: 30 | 31 | O(logn) 32 | 33 | # 空间复杂度 34 | O(1) 35 | 36 | # 代码 37 | ```c++ 38 | class Solution { 39 | public: 40 | bool validMountainArray(vector& A) { 41 | int n = A.size(); 42 | if (n < 3) return false; 43 | int l = 0, r = n-1; 44 | while(l < n - 2 && A[l] < A[l+1]) l++; 45 | while(r > 1 && A[r] < A[r-1]) r--; 46 | return l == r; 47 | } 48 | }; 49 | ``` 50 | -------------------------------------------------------------------------------- /cpp/Valid-Palindrome/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 验证回文串 2 | 3 | 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 4 | 5 | 说明:本题中,我们将空字符串定义为有效的回文串。 6 | 7 | **示例 1:** 8 | ``` 9 | 输入: "A man, a plan, a canal: Panama" 10 | 输出: true 11 | ``` 12 | **示例 2:** 13 | ``` 14 | 输入: "race a car" 15 | 输出: false 16 | ``` 17 | 18 | # 解题思路: 19 | 20 | 记一下 c++的几个内置函数 21 | 22 | islower(char c) 是否为小写字母 23 | 24 | isupper(char c) 是否为大写字母 25 | 26 | isdigit(char c) 是否为数字 27 | 28 | isalpha(char c) 是否为字母 29 | 30 | isalnum(char c) 是否为字母或者数字 31 | 32 | toupper(char c) 字母小转大 33 | 34 | tolower(char c) 字母大转小 35 | 36 | # 时间复杂度: 37 | O(n) 38 | # 空间复杂度 39 | O(1) 40 | 41 | # 代码 42 | 43 | ### 双指针 44 | ```c++ 45 | class Solution { 46 | public: 47 | bool isPalindrome(string s) { 48 | string tmp; 49 | for (const char& c : s) { 50 | for (const char& c : s) { 51 | if (islower(c) || isdigit(c)) { 52 | tmp += c; 53 | } 54 | else if (isupper(c)) { 55 | tmp += (c+32); // tmp += tolower(c); 56 | } 57 | } 58 | int n = tmp.size(); 59 | int i = 0; 60 | int j = n - 1; 61 | while (i < j) { 62 | if (tmp[i]!=tmp[j]) { 63 | return false; 64 | } 65 | else { 66 | i++; 67 | j--; 68 | } 69 | } 70 | return true; 71 | } 72 | }; 73 | ``` 74 | -------------------------------------------------------------------------------- /cpp/Valid-Parentheses/Valid-Parentheses.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// Source : https://leetcode-cn.com/problems/valid-parentheses/ 3 | /// Author : bryce 4 | /// Time : 2019-11-11 5 | 6 | /* 7 | 栈结构 8 | 使用数据栈结构: 9 | 1.遇到左括号,就进行压栈 10 | 2.遇到右括号,如果此时栈为空,则直接返回false,如果不为空,就取出栈顶元素判断是否和当前括号匹配,若不匹配就返回false,否则匹配弹出栈顶 11 | 3.最后判断栈是否为空,若为空则合法,否则不合法 12 | 13 | 时间复杂度:只要遍历一次整个序列,所以是O(n)的 14 | 15 | 空间复杂度:栈需要O(n)的空间 16 | 17 | */ 18 | class Solution { 19 | public: 20 | bool isValid(string s) { 21 | int n = s.size(); 22 | stack stk; 23 | if (n % 2 != 0) return false; //判断元素个数是否为奇数,奇数直接返回false 24 | for (int i = 0; i < n; i++) 25 | { 26 | if (s[i] == '(' || s[i] == '[' || s[i] == '{') 27 | stk.push(s[i]); 28 | else 29 | { 30 | if (stk.empty()) return false; 31 | if (s[i] == ')' && stk.top() != '(') return false; 32 | if (s[i] == ']' && stk.top() != '[') return false; 33 | if (s[i] == '}' && stk.top() != '{') return false; 34 | stk.pop(); // pop 元素出栈 35 | } 36 | } 37 | return (stk.empty()); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /cpp/Validate-Stack-Sequences/Validate-Stack-Sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validateStackSequences(vector& pushed, vector& popped) { 4 | int n = pushed.size(); 5 | int m = popped.size(); 6 | if (n!=m) return false; 7 | stack s; 8 | int index = 0; 9 | for (int i=0;i str2ch; 6 | unordered_map ch2str; 7 | int m = str.length(); 8 | int i = 0; 9 | for (auto ch : pattern) { 10 | if (i >= m) { 11 | return false; 12 | } 13 | int j = i; 14 | while (j < m && str[j] != ' ') j++; 15 | const string &tmp = str.substr(i, j - i); 16 | if (str2ch.count(tmp) && str2ch[tmp] != ch) { 17 | return false; 18 | } 19 | if (ch2str.count(ch) && ch2str[ch] != tmp) { 20 | return false; 21 | } 22 | str2ch[tmp] = ch; 23 | ch2str[ch] = tmp; 24 | i = j + 1; 25 | } 26 | return i >= m; 27 | } 28 | }; 29 | ``` 30 | -------------------------------------------------------------------------------- /cpp/X-Of-A-Kind-In-A-Deck-Of-Cards/README.md: -------------------------------------------------------------------------------- 1 | # 题目描述: 卡牌分组 2 | 3 | 给定一副牌,每张牌上都写着一个整数。 4 | 5 | 此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组: 6 | 7 | 每组都有 X 张牌。 8 | 组内所有的牌上都写着相同的整数。 9 | 仅当你可选的 X >= 2 时返回 true。 10 | 11 | 12 | **示例 :** 13 | ``` 14 | 输入:[1,2,3,4,4,3,2,1] 15 | 输出:true 16 | 解释:可行的分组是 [1,1],[2,2],[3,3],[4,4] 17 | ``` 18 | **示例 :** 19 | ``` 20 | 输入:[1,1,1,2,2,2,3,3] 21 | 输出:false 22 | 解释:没有满足要求的分组。 23 | 24 | 输入:[1,1,2,2,2,2] 25 | 输出:true 26 | 解释:可行的分组是 [1,1],[2,2],[2,2] 27 | 28 | ``` 29 | 30 | # 解题思路: 31 | 统计各个数出现的次数,然后求次数之间是否存在公约数 32 | 33 | # 时间复杂度: 34 | O(n) 35 | # 空间复杂度 36 | O(n) 37 | # 代码 38 | 39 | ### 哈希 40 | ```c++ 41 | class Solution { 42 | public: 43 | bool hasGroupsSizeX(vector& deck) { 44 | if (deck.size() < 2) return false; 45 | // 可以用数组,因为都为小写字母 46 | unordered_map m; 47 | for (int a : deck) 48 | { 49 | m[a]++; 50 | } 51 | int x = m[deck[0]]; 52 | for (int a : deck) 53 | { 54 | if (m[a]>0) 55 | { 56 | x = __gcd(x, m[a]); 57 | if (x==1) 58 | return false; 59 | } 60 | } 61 | return x>=2; 62 | } 63 | }; 64 | ``` 65 | ## 参考 66 | - [题解](https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/solution/qiu-jie-zui-da-gong-yue-shu-java-by-liweiwei1419/) 67 | -------------------------------------------------------------------------------- /cpp/Zigzag-Conversion/Zigzag-Conversion.cpp: -------------------------------------------------------------------------------- 1 | /// Source : https://leetcode-cn.com/problems/zigzag-conversion/submissions/ 2 | /// Author : bryce 3 | /// Time : 2019-10-26 4 | class Solution { 5 | public: 6 | string convert(string s, int numRows) { 7 | string res; 8 | int n = s.length(); 9 | int m = 2*numRows -2; 10 | if (numRows == 1) return s; 11 | for(int i = 0; i < numRows; i++ ) 12 | { 13 | if(i == 0 || i == numRows -1) 14 | { 15 | for (int j = i; j i: 23 | sum_res = nums[i] + nums[j] + nums[k] 24 | newDiff = abs(sum_res - target) 25 | if diff > newDiff : 26 | diff = newDiff 27 | res = sum_res 28 | if sum_res < target: 29 | i += 1 30 | else: 31 | j -= 1 32 | k +=1 33 | return res 34 | -------------------------------------------------------------------------------- /python/3Sum/3Sum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-06 4 | # Author: Bryce 5 | 6 | class Solution(object): 7 | def threeSum(self, nums): 8 | """ 9 | :type nums: List[int] 10 | :rtype: List[List[int]] 11 | """ 12 | nums= sorted(nums) 13 | res=[] 14 | k = 0 15 | while k < len(nums)-1: 16 | while k > 0 and k <= len(nums)-1 and nums[k] == nums[k-1]: 17 | k+=1 18 | l = k + 1 19 | r = len(nums) - 1 20 | while (l < r): 21 | if nums[k] + nums[l] + nums[r] == 0: 22 | res.append([nums[k],nums[l],nums[r]]) 23 | while l < r and nums[l] == nums[l+1]: 24 | l+=1 25 | while l < r and nums[r] == nums[r-1]: 26 | r-=1 27 | l+=1 28 | r-=1 29 | elif nums[k] + nums[l] + nums[r] < 0: 30 | l+=1 31 | elif nums[k] + nums[l] + nums[r] > 0: 32 | r-=1 33 | k+=1 34 | return res 35 | -------------------------------------------------------------------------------- /python/4Sum/4Sum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-09 4 | # Author: Bryce 5 | class Solution(object): 6 | def fourSum(self, nums, target): 7 | """ 8 | :type nums: List[int] 9 | :type target: int 10 | :rtype: List[List[int]] 11 | """ 12 | res = [] 13 | nums = sorted(nums) 14 | n = len(nums) 15 | if n < 3: 16 | return res 17 | for i in range(n-3): 18 | if i>0 and nums[i] == nums[i-1]: 19 | continue 20 | for j in range(i+1,n-2): 21 | if j > i+1 and nums[j] == nums[j-1]: 22 | continue 23 | l = j+1 24 | r = n-1 25 | while l target: 38 | r-=1 39 | return res 40 | -------------------------------------------------------------------------------- /python/Add-Strings/Add-Strings.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-12-5 4 | # Author: Bryce 5 | 6 | class Solution: 7 | def addStrings(self, num1: str, num2: str) -> str: 8 | res ="" 9 | n1 = len(num1) 10 | n2 = len(num2) 11 | i = n1-1 12 | j = n2-1 13 | carry = 0 14 | while i >=0 or j >=0: 15 | if i < 0: 16 | temp = ord(num2[j]) - ord('0') + carry 17 | if j < 0: 18 | temp = ord(num1[i]) - ord('0') + carry 19 | if i>=0 and j>=0: 20 | temp = (ord(num1[i]) -ord('0')) + (ord(num2[j]) - ord('0')) + carry 21 | carry = temp // 10 22 | temp = temp%10 23 | res += str(temp) 24 | i=i-1 25 | j=j-1 26 | if carry>0: 27 | res+=str(carry) 28 | return res[::-1] 29 | -------------------------------------------------------------------------------- /python/Add_Two_Numbers/Add_Two_Numbers.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Author: Bryce 4 | class ListNode(object): 5 | def __init__(self, x): 6 | self.val = x 7 | self.next = None 8 | 9 | 10 | class Solution(object): 11 | def addTwoNumbers(self, l1, l2): 12 | carry = 0 13 | # dummy head 14 | sum_val = l3 = ListNode(0) #引用ListNode类定义一个链表节点并初始化值为0 15 | while l1 or l2: #l1或l2不为空就持续执行 16 | val = carry 17 | if l1: #l1不为空,就把l1的某个节点值相加val再复制给val 18 | val += l1.val 19 | l1 = l1.next 20 | if l2: #l2不为空,就把l2的某个节点值相加val再复制给val 21 | val += l2.val 22 | l2 = l2.next 23 | l3.next = ListNode(val % 10) 24 | l3 = l3.next 25 | carry = val / 10 26 | if carry > 0: 27 | l3.next = ListNode(carry) 28 | return sum_val.next 29 | -------------------------------------------------------------------------------- /python/Balanced-Binary-Tree/Balanced-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isBalanced(self, root: TreeNode) -> bool: 3 | if root is None: 4 | return True 5 | left = self.TreeDepth(root.left) 6 | right = self.TreeDepth(root.right) 7 | if abs(left-right)>1: 8 | return False 9 | return self.isBalanced(root.left) and self.isBalanced(root.right) 10 | def TreeDepth(self, root): 11 | if root is None: 12 | return 0 13 | left = self.TreeDepth(root.left) 14 | right = self.TreeDepth(root.right) 15 | return max(left, right) + 1 16 | class Solution: 17 | def isBalanced(self, root: TreeNode) -> bool: 18 | if root is None: 19 | return True 20 | return self.helper(root)[0] 21 | def helper(self, root): 22 | if root is None: 23 | return True, 0 24 | leftIsBalanced, left = self.helper(root.left) 25 | if not leftIsBalanced: 26 | return False, 0 27 | rightIsBalanced,right = self.helper(root.right) 28 | if not rightIsBalanced: 29 | return False, 0 30 | return (abs(left - right)<=1), max(left, right) +1 31 | -------------------------------------------------------------------------------- /python/Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def inorderTraversal(self, root: TreeNode) -> List[int]: 3 | res = [] 4 | if root == None: 5 | return res 6 | self.helper(root,res) 7 | return res 8 | def helper(self,root,res): 9 | if root is None: 10 | return 11 | self.helper(root.left,res) 12 | res.append(root.val) 13 | self.helper(root.right,res) 14 | 15 | 16 | class Solution: 17 | def inorderTraversal(self, root: TreeNode) -> List[int]: 18 | res = [] 19 | if root is None: 20 | return res 21 | s = [] 22 | p = root 23 | while p or s: 24 | while p!=None: 25 | s.append(p) 26 | p = p.left 27 | p = s.pop() 28 | res.append(p.val) 29 | p = p.right 30 | return res 31 | -------------------------------------------------------------------------------- /python/Binary-Tree-Level-Order-Traversal/Binary-Tree-Level-Order-Traversal.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | class Solution { 3 | public: 4 | vector> levelOrder(TreeNode* root) { 5 | vector> res; 6 | if (root==NULL) 7 | return res; 8 | helper(root, res,0); 9 | return res; 10 | } 11 | 12 | void helper(TreeNode* root, vector> &res, int level) 13 | { 14 | if (root==NULL) 15 | return; 16 | if (res.size()==level) 17 | res.push_back(vector()); 18 | res[level].push_back(root->val); 19 | if (root->left) 20 | helper(root->left,res,level+1); 21 | if (root->right) 22 | helper(root->right,res,level+1); 23 | } 24 | }; 25 | ## Python Solution 2: 26 | class Solution: 27 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 28 | res = [] 29 | if root is None: 30 | return res 31 | q = [] 32 | q.append(root) 33 | while q: 34 | n = len(q) 35 | out = [] 36 | while n>0: 37 | node = q.pop(0) 38 | out.append(node.val) 39 | if node.left: 40 | q.append(node.left) 41 | if node.right: 42 | q.append(node.right) 43 | n-=1 44 | res.append(out[:]) 45 | return res 46 | -------------------------------------------------------------------------------- /python/Binary-Tree-Postorder-Traversal/Binary-Tree-Postorder-Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def postorderTraversal(self, root: TreeNode) -> List[int]: 3 | res = [] 4 | if root == None: 5 | return res 6 | self.helper(root,res) 7 | return res 8 | def helper(self,root,res): 9 | if root is None: 10 | return 11 | self.helper(root.left,res) 12 | self.helper(root.right,res) 13 | res.append(root.val) 14 | 15 | 16 | 17 | class Solution: 18 | def postorderTraversal(self, root: TreeNode) -> List[int]: 19 | res = [] 20 | if root is None: 21 | return res 22 | s = [] 23 | s.append(root) 24 | while s: 25 | node = s.pop() 26 | if node.left: 27 | s.append(node.left) 28 | if node.right: 29 | s.append(node.right) 30 | res.append(node.val) 31 | return res[::-1] 32 | -------------------------------------------------------------------------------- /python/Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: 3 | res = [] 4 | if root is None: 5 | return res 6 | q = collections.deque() 7 | q.append(root) 8 | zigzag = True 9 | while q: 10 | n = len(q) 11 | out = [] 12 | node = None 13 | while n>0: 14 | if zigzag: 15 | node = q.popleft() 16 | if node.left: 17 | q.append(node.left) 18 | if node.right: 19 | q.append(node.right) 20 | else: 21 | node = q.pop() 22 | if node.right: 23 | q.appendleft(node.right) 24 | if node.left: 25 | q.appendleft(node.left) 26 | out.append(node.val) 27 | n-=1 28 | res.append(out[:]) 29 | zigzag= not zigzag 30 | return res 31 | -------------------------------------------------------------------------------- /python/Coin-Change/Coin-Change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def coinChange(self, coins: List[int], amount: int) -> int: 3 | res = -1 4 | dp = [amount+1 for _ in range(amount+1)] 5 | dp[0] = 0 6 | n = len(dp) 7 | for i in range(n): 8 | for coin in coins: 9 | if i < coin: 10 | continue 11 | dp[i] = min(dp[i], dp[i-coin]+1) 12 | if dp[amount]==amount+1: 13 | res = -1 14 | else: 15 | res = dp[amount] 16 | return res 17 | -------------------------------------------------------------------------------- /python/Combination-Sum-II/Combination-Sum-II.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-12-1 4 | # Author: Bryce 5 | 6 | from typing import List 7 | class Solution: 8 | def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 9 | res = [] 10 | out = [] 11 | candidates = sorted(candidates) 12 | self.DFS(candidates,target,0,out,res) 13 | return res 14 | def DFS(self,candidates: List[int], target:int, start: int, out: List[int], res: List[List[int]]): 15 | if target < 0: 16 | return 17 | if target == 0: 18 | res.append(out[:]) 19 | return 20 | n = len(candidates) 21 | for i in range(start,n): 22 | if candidates[i] == candidates[i-1] and i > start: 23 | continue 24 | out.append(candidates[i]) 25 | self.DFS(candidates,target-candidates[i],i+1,out,res) 26 | del out[-1] 27 | 28 | if __name__ == " __main__ ": 29 | candidates = [10,1,2,7,6,1,5] 30 | target = 8 31 | print (Solution().combinationSum2(candidates, target)) 32 | -------------------------------------------------------------------------------- /python/Combination-Sum/Combination-Sum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-30 4 | # Author: Bryce 5 | 6 | from typing import List 7 | 8 | class Solution: 9 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 10 | res = [] 11 | out = [] 12 | self.DFS(candidates, target, 0, out, res) 13 | return res 14 | def DFS(self, candidates: List[int], target: int, start: int, out: List[int], res: List[List[int]]): 15 | if target < 0: return 16 | if target == 0: 17 | res.append(out[:]) 18 | return 19 | n = len(candidates) 20 | for i in range (start,n): 21 | out.append(candidates[i]) 22 | self.DFS(candidates,target-candidates[i],i,out,res) 23 | out.pop() ## out.pop(-1) or del out[-1] 24 | 25 | 26 | 27 | if __name__ == " __main__ ": 28 | candidates = [ 2 , 3 , 6 , 7 ] 29 | target = 7 30 | print ( Solution().combinationSum (candidates, target) ) 31 | -------------------------------------------------------------------------------- /python/Container-With-Most-Water/Container-With-Most-Water.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-02 4 | # Author: Bryce 5 | class Solution(object): 6 | def maxArea(self, height): 7 | """ 8 | :type height: List[int] 9 | :rtype: int 10 | """ 11 | res = 0 12 | if len(height) < 2: 13 | return 0 14 | for i in range(0,len(height)): 15 | j = i 16 | for j in range(0,len(height)): 17 | width = j - i 18 | high = min (height[i],height[j]) 19 | res = max(res, width * high) 20 | return res 21 | -------------------------------------------------------------------------------- /python/Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List/Convert-Binary-Search-Tree-To-Sorted-Doubly-Lnked-List.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def treeToDoublyList(self, root: 'Node') -> 'Node': 3 | if root is None: 4 | return None 5 | pre = None 6 | pre = self.helper(root, pre) 7 | head = pre 8 | while head and head.left: 9 | head = head.left 10 | pre.right = head 11 | head.left = pre 12 | return head 13 | def helper(self, cur, pre): 14 | if cur == None: 15 | return pre 16 | pre = self.helper(cur.left, pre) 17 | cur.left = pre 18 | if pre: 19 | pre.right = cur 20 | pre = cur 21 | return self.helper(cur.right, pre) 22 | -------------------------------------------------------------------------------- /python/Count-And-Say/Count-And-Say.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-29 4 | # Author: Bryce 5 | 6 | 7 | ###########Python Solution 1: 8 | class Solution: 9 | def countAndSay(self, n: int) -> str: 10 | if n==0: return "" 11 | res = '1' 12 | for i in range(1,n): 13 | temp, num, count = '', res[0], 1 14 | for j in range(1,len(res)): 15 | if res[j] == num:count += 1 16 | else: 17 | temp += str(count) + num 18 | num = res[j] 19 | count = 1 20 | temp += str(count) + num 21 | res = temp 22 | return res 23 | 24 | ###########Python Solution 2: 25 | 26 | class Solution: 27 | def countAndSay(self, n: int, res='1') -> str: 28 | return res if n == 1 else self.countAndSay(n-1, ''.join([str(len(list(gen)))+val for val, gen in groupby(res)]) 29 | -------------------------------------------------------------------------------- /python/Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /python/Diameter-Of-Binary-Tree/Diameter-Of-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.res = 0 4 | 5 | def diameterOfBinaryTree(self, root: TreeNode) -> int: 6 | self.dfs(root) 7 | return self.res 8 | 9 | def dfs(self, root): 10 | if root is None: 11 | return 0 12 | left = self.dfs(root.left) 13 | right = self.dfs(root.right) 14 | self.res = max(left+right, self.res) 15 | return max(left, right) + 1 16 | -------------------------------------------------------------------------------- /python/Distribute-Candies-To-People/Distribute-Candies-To-People.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def distributeCandies(self, candies: int, num_people: int) -> List[int]: 3 | res = [0]*num_people 4 | i =0 5 | while candies >i: 6 | res[i%num_people] += i+1 7 | candies -= i+1 8 | i+=1 9 | res[i%num_people]+= candies 10 | return res 11 | 12 | 13 | class Solution: 14 | def distributeCandies(self, candies: int, num_people: int) -> List[int]: 15 | # 为了方便理解,把num_people赋值给n,即n个小朋友 16 | n = num_people 17 | # 套用上面推出来的公式,直接计算可以完整发放糖果的次数p 18 | p = int((2 * candies + 0.25)**0.5 - 0.5) 19 | # 继续套用公式,算出完整发放糖果以后剩余的糖果数量 20 | R = int(candies - (p + 1) * p * 0.5) 21 | # 迭代rows轮,cols是倒霉孩子的下标 22 | rows, cols = p // n, p % n 23 | 24 | # 小朋友们端好了碗,等你发糖 25 | kids = [0] * n 26 | for i in range(n): 27 | # 性感coder,在线发糖 28 | kids[i] = (i + 1) * rows + int(rows * (rows - 1) * 0.5) * n 29 | # 最后一轮or在p=x): 23 | temp = x 24 | s = 1 25 | while y > temp + temp: 26 | temp+=temp 27 | s+=s 28 | res+=s 29 | y-=temp 30 | if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0): 31 | res*=-1 32 | return res 33 | -------------------------------------------------------------------------------- /python/Find-Minimum-In-Rotated-Sorted-Array/Find-Minimum-In-Rotated-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | class Solution: 3 | def findMin(self, nums: List[int]) -> int: 4 | n = len(nums) 5 | if n==0: 6 | return 0 7 | res = nums[0] 8 | for i in range (n): 9 | if res >nums[i]: 10 | res = nums[i] 11 | return res 12 | 13 | 14 | ## Python Solution 2: 15 | class Solution: 16 | def findMin(self, nums: List[int]) -> int: 17 | n = len(nums) 18 | if n==0: 19 | return 0 20 | res = nums[0] 21 | start = 0 22 | end = n-1 23 | while end>=start: 24 | mid = start+(end-start)//2 25 | if nums[mid]>=res: 26 | start=mid+1 27 | if nums[mid] int: 35 | n = len(nums) 36 | if n==0: 37 | return 0 38 | res = nums[0] 39 | for i in range (n): 40 | if res >nums[i]: 41 | res = nums[i] 42 | return res 43 | -------------------------------------------------------------------------------- /python/Find-The-Duplicate-Number/Find-The-Duplicate-Number.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-12-2 4 | # Author: Bryce 5 | 6 | 7 | ### Python Solution 1: 8 | class Solution: 9 | def findDuplicate(self, nums: List[int]) -> int: 10 | n = len(nums)-1 11 | start = 1 12 | end = n 13 | while end > start: 14 | mid = start + (end-start)//2 15 | k = 0 16 | for num in nums: 17 | if num<=mid and num>=start: 18 | k+=1 19 | if k > mid-start+1: 20 | end = mid 21 | else: 22 | start = mid +1 23 | return start 24 | 25 | 26 | ##### Python Solution 2: 27 | class Solution: 28 | def findDuplicate(self, nums: List[int]) -> int: 29 | res = 0 30 | nums = sorted(nums) 31 | for i in range(1,len(nums)): 32 | if nums[i] == nums[i-1]: 33 | res = nums[i] 34 | break 35 | return res 36 | 37 | ####Python Solution 3: 38 | dic = {} 39 | res = 0 40 | for index,num in enumerate(nums): 41 | if num in dic: 42 | res = num 43 | else: 44 | dic[num]=index 45 | return res 46 | -------------------------------------------------------------------------------- /python/First-Missing-Positive/First-Missing-Positive.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-12-2 4 | # Author: Bryce 5 | -------------------------------------------------------------------------------- /python/First-Unique-Character-In-A-String/First-Unique-Character-In-A-String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstUniqChar(self, s: str) -> int: 3 | n = len(s) 4 | res = -1 5 | if n==0: 6 | return res 7 | count = collections.Counter(s) 8 | for index,ch in enumerate(s): 9 | if count[ch]==1: 10 | return index 11 | return res 12 | -------------------------------------------------------------------------------- /python/Generate-Parentheses/Generate-Parentheses.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-13 4 | # Author: Bryce 5 | 6 | 7 | ###Python Solution 1: 8 | class Solution(object): 9 | def generateParenthesis(self, n): 10 | """ 11 | :type n: int 12 | :rtype: List[str] 13 | """ 14 | res = [] 15 | out = "" 16 | if n==0: 17 | return res 18 | res = self.DFS(n,n,out,res) 19 | return res 20 | def DFS(self,l,r,out,res): 21 | if l == 0 and r == 0: 22 | res.append(out) 23 | if l > 0: 24 | self.DFS(l-1,r,out+'(',res) 25 | if r > 0 and r > l: 26 | self.DFS(l,r-1,out+')',res) 27 | return res 28 | -------------------------------------------------------------------------------- /python/Group-Anagrams/Group-Anagrams.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | ##### Solution 1: 4 | class Solution: 5 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 6 | res = [] 7 | n = len(strs) 8 | if n==0: 9 | return res 10 | dic = {} 11 | for s in strs: 12 | t = s 13 | t = "".join(sorted(t)) 14 | if t not in dic: 15 | dic[t] = len(res) 16 | res.append([]) 17 | res[dic[t]].append(s) 18 | return res 19 | 20 | 21 | 22 | 23 | ### Solution 2: 24 | class Solution: 25 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 26 | res = [] 27 | dic = {} 28 | m ={} 29 | n = len(strs) 30 | if n==0: 31 | return res 32 | for s in strs: 33 | t = s 34 | t = "".join(sorted(t)) 35 | if t not in dic: 36 | dic[t] = [s] 37 | else: 38 | dic[t].append(s) 39 | res = list(dic.values()) 40 | return res 41 | -------------------------------------------------------------------------------- /python/Implement-Stack-Using-Queues/Implement-Stack-Using-Queues.py: -------------------------------------------------------------------------------- 1 | class MyStack: 2 | 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.q = [] 8 | 9 | def push(self, x: int) -> None: 10 | """ 11 | Push element x onto stack. 12 | """ 13 | self.q.append(x) 14 | for i in range(len(self.q)-1): 15 | self.q.append(self.q.pop(0)) 16 | 17 | def pop(self) -> int: 18 | """ 19 | Removes the element on top of the stack and returns that element. 20 | """ 21 | return self.q.pop(0) 22 | 23 | def top(self) -> int: 24 | """ 25 | Get the top element. 26 | """ 27 | return self.q[0] 28 | 29 | 30 | def empty(self) -> bool: 31 | """ 32 | Returns whether the stack is empty. 33 | """ 34 | n = len(self.q) 35 | return n==0 36 | -------------------------------------------------------------------------------- /python/Implement-Strstr/Implement-Strstr.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-19 4 | # Author: Bryce 5 | 6 | ## Python Solution 1: (使用内置函数) 7 | class Solution(object): 8 | def strStr(self, haystack, needle): 9 | """ 10 | :type haystack: str 11 | :type needle: str 12 | :rtype: int 13 | """ 14 | return haystack.find(needle) 15 | 16 | 17 | ## Python Solution 2: 18 | class Solution(object): 19 | def strStr(self, haystack, needle): 20 | """ 21 | :type haystack: str 22 | :type needle: str 23 | :rtype: int 24 | """ 25 | m = len(needle) 26 | n = len(haystack) 27 | if needle is None: return 0 28 | if haystack is None or m > n: return -1 29 | for i in range (0,n-m+1): 30 | if haystack[i:i+m] == needle: 31 | return i 32 | return -1 33 | -------------------------------------------------------------------------------- /python/Insert-Intervals/Insert-Intervals.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /python/Integer-To-Roman/Integer-To-Roman.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-03 4 | # Author: Bryce 5 | 6 | #Python Solution 1: 7 | class Solution(object): 8 | def intToRoman(self, num): 9 | """ 10 | :type num: int 11 | :rtype: str 12 | """ 13 | res = '' 14 | val= [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] 15 | roman = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] 16 | for i in range(0,len(roman)): 17 | while num >= val[i] : 18 | num -= val[i] 19 | res += roman[i] 20 | return res 21 | 22 | 23 | #Python Solution 2: 24 | class Solution(object): 25 | def maxArea(self, height): 26 | """ 27 | :type height: List[int] 28 | :rtype: int 29 | """ 30 | res = 0 31 | if len(height) < 2: 32 | return 0 33 | i = 0 34 | j = len(height) -1 35 | while i < j: 36 | width = j - i 37 | high = min (height[i],height[j]) 38 | res = max(res, width * high) 39 | if height[i] > height[j]: 40 | j -=1 41 | else: 42 | i +=1 43 | return res 44 | -------------------------------------------------------------------------------- /python/Intersection-Of-Two-Linked-Lists/Intersection-Of-Two-Linked-Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 9 | if headA==None or headB == None: 10 | return None 11 | p = headA 12 | q = headB 13 | n =0 14 | m=0 15 | while p: 16 | n+=1 17 | p = p.next 18 | while q: 19 | m+=1 20 | q = q.next 21 | p = headA 22 | q = headB 23 | k = 0 24 | if n>=m: 25 | k = n-m 26 | else: 27 | p = headB 28 | q = headA 29 | k = m-n 30 | for i in range(k): 31 | p = p.next 32 | while p and q and p!=q: 33 | p = p.next 34 | q = q.next 35 | res = p 36 | return res 37 | -------------------------------------------------------------------------------- /python/Invert-Binary-Tree/Invert-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.left = None 7 | # self.right = None 8 | 9 | class Solution: 10 | def invertTree(self, root: TreeNode) -> TreeNode: 11 | if root == None: 12 | return root 13 | temp = root.left 14 | root.left = self.invertTree(root.right) 15 | root.right = self.invertTree(temp) 16 | return root 17 | ## Python Solution 2: 18 | class Solution: 19 | def invertTree(self, root: TreeNode) -> TreeNode: 20 | if not root: 21 | return root 22 | # 将二叉树中的节点逐层放入队列中,再迭代处理队列中的元素 23 | queue = [root] 24 | while queue: 25 | # 每次都从队列中拿一个节点,并交换这个节点的左右子树 26 | tmp = queue.pop(0) 27 | tmp.left,tmp.right = tmp.right,tmp.left 28 | # 如果当前节点的左子树不为空,则放入队列等待后续处理 29 | if tmp.left: 30 | queue.append(tmp.left) 31 | # 如果当前节点的右子树不为空,则放入队列等待后续处理 32 | if tmp.right: 33 | queue.append(tmp.right) 34 | # 返回处理完的根节点 35 | return root 36 | -------------------------------------------------------------------------------- /python/Jump-Game/Jump-Game.py: -------------------------------------------------------------------------------- 1 | ### Python Solution 1:动态规划 2 | class Solution: 3 | def canJump(self, nums: List[int]) -> bool: 4 | n = len(nums) 5 | if n==0: 6 | return False 7 | dp=[0 for _ in range(n)] 8 | for i in range (1,n): 9 | dp[i] = max(dp[i-1],nums[i-1])-1 10 | if dp[i]<0: 11 | return False 12 | return True 13 | 14 | 15 | 16 | ### Python Solution 2:贪心算法 17 | class Solution: 18 | def canJump(self, nums: List[int]) -> bool: 19 | n = len(nums) 20 | reach = 0 21 | if n==0: 22 | return False 23 | for i in range (n): 24 | if i> reach or reach==n-1: 25 | break 26 | reach = max(reach,i+nums[i]) 27 | return reach>=n-1 28 | -------------------------------------------------------------------------------- /python/Length-Of-Last-Word/Length-Of-Last-Word.py: -------------------------------------------------------------------------------- 1 | ### Python Solution 1: 2 | class Solution: 3 | def lengthOfLastWord(self, s: str) -> int: 4 | res =0 5 | n=len(s) 6 | if n==0: 7 | return res 8 | m = n-1 9 | while m>=0 and s[m]==' ': 10 | m-=1 11 | for i in range (m,-1,-1): 12 | if s[i]==' ': 13 | break 14 | res+=1 15 | return res 16 | 17 | ### Python Solution 2: 18 | class Solution: 19 | def lengthOfLastWord(self, s: str) -> int: 20 | res = 0 21 | s = s.strip(' ') 22 | s = s.split(' ') 23 | res = len(s[-1]) 24 | return res 25 | -------------------------------------------------------------------------------- /python/Longest-Common-Prefix/Longest-Common-Prefix.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-06 4 | # Author: Bryce 5 | 6 | # Python Solution 1: 7 | class Solution: 8 | def longestCommonPrefix(self, strs): 9 | """ 10 | :type strs: List[str] 11 | :rtype: str 12 | """ 13 | res = "" 14 | for tmp in zip(*strs): #zip ()打包 加星号是解压操作 15 | tmp_set = set(tmp) #set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。 16 | if len(tmp_set) == 1: 17 | res += tmp[0] 18 | else: 19 | break 20 | return res 21 | 22 | # Python Solution 2: 23 | class Solution: 24 | def longestCommonPrefix(self, strs): 25 | if not strs: 26 | return "" 27 | res = strs[0] 28 | i = 1 29 | while i < len(strs): 30 | while strs[i].find(res) != 0: 31 | res = res[0:len(res)-1] 32 | i += 1 33 | return res 34 | -------------------------------------------------------------------------------- /python/Longest-Valid-Parentheses/Longest-Valid-Parentheses.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-23 4 | # Author: Bryce 5 | 6 | 7 | ###############Python Solution 1:栈 8 | class Solution: 9 | def longestValidParentheses(self, s: str) -> int: 10 | n = len(s) 11 | stack = [] 12 | start = 0 13 | res = 0 14 | for i in range (n): 15 | if s[i] == '(': 16 | stack.append(i) 17 | elif s[i] == ')': 18 | if stack: 19 | stack.pop() 20 | if stack: 21 | res = max(res,i-stack[-1]) 22 | else: 23 | res = max(res,i-start+1) 24 | else: 25 | start = i+1 26 | return res 27 | -------------------------------------------------------------------------------- /python/Longest_Substring_Without_Repeating_Characters/Longest_Substring_Without_Repeating_Characters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLongestSubstring(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | freq = {} 8 | for i in range(256): 9 | freq[i] = 0 10 | l=max_len = 0 11 | r=-1 12 | while(r+1 < len(s)): 13 | if freq[ord(s[r+1])] ==0: 14 | freq[ord(s[r+1])] += 1 15 | r+=1 16 | else: 17 | freq[ord(s[l])] -= 1 18 | l +=1 19 | max_len = max(max_len, r - l + 1) 20 | return max_len 21 | -------------------------------------------------------------------------------- /python/Maximum-Depth-Of-Binary-Tree/Maximum-Depth-Of-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, root: TreeNode) -> int: 3 | if root is None: 4 | return 0 5 | left = self.maxDepth(root.left) 6 | right = self.maxDepth(root.right) 7 | return max(left, right)+1 8 | class Solution: 9 | def maxDepth(self, root: TreeNode) -> int: 10 | depth = 0 11 | if root is None: 12 | return depth 13 | q = [] 14 | q.append(root) 15 | while q: 16 | count = len(q) 17 | while count >0: 18 | node = q.pop(0) 19 | if node.left: 20 | q.append(node.left) 21 | if node.right: 22 | q.append(node.right) 23 | count -=1 24 | depth+=1 25 | return depth 26 | -------------------------------------------------------------------------------- /python/Median_Of_Two_Sorted_Arrays/Median_Of_Two_Sorted_Arrays.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Author: Bryce 4 | 5 | class Solution(object): 6 | def findMedianSortedArrays(self, nums1, nums2): 7 | """ 8 | :type nums1: List[int] 9 | :type nums2: List[int] 10 | :rtype: float 11 | """ 12 | n = len(nums1) 13 | m = len(nums2) 14 | left = (m + n + 1)/2 15 | right = (m+n+2)/2 16 | left = int (left) 17 | right = int (right) 18 | res_l = self.find_Kth_num(nums1, nums2, left) 19 | res_r = self.find_Kth_num(nums1, nums2, right) 20 | res = (res_l + res_r)/2.0 21 | return res 22 | 23 | def find_Kth_num(self, nums1, nums2, k): 24 | if len(nums1) == 0: 25 | return nums2[int(k - 1)] 26 | if len(nums2) == 0: 27 | return nums1[int(k - 1)] 28 | if k == 1: 29 | return min(nums1[0], nums2[0]) 30 | 31 | a = nums1[int(k / 2) - 1] if len(nums1) >= k / 2 else None 32 | b = nums2[int(k / 2) - 1] if len(nums2) >= k / 2 else None 33 | if b is None or (a is not None and a < b): 34 | return self.find_Kth_num(nums1[int(k / 2):], nums2, int(k - k // 2)) 35 | return self.find_Kth_num(nums1, nums2[int(k / 2):], int(k - k // 2)) 36 | 37 | 38 | if __name__ == '__main__': 39 | s = Solution() 40 | print(s.findMedianSortedArrays([1,2], [3,4])) 41 | -------------------------------------------------------------------------------- /python/Merge-K-Sorted-Lists/Merge-K-Sorted-Lists.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-14 4 | # Author: Bryce 5 | # Definition for singly-linked list. 6 | # class ListNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | 12 | ######## Python Solution 1: 13 | class Solution(object): 14 | def mergeKLists(self, lists): 15 | """ 16 | :type lists: List[ListNode] 17 | :rtype: ListNode 18 | """ 19 | res =[] 20 | dummyHead = ListNode(0) 21 | temp = dummyHead 22 | k = len(lists) 23 | if k==0: 24 | return None 25 | if k==1: 26 | return lists[0] 27 | l1 = lists[0] 28 | l2 = lists[1] 29 | for i in range (1,k): 30 | l2 = lists[i] 31 | while l1 and l2: 32 | if l1.val < l2.val: 33 | temp.next = l1 34 | l1 = l1.next 35 | else: 36 | temp.next = l2 37 | l2 = l2.next 38 | temp = temp.next 39 | if l1: 40 | temp.next = l1 41 | else: 42 | temp.next = l2 43 | l1 = dummyHead.next 44 | temp = dummyHead 45 | res = dummyHead.next 46 | return res 47 | 48 | ######## Python Solution 2:(分治法) 49 | -------------------------------------------------------------------------------- /python/Merge-Two-Sorted-Lists/Merge-Two-Sorted-Lists.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-12 4 | # Author: Bryce 5 | 6 | 7 | ###Python Solution 1: 8 | class Solution(object): 9 | def mergeTwoLists(self, l1, l2): 10 | """ 11 | :type l1: ListNode 12 | :type l2: ListNode 13 | :rtype: ListNode 14 | """ 15 | dummyHead = ListNode(0) 16 | temp = dummyHead 17 | while l1 and l2: 18 | if l1.val <= l2.val: 19 | temp.next = l1 20 | l1 = l1.next 21 | else: 22 | temp.next = l2 23 | l2 = l2.next 24 | temp = temp.next 25 | if l1: 26 | temp.next = l1 27 | else: 28 | temp.next = l2 29 | l3 = dummyHead.next 30 | return l3 31 | 32 | 33 | ### Python Solution 2: 34 | class Solution(object): 35 | def mergeTwoLists(self, l1, l2): 36 | """ 37 | :type l1: ListNode 38 | :type l2: ListNode 39 | :rtype: ListNode 40 | """ 41 | if l1 is None: 42 | return l2 43 | if l2 is None: 44 | return l1 45 | if l1.val < l2.val: 46 | l1.next = self.mergeTwoLists(l1.next,l2) 47 | return l1 48 | else: 49 | l2.next = self.mergeTwoLists(l1,l2.next) 50 | return l2 51 | -------------------------------------------------------------------------------- /python/Min-Stack/Min-Stack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | """ 5 | initialize your data structure here. 6 | """ 7 | self.stack1 = [] 8 | self.stack2 = [] 9 | 10 | def push(self, x: int) -> None: 11 | self.stack1.append(x) 12 | if len(self.stack2)==0 or x < self.stack2[-1]: 13 | self.stack2.append(x) 14 | else: 15 | a = self.stack2[-1] 16 | self.stack2.append(a) 17 | 18 | def pop(self) -> None: 19 | if len(self.stack1) > 0 and len(self.stack2) > 0: 20 | self.stack1.pop() 21 | self.stack2.pop() 22 | 23 | def top(self) -> int: 24 | return self.stack1[-1] 25 | 26 | def getMin(self) -> int: 27 | return self.stack2[-1] 28 | 29 | 30 | # Your MinStack object will be instantiated and called as such: 31 | # obj = MinStack() 32 | # obj.push(x) 33 | # obj.pop() 34 | # param_3 = obj.top() 35 | # param_4 = obj.getMin() 36 | -------------------------------------------------------------------------------- /python/Missing-Number/Missing-Number.py: -------------------------------------------------------------------------------- 1 | ### Python Solution 1: 2 | class Solution { 3 | public: 4 | int missingNumber(vector& nums) { 5 | sort(nums.begin(),nums.end()); 6 | int n = nums.size(); 7 | int res = 0; 8 | if (nums[n-1]!=n) 9 | { 10 | return n; 11 | } 12 | for (int i=0;i int: 26 | res = 0; 27 | n = len(nums) 28 | x = range(n+1) 29 | x = list(x) ### Python3 需要用list转换成数组 30 | res = sum(x)-sum(nums) 31 | return res 32 | 33 | 34 | class Solution: 35 | def missingNumber(self, nums: List[int]) -> int: 36 | n = len(nums) 37 | res = n 38 | for i in range(n): 39 | res = res ^ nums[i] 40 | res = res ^ i 41 | return res 42 | ### Python Solution 3: 43 | class Solution: 44 | def missingNumber(self, nums: List[int]) -> int: 45 | nums = sorted(nums) 46 | n = len(nums) 47 | if nums[-1] != n: 48 | return n 49 | for i in range(0,n): 50 | if i!=nums[i]: 51 | return i 52 | -------------------------------------------------------------------------------- /python/Multiply-Strings/Multiply-Strings.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-12-4 4 | # Author: Bryce 5 | 6 | 7 | class Solution: 8 | def multiply(self, num1: str, num2: str) -> str: 9 | n1,n2 = len(num1),len(num2) 10 | res = [0 for i in range(n1+n2)] 11 | for i in range(n2-1,-1,-1): 12 | for j in range(n1-1,-1,-1): 13 | x,y = ord(num1[j])-ord('0'),ord(num2[i])-ord('0') 14 | temp = x*y + res[i+j+1] 15 | res[i+j+1] = temp % 10 16 | res[i+j] += temp // 10 17 | for i in range(0,n1+n2): 18 | if res[i] != 0: 19 | res = ''.join(str(x) for x in res[i:]) 20 | return res 21 | return "0" 22 | -------------------------------------------------------------------------------- /python/Next-Permutation/Next-Permutation.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-22 4 | # Author: Bryce 5 | -------------------------------------------------------------------------------- /python/Nth-Digit/Nth-Digit.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findNthDigit(self, n: int) -> int: 3 | if n<0: 4 | return -1 5 | if n<10: 6 | return n 7 | digits = 1 8 | numbers = 9 9 | while n>digits*numbers: 10 | n-=digits*numbers 11 | digits+=1 12 | numbers*=10 13 | n-=1 14 | a = n//digits 15 | b = n%digits 16 | num = int(pow(10,digits-1) + a) 17 | idx = digits-b 18 | for i in range(1, idx): 19 | num//=10 20 | return num%10 21 | # s = str(num) 22 | # res = int(s[b]) 23 | # return res 24 | -------------------------------------------------------------------------------- /python/Number-Of-1-Bits/Number-Of-1-Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | res = 0 4 | while n: 5 | res +=1 6 | n&=n-1 7 | return res 8 | -------------------------------------------------------------------------------- /python/Number-Of-Digit-One/Number-Of-Digit-One.py: -------------------------------------------------------------------------------- 1 | # Solution 1: 2 | class Solution: 3 | def countDigitOne(self, n: int) -> int: 4 | res = 0 5 | for i in range(1,n+1): 6 | res+=self.NumberOf1(i) 7 | return res 8 | def NumberOf1(self, n: int): 9 | num = 0 10 | while n>0: 11 | if (n%10==1): 12 | num+=1 13 | n//=10 14 | return num 15 | # Solution 2: 16 | class Solution: 17 | def countDigitOne(self, n: int) -> int: 18 | res = 0 19 | i = 1 20 | while i<=n: 21 | a = n // i 22 | b = n % i 23 | res += (a+8)//10*i + (a%10==1)*(b+1) 24 | i*=10 25 | return res 26 | # Solution 3: 27 | # -*- coding:utf-8 -*- 28 | class Solution: 29 | def countDigitOne(self, n: int) -> int: 30 | # write code here 31 | res = 0 32 | for i in range(1,n+1): 33 | s = str(i) 34 | res+=s.count('1') 35 | return res 36 | -------------------------------------------------------------------------------- /python/Palindrome-Number/Palindrome-Number.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-10-31 4 | # Author: bryce 5 | 6 | 7 | #######转成字符一行就可以搞定 8 | class Solution(object): 9 | def isPalindrome(self, x): 10 | """ 11 | :type x: int 12 | :rtype: bool 13 | """ 14 | return str(x) == str(x)[::-1] 15 | 16 | 17 | 18 | ########不转成字符求回文数表示 19 | class Solution2(object): 20 | def isPalindrome(self, x): 21 | """ 22 | :type x: int 23 | :rtype: bool 24 | """ 25 | a = x 26 | n = 0 27 | if a < 0: 28 | return False 29 | while a != 0: 30 | m = a % 10 31 | a /= 10 32 | n = n * 10 + m 33 | return x == n 34 | -------------------------------------------------------------------------------- /python/Path-Sum-II/Path-Sum-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.res = [] 4 | self.path = [] 5 | def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: 6 | if root is None: 7 | return self.res 8 | self.dfs(root, self.path, sum) 9 | return self.res 10 | def dfs(self, root, path, sum): 11 | if root is None: 12 | return 13 | self.path.append(root.val) 14 | if sum == root.val and (root.left is None and root.right is None): 15 | self.res.append(self.path[:]) 16 | self.dfs(root.left, self.path, sum - root.val) 17 | self.dfs(root.right, self.path, sum - root.val) 18 | self.path.pop() 19 | -------------------------------------------------------------------------------- /python/Path-Sum/Path-Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasPathSum(self, root: TreeNode, sum: int) -> bool: 3 | if root is None: 4 | return False 5 | isLeaf = (root.left==None) and (root.right==None) 6 | sum -= root.val 7 | if isLeaf: 8 | return sum == 0 9 | return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum) 10 | -------------------------------------------------------------------------------- /python/Permutation-Sequence/Permutation-Sequence.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /python/Permutations-II/Permutations-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | out = [] 5 | n = len(nums) 6 | if n==0 : 7 | return res 8 | 9 | visited = [ 0 for i in range(n)] 10 | nums= sorted(nums) 11 | self.DFS(nums,0,visited,out,res) 12 | return res 13 | def DFS(self,nums:List[int],level:int,visited:List[int],out:List[int],res:List[List[int]]): 14 | n = len(nums) 15 | if level == n: 16 | res.append(out[:]) 17 | return 18 | for i in range (0,n): 19 | if visited[i] ==1: 20 | continue 21 | if i>=1 and nums[i]==nums[i-1] and visited[i-1]==0: 22 | continue 23 | visited[i]=1 24 | out.append(nums[i]) 25 | self.DFS(nums,level+1,visited,out,res) 26 | out.pop() 27 | visited[i]=0 28 | -------------------------------------------------------------------------------- /python/Permutations/Permutations.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def permute(self, nums: List[int]) -> List[List[int]]: 4 | n = len(nums) 5 | res=[] 6 | if n == 0: 7 | return res 8 | out = [] 9 | visited = [0 for i in range(n)] 10 | self.DFS(nums,0,visited,out,res) 11 | return res 12 | def DFS(self, nums: List[int], level : int, visited: List[int], out: List[int], res: List[List[int]]): 13 | n = len(nums) 14 | if level == n: 15 | res.append(out[:]) 16 | return 17 | for i in range (0,n): 18 | if visited[i] == 1: 19 | continue 20 | visited[i] = 1 21 | out.append(nums[i]) 22 | self.DFS(nums, level+1, visited, out, res) 23 | out.pop() ## del out[-1] out.pop(-1) 24 | visited[i] = 0 25 | -------------------------------------------------------------------------------- /python/PowX-N/PowX-N.py: -------------------------------------------------------------------------------- 1 | ### Solution 1: 根据定义暴力求解 2 | class Solution: 3 | def myPow(self, x: float, n: int) -> float: 4 | res = x 5 | if x==0: 6 | return 0 7 | if x==1: 8 | return 1 9 | if x==-1 and n%2 == 0: 10 | return 1 11 | if x==-1 and n%2 != 0: 12 | return -1 13 | if n==2147483647 and x<1: 14 | return 0 15 | if n==-2147483648 and x>1: 16 | return 0 17 | if n>0: 18 | for i in range(1,n): 19 | res *= x 20 | if n<0: 21 | for i in range(-1,n,-1): 22 | res *=x 23 | res = 1/res 24 | if n==0: 25 | res = 1 26 | return res; 27 | -------------------------------------------------------------------------------- /python/Remove-Duplicates-From-Sorted-Array/Remove-Duplicates-From-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-17 4 | # Author: Bryce 5 | 6 | ######Python Solution 1: 7 | class Solution(object): 8 | def removeDuplicates(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | res = 0 14 | n = len(nums) 15 | if n==0: 16 | return res 17 | k = 0 18 | for i in range(1,n): 19 | if nums[k] != nums[i]: 20 | k+=1 21 | nums[k] = nums[i] 22 | res = k+1 23 | return res 24 | 25 | 26 | ######Python Solution 2: 27 | class Solution(object): 28 | def removeDuplicates(self, nums): 29 | """ 30 | :type nums: List[int] 31 | :rtype: int 32 | """ 33 | res = 0 34 | n = len(nums) 35 | if n==0: 36 | return res 37 | l = 0 38 | r = 0 39 | while r < n: 40 | if nums[l] == nums[r]: 41 | r+=1 42 | else: 43 | l+=1 44 | nums[l] = nums[r] 45 | r+=1 46 | res = l+1 47 | return res 48 | -------------------------------------------------------------------------------- /python/Remove-Duplicates-From-Sorted-List/Remove-Duplicates-From-Sorted-List.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /python/Remove-Element/Remove-Element.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-18 4 | # Author: Bryce 5 | 6 | ######Python Solution 1: 7 | class Solution(object): 8 | def removeElement(self, nums, val): 9 | """ 10 | :type nums: List[int] 11 | :type val: int 12 | :rtype: int 13 | """ 14 | res = 0 15 | k = 0 16 | n = len(nums) 17 | if n == 0: 18 | return res 19 | for i in range(n): 20 | if nums[i] != val: 21 | nums[k] = nums[i] 22 | k+=1 23 | res = k 24 | return res 25 | 26 | ######Python Solution 2: 27 | class Solution(object): 28 | def removeElement(self, nums, val): 29 | """ 30 | :type nums: List[int] 31 | :type val: int 32 | :rtype: int 33 | """ 34 | j=len(nums) 35 | for i in range(j-1,-1,-1): ## 倒序 36 | if nums[i]==val: 37 | nums.pop(i) ###pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。 38 | return len(nums) 39 | -------------------------------------------------------------------------------- /python/Remove-Linked-List-Elements/Remove-Linked-List-Elements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def removeElements(self, head: ListNode, val: int) -> ListNode: 9 | p = ListNode(-1) 10 | p.next = head 11 | prev = p 12 | cur = head 13 | while cur: 14 | if cur.val == val: 15 | prev.next = cur.next 16 | else: 17 | prev = cur 18 | cur = cur.next 19 | return p.next 20 | -------------------------------------------------------------------------------- /python/Reverse-Integer/Reverse-Integer.py: -------------------------------------------------------------------------------- 1 | 2 | #! /usr/bin/env python 3 | #! -*- coding=utf-8 -*- 4 | # Date: 2019-10-28 5 | # Author: Bryce 6 | class Solution(object): 7 | # 本题的思路就是先判断给定整数x的正负情况,把符号首先给提取出来 8 | # 然后将abs(x)变成字符串,接着将字符串反转,最后恢复成整数 9 | def reverse(self, x): 10 | """ 11 | :type x: int 12 | :rtype: int 13 | """ 14 | # 定义用来标记给定整数x的正负情况,若x>=0, 则flag=1;反之,则flag=-1 15 | flag = 1 if x >= 0 else -1 16 | abs_x = abs(x) 17 | # 将abs(x)变成字符串 18 | x_str = str(abs_x) 19 | # 将字符串x_str反转 20 | reverse_x_str = x_str[::-1] 21 | # 最后恢复成整数 22 | reverse_x_int = int(reverse_x_str) * flag 23 | if -2 ** 31 <= reverse_x_int <= 2**31 - 1: 24 | return reverse_x_int 25 | else: 26 | return 0 27 | 28 | 29 | if __name__ == "__main__": 30 | x = 231 31 | reverse_x = Solution().reverse(x) 32 | print(reverse_x) 33 | -------------------------------------------------------------------------------- /python/Reverse-Linked-List/Reverse-Linked-List.py: -------------------------------------------------------------------------------- 1 | ## Solution 1: 2 | # Definition for singly-linked list. 3 | # class ListNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | 8 | class Solution: 9 | def reverseList(self, head: ListNode) -> ListNode: 10 | if head==None or head.next==None: 11 | return head 12 | p = None 13 | cur = head 14 | temp = head.next 15 | while cur: 16 | temp = cur.next 17 | cur.next = p 18 | p = cur 19 | cur = temp 20 | return p 21 | ### Solution 2: 22 | # Definition for singly-linked list. 23 | # class ListNode: 24 | # def __init__(self, x): 25 | # self.val = x 26 | # self.next = None 27 | 28 | class Solution: 29 | def reverseList(self, head: ListNode) -> ListNode: 30 | if head == None or head.next == None: 31 | return head 32 | else: 33 | newhead = self.reverseList(head.next) 34 | head.next.next = head 35 | head.next = None 36 | return newhead 37 | -------------------------------------------------------------------------------- /python/Reverse-Nodes-In-K-Group/Reverse-Nodes-In-K-Group.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-16 4 | # Author: Bryce 5 | 6 | ########## Python Solution 1: 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | class Solution(object): 14 | def reverseKGroup(self, head, k): 15 | """ 16 | :type head: ListNode 17 | :type k: int 18 | :rtype: ListNode 19 | """ 20 | res = [] 21 | dummmyHead = ListNode(0) 22 | pre = dummmyHead 23 | dummmyHead.next=head 24 | cur = head 25 | i = 1 26 | if head is None or k==1: 27 | return head 28 | while cur: 29 | if i%k == 0: 30 | pre = self.reverseOneGroup(pre,cur.next) 31 | cur = pre.next 32 | else: 33 | cur = cur.next 34 | i+=1 35 | res = dummmyHead.next 36 | return res 37 | def reverseOneGroup(self, pre, l): 38 | last = pre.next 39 | cur = last.next 40 | while cur != l: 41 | last.next = cur.next 42 | cur.next = pre.next 43 | pre.next = cur 44 | cur = last.next 45 | return last 46 | -------------------------------------------------------------------------------- /python/Reverse-Words-In-A-String/Reverse-Words-In-A-String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | s = list(s) 4 | n = len(s) 5 | self.Reverse(s,0,n-1) 6 | i =0 7 | while i str: 42 | return " ".join(s.split()[::-1]) 43 | -------------------------------------------------------------------------------- /python/Roman-To-Integer/Roman-To-Integer.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-04 4 | # Author: Bryce 5 | #Python Solution 1: 6 | class Solution(object): 7 | def romanToInt(self, s): 8 | """ 9 | :type s: str 10 | :rtype: int 11 | """ 12 | words = {} 13 | res = 0 14 | i = 0 15 | words['I'] = 1; words['V'] = 5; 16 | words['X'] = 10; words['L'] = 50; 17 | words['C'] = 100; words['D'] = 500; 18 | words['M'] = 1000; 19 | 20 | while i < len(s): 21 | if i + 1 < len(s) and words[s[i+1]] > words[s[i]]: 22 | res += words[s[i+1]] - words[s[i]] 23 | i +=2 24 | else: 25 | res += words[s[i]] 26 | i += 1 27 | return res 28 | 29 | #Python Solution 2: 30 | class Solution(object): 31 | def romanToInt(self, s): 32 | """ 33 | :type s: str 34 | :rtype: int 35 | """ 36 | words = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} 37 | res = 0 38 | for i in range(len(s)): 39 | if i < len(s)-1 and words[s[i+1]] > words[s[i]]: 40 | res -= words[s[i]] 41 | else: 42 | res += words[s[i]] 43 | return res 44 | 45 | if __name__ == " __main__ ": 46 | a = "III" 47 | print ( Solution().romanToInt (a) ) 48 | -------------------------------------------------------------------------------- /python/Rotate-Image/Rotate-Image.py: -------------------------------------------------------------------------------- 1 | ####### Solution 1: 2 | class Solution: 3 | def rotate(self, matrix: List[List[int]]) -> None: 4 | """ 5 | Do not return anything, modify matrix in-place instead. 6 | """ 7 | n = len(matrix) 8 | 9 | # 转置 10 | for i in range(n): 11 | for j in range(i,n): 12 | temp = matrix[i][j] 13 | matrix[i][j] = matrix[j][i] 14 | matrix[j][i] = temp 15 | #旋转 16 | for i in range(n): 17 | j = 0 18 | k = n-1 19 | while j None: 30 | """ 31 | Do not return anything, modify matrix in-place instead. 32 | """ 33 | n = len(matrix) 34 | for i in range (n): 35 | for j in range(i,n-1-i): 36 | temp = matrix[i][j] 37 | matrix[i][j] = matrix[n-1-j][i] 38 | matrix[n-1-j][i] = matrix[n-1-i][n-1-j] 39 | matrix[n-1-i][n-1-j] = matrix[j][n-1-i] 40 | matrix[j][n-1-i] = temp 41 | -------------------------------------------------------------------------------- /python/Rotate-String/Rotate-String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotateString(self, A: str, B: str) -> bool: 3 | n = len(A) 4 | m = len(B) 5 | if n!=m: 6 | return False 7 | if A=="" and B=="": 8 | return True 9 | for i in range(n): 10 | A = self.leftmove(A) 11 | if A==B: 12 | return True 13 | return False 14 | 15 | def leftmove(self,s): 16 | s = list(s) 17 | n = len(s) 18 | temp = s[0] 19 | for i in range(n): 20 | if i!=n-1: 21 | s[i]=s[i+1] 22 | else: 23 | s[i]=temp 24 | return ''.join(s) 25 | ## Solution 2: 26 | class Solution: 27 | def rotateString(self, A: str, B: str) -> bool: 28 | n = len(A) 29 | m = len(B) 30 | if n!=m: 31 | return False 32 | if A=="" and B == "": 33 | return True 34 | if B in (A+A): 35 | return True 36 | return False 37 | -------------------------------------------------------------------------------- /python/Rotting-Oranges/Rotting-Oranges.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def orangesRotting(self, grid: List[List[int]]) -> int: 3 | res = 0 4 | if grid == []: 5 | return res 6 | m = len(grid) 7 | n = len(grid[0]) 8 | dx = [1,-1,0,0] 9 | dy = [0,0,1,-1] 10 | q=[] 11 | for i in range(m): 12 | for j in range(n): 13 | if grid[i][j]==2: 14 | q.append((i,j)) 15 | while q: 16 | size = len(q) 17 | for i in range(size): 18 | d = q.pop(0) 19 | for k in range(4): 20 | x = d[0] + dx[k] 21 | y = d[1] + dy[k] 22 | if 0<=x int: 9 | n=len(nums) 10 | if n==0: 11 | return 0 12 | start = 0 13 | end = n 14 | while end > start: 15 | mid = start + (end-start)//2 16 | if nums[mid] int: 26 | n=len(nums) 27 | if n==0: 28 | return 0 29 | for i in range(n): 30 | if nums[i]>=target: 31 | return i 32 | return n 33 | -------------------------------------------------------------------------------- /python/Single-Number-III/Single-Number-III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumbers(self, nums: List[int]) -> List[int]: 3 | number = 0 4 | res = [0,0] 5 | for num in nums: 6 | number ^= num 7 | pos = 1 8 | while (number&pos) == 0: 9 | pos <<=1 10 | for num in nums: 11 | if (num&pos) == pos: 12 | res[0] ^= num 13 | else: 14 | res[1] ^= num 15 | return res 16 | -------------------------------------------------------------------------------- /python/Single-Number/Single-Number.py: -------------------------------------------------------------------------------- 1 | ## Python Solution 1: 2 | class Solution: 3 | def singleNumber(self, nums: List[int]) -> int: 4 | hash_table = {} 5 | for num in nums: 6 | try: 7 | hash_table.pop(num) 8 | except: 9 | hash_table[num] = 1 10 | res = hash_table.popitem()[0] ## Python 字典 popitem() 方法随机返回并删除字典中的最后一对键和值。如果字典已经为空,却调用了此方法,就报出KeyError异常。 11 | return res 12 | 13 | ## Python Solution 2: 14 | class Solution: 15 | def singleNumber(self, nums: List[int]) -> int: 16 | res = 0 17 | res = 2*sum(set(nums)) - sum(nums) ## set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。 18 | return res 19 | 20 | 21 | ## Python Solution 3: 22 | class Solution: 23 | def singleNumber(self, nums: List[int]) -> int: 24 | res = 0 25 | for num in nums: 26 | res = res ^ num 27 | return res 28 | -------------------------------------------------------------------------------- /python/Sorted-Merge-Lcci/Sorted-Merge-Lcci.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, A: List[int], m: int, B: List[int], n: int) -> None: 3 | """ 4 | Do not return anything, modify A in-place instead. 5 | """ 6 | i = m-1 7 | j = n-1 8 | index = m+n-1 9 | while i>=0 and j>=0: 10 | if A[i] >= B[j]: 11 | A[index] = A[i] 12 | index-=1 13 | i-=1 14 | else: 15 | A[index] = B[j] 16 | index -=1 17 | j-=1 18 | # 比较完B还有剩下的,全填到A前面即可 19 | A[:j+1] = B[:j+1] 20 | -------------------------------------------------------------------------------- /python/Spiral-Matrix/Spiral-Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 | res = [] 4 | m = len(matrix) 5 | if m==0: 6 | return res 7 | n = len(matrix[0]) 8 | u = 0 9 | d = m-1 10 | l = 0 11 | r = n-1 12 | while(True): 13 | for i in range(l,r+1): 14 | res.append(matrix[u][i]) 15 | u+=1 16 | if u>d: break 17 | for i in range(u,d+1): 18 | res.append(matrix[i][r]) 19 | r-=1 20 | if rr:break 29 | return res 30 | -------------------------------------------------------------------------------- /python/String-To-Integer-Atoi/String-To-Integer-Atoi.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-10-30 4 | # Author: bryce 5 | 6 | class Solution(object): 7 | def myAtoi(self, str): 8 | """ 9 | :type str: str 10 | :rtype: int 11 | """ 12 | res = 0; 13 | r = 0 14 | i = 0; 15 | flag = 1; 16 | 17 | if len(str) == 0: 18 | return 0 19 | while (i < len(str) and (str[i]==' ' or str[i]=='/t')): 20 | i+=1 21 | if (i > len(str)): 22 | return 0 23 | if (i < len(str) and str[i]=='-'): 24 | flag = -1 25 | i+=1 26 | if (i < len(str) and str[i]=='+'): 27 | if(flag == -1): 28 | return 0 29 | i+=1 30 | while (i < len(str) and str[i] >= '0' and str[i] <= '9'): 31 | r = int (ord(str[i]) - ord('0')) 32 | if res > (pow(2,31) - 1)/10 or (res == (pow(2,31) - 1)/10 and r > 7 ): 33 | if flag > 0: 34 | res_max = pow(2,31) - 1 35 | return res_max 36 | else: 37 | res_min = - pow(2,31) 38 | return res_min 39 | res = res * 10 + r 40 | i+=1 41 | res *=flag 42 | return res 43 | -------------------------------------------------------------------------------- /python/Substring-With-Concatenation-Of-All-Words/Substring-With-Concatenation-Of-All-Words.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-21 4 | # Author: Bryce 5 | 6 | class Solution(object): 7 | def findSubstring(self, s, words): 8 | """ 9 | :type s: str 10 | :type words: List[str] 11 | :rtype: List[int] 12 | """ 13 | if not s or len(s)==0 or not words or len(words)==0: 14 | return [] 15 | # 将每个单词以及出现的频率记录到字典中 16 | words_map,res = dict(),[] 17 | for i in words: 18 | if i not in words_map: 19 | words_map[i] = 1 20 | else: 21 | words_map[i] += 1 22 | one_word_size = len(words[0]) 23 | all_words_size = len(words)*one_word_size 24 | for i in range(len(s)-all_words_size+1): 25 | # 每次取 all_words_size长度的子串 26 | tmp_str,d = s[i:i+all_words_size],dict(words_map) 27 | # 将子串和临时字典进行比较 28 | for j in range(0,len(tmp_str),one_word_size): 29 | # 从子串tmp_str中取出one_word_size长度的子串,看是否出现在临时字典中 30 | # 如果是就将临时字典记录的频率-1,如果不在就跳出循环 31 | key = tmp_str[j:j+one_word_size] 32 | if key in d: 33 | d[key] -= 1 34 | if d[key]==0: 35 | del d[key] 36 | else: 37 | break 38 | # 当内层循环遍历完后,如果临时字典为空则表示全部匹配上了 39 | # 记录数组的下标 40 | if not d: 41 | res.append(i) 42 | return res 43 | -------------------------------------------------------------------------------- /python/Swap-Nodes-In-Pairs/Swap-Nodes-In-Pairs.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-15 4 | # Author: Bryce 5 | 6 | 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | 14 | ################Python Solution 1: (非递归) 15 | class Solution(object): 16 | def swapPairs(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: ListNode 20 | """ 21 | res=[] 22 | dummyHead = ListNode(0) 23 | temp = dummyHead 24 | dummyHead.next = head 25 | while temp.next and temp.next.next: 26 | s1 = temp.next 27 | s2 = s1.next 28 | s = s2.next 29 | temp.next = s2 30 | s2.next = s1 31 | s1.next = s 32 | temp = temp.next.next 33 | res = dummyHead.next 34 | return res 35 | 36 | ################Python Solution 2: (递归) 37 | class Solution(object): 38 | def swapPairs(self, head): 39 | """ 40 | :type head: ListNode 41 | :rtype: ListNode 42 | """ 43 | if head is None or head.next is None: 44 | return head 45 | res = head.next 46 | head.next = self.swapPairs(head.next.next) 47 | res.next = head 48 | return res 49 | -------------------------------------------------------------------------------- /python/Symmetric-Tree/Symmetric-Tree.py: -------------------------------------------------------------------------------- 1 | ## Solution 1: 2 | class Solution: 3 | def isSymmetric(self, root: TreeNode) -> bool: 4 | res = True 5 | if root: 6 | res = self.helper(root.left, root.right) 7 | return res 8 | 9 | def helper(self,A,B): 10 | if A is None and B is None: 11 | return True 12 | if A is None or B is None: 13 | return False 14 | if A.val != B.val: 15 | return False 16 | return self.helper(A.left,B.right) and self.helper(A.right,B.left) 17 | ### Solution 2: 18 | class Solution: 19 | def isSymmetric(self, root: TreeNode) -> bool: 20 | if root is None: 21 | return True 22 | q = [] 23 | q.append(root.left) 24 | q.append(root.right) 25 | while len(q)!=0: 26 | A = q.pop(0) 27 | B = q.pop(0) 28 | if A == None and B == None: 29 | continue 30 | if A == None or B == None: 31 | return False 32 | if A.val != B.val: 33 | return False 34 | q.append(A.left) 35 | q.append(B.right) 36 | q.append(A.right) 37 | q.append(B.left) 38 | return True 39 | -------------------------------------------------------------------------------- /python/Two_Sum/Two_Sum.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-10-12 4 | # Author: Bryce 5 | 6 | class Solution: 7 | def twoSum (self ,nums,target ): 8 | dic={ }; 9 | for index, num in enumerate (nums): 10 | if num in dic : 11 | return [dic[num], index] 12 | dic [target - num]= index 13 | if __name__ == " __main__ ": 14 | nums = [ 2 , 7 , 11 , 15 ] 15 | target = 9 16 | print ( Solution().twoSum (nums, target) ) 17 | -------------------------------------------------------------------------------- /python/Ugly-Number/Ugly-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isUgly(self, num: int) -> bool: 3 | if num <1: 4 | return False 5 | while num%5 == 0: 6 | num//=5 7 | while num%3 == 0: 8 | num//=3 9 | while num%2 == 0: 10 | num//=2 11 | return num==1 12 | -------------------------------------------------------------------------------- /python/Valid-Number/Valid-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isNumber(self, s: str) -> bool: 3 | n = len(s) 4 | if n==0: 5 | return False 6 | num = False 7 | numAfterE = False 8 | decimal = False 9 | sign = False 10 | hasE = False 11 | for i in range(n): 12 | if s[i]==' ': 13 | if (i0 and s[i-1]!='e' and s[i-1]!=' ': 17 | return False 18 | sign = True 19 | elif s[i]>='0' and s[i]<='9': 20 | num =True 21 | numAfterE=True 22 | elif s[i]=='.': 23 | if hasE or decimal: 24 | return False 25 | decimal = True 26 | elif s[i]=='e': 27 | if hasE or (num is False): 28 | return False 29 | hasE = True 30 | numAfterE=False 31 | else: 32 | return False 33 | return num and numAfterE 34 | -------------------------------------------------------------------------------- /python/Valid-Parentheses/Valid-Parentheses.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-11-11 4 | # Author: Bryce 5 | 6 | ### Python Solution 1: 7 | class Solution: 8 | def isValid(self, s): 9 | while '{}' in s or '()' in s or '[]' in s: 10 | s = s.replace('{}', '') 11 | s = s.replace('[]', '') 12 | s = s.replace('()', '') 13 | return s == '' 14 | 15 | 16 | ### Python Solution 2: 17 | class Solution(object): 18 | def isValid(self, s): 19 | """ 20 | :type s: str 21 | :rtype: bool 22 | """ 23 | if len(s) & 1 == 1: # 位运算判断奇偶 24 | return False 25 | stack = [] 26 | hash_map = {'(': ')', '[': ']', '{': '}'} 27 | for c in s: 28 | if c in hash_map: 29 | stack.append(c) 30 | continue 31 | elif stack and hash_map[stack[-1]] == c: 32 | stack.pop() 33 | else: 34 | return False 35 | return not stack 36 | -------------------------------------------------------------------------------- /python/Validate-Stack-Sequences/Validate-Stack-Sequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: 3 | n = len(pushed) 4 | m = len(popped) 5 | if n!=m: 6 | return False 7 | s = [] 8 | index = 0 9 | for i in range(n): 10 | s.append(pushed[i]) 11 | while len(s)>0 and s[-1]==popped[index]: 12 | s.pop() 13 | index+=1 14 | return len(s)==0 15 | -------------------------------------------------------------------------------- /python/Wildcard-Matching/Wildcard-Matching.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 2019-12-6 4 | # Author: Bryce 5 | 6 | -------------------------------------------------------------------------------- /python/Zigzag-Conversion/Zigzag-Conversion.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | #! -*- coding=utf-8 -*- 3 | # Date: 8/12/19 4 | # Author: Bryce 5 | class Solution(object): 6 | def convert(self, s, numRows): 7 | """ 8 | :type s: str 9 | :type numRows: int 10 | :rtype: str 11 | """ 12 | n = len(s) 13 | res = "" 14 | if numRows == 1: 15 | return s 16 | m = 2 * numRows -2 17 | for i in range (numRows): 18 | if (i == 0 or i == numRows-1): 19 | for j in range (i,n,m): 20 | res += s[j] 21 | else: 22 | j = i 23 | k = 2*numRows -i -1 -1 24 | while (j < n or k < n ): 25 | if j < n: 26 | res += s[j] 27 | if k < n: 28 | res += s[k] 29 | j += m 30 | k += m 31 | return res 32 | --------------------------------------------------------------------------------