├── .flake8 ├── .gitignore ├── LICENSE ├── LeetCode ├── 0001-两数之和-two-sum.md ├── 0002-两数相加-add-two-numbers.md ├── 0003-无重复字符的最长子串-Longest-Substring-Without-Repeating-Characters.md ├── 2018-08-16-Count and Say.py ├── 2018-08-23-Direct-Insertion-Sort.py ├── 2018-08-24-Bubble-Sort.py ├── 2018-08-26-Switch.py ├── 2018-08-29-300-Longest-Increasing-Subsequence.py ├── 2018-08-30-53-Maximum-Subarray.py ├── 2018-08-30-66-Plus-One.py ├── 2018-08-30-67-Add-Binary.py ├── 2018-09-09-iflytek.py ├── 2018-11-06-Palindrome-Linked-List.py ├── 2018-11-11-Reverse-Linked-List.py ├── 2018-11-12-155-Min-Stack.py ├── 2018-11-12-876-Middle-of-the-Linked-List.py ├── 2018-11-12-Linked-List-Cycle.py ├── 2018-11-13-232-Implement-Queue-using-Stacks.py ├── 2018-11-13-844-Backspace-String-Compare.py ├── 2018-11-14-224-Basic-Calculator.py ├── 2018-11-15-496-Next-Greater-Element-I.py ├── 2018-11-15-682-Baseball-Game.py ├── 2018-11-28-39-Combination-Sum.md ├── 2018-11-28-39-Combination-Sum.py ├── 2018-11-30-40-Combination-Sum-II.md ├── 2018-11-30-40-Combination-Sum-II.py ├── 2018-12-01-42-Trapping-Rain-Water.py ├── 2018-12-03-42-Trapping-Rain-Water.md ├── 2018-12-05-43-Multiply-Strings.md ├── 2018-12-05-43-Multiply-Strings.py ├── 2018-12-07-44-Wildcard-Matching.md ├── 2018-12-07-44-Wildcard-Matching.py ├── 2018-12-09-45-Jump-Game-II.md ├── 2018-12-09-45-Jump-Game-II.py ├── 2018-12-12-46-Permutations.md ├── 2018-12-12-46-Permutations.py ├── 2018-12-12-47-Permutations-II.md ├── 2018-12-12-47-Permutations-II.py ├── 2018-12-13-48-Rotate-Image.md ├── 2018-12-13-48-Rotate-Image.py ├── 2018-12-13-49-Group-Anagrams.md ├── 2018-12-13-49-Group-Anagrams.py ├── 2018-12-13-50-Pow-x-n.md ├── 2018-12-13-50-Pow-x-n.py ├── 2018-12-14-51-N-Queens.md ├── 2018-12-14-51-N-Queens.py ├── 2018-12-14-52-N-Queens-II.md ├── 2018-12-14-52-N-Queens-II.py ├── 2018-12-14-53-Maximum-Subarray.md ├── 2018-12-14-53-Maximum-Subarray.py ├── 2018-12-15-54-Spiral-Matrix.md ├── 2018-12-15-54-Spiral-Matrix.py ├── 2018-12-15-55-Jump-Game.md ├── 2018-12-15-55-Jump-Game.py ├── 2018-12-15-56-Merge-Intervals.md ├── 2018-12-15-56-Merge-Intervals.py ├── 2018-12-16-57-Insert-Interval.md ├── 2018-12-16-57-Insert-Interval.py ├── 2018-12-16-58-Length-of-Last-Word.md ├── 2018-12-16-58-Length-of-Last-Word.py ├── 2018-12-17-59-Spiral-Matrix-II.md ├── 2018-12-17-59-Spiral-Matrix-II.py ├── 2018-12-17-60-Permutation-Sequence.md ├── 2018-12-17-60-Permutation-Sequence.py ├── 2018-12-17-61-Rotate-List.md ├── 2018-12-17-61-Rotate-List.py ├── 2018-12-17-62-Unique-Paths.md ├── 2018-12-17-62-Unique-Paths.py ├── 2018-12-17-63-Unique-Paths-II.md ├── 2018-12-17-63-Unique-Paths-II.py ├── 2018-12-17-64-Minimum-Path-Sum.md ├── 2018-12-17-64-Minimum-Path-Sum.py ├── 2018-12-18-65-Valid-Number.md ├── 2018-12-18-65-Valid-Number.py ├── 2018-12-18-66-Plus-One.md ├── 2018-12-18-66-Plus-One.py ├── 2018-12-18-67-Add-Binary.md ├── 2018-12-18-67-Add-Binary.py ├── 2018-12-18-68-Text-Justification.md ├── 2018-12-18-68-Text-Justification.py ├── 2018-12-19-69-Sqrt-x.md ├── 2018-12-19-69-Sqrt-x.py ├── 2018-12-19-70-Climbing-Stairs.md ├── 2018-12-19-70-Climbing-Stairs.py ├── 2018-12-19-71-Simplify-Path.md ├── 2018-12-19-71-Simplify-Path.py ├── 2018-12-20-72-Edit-Distance.md ├── 2018-12-20-72-Edit-Distance.py ├── 2018-12-20-73-Set-Matrix-Zeroes.md ├── 2018-12-20-73-Set-Matrix-Zeroes.py ├── 2018-12-21-74-Search-a-2D-Matrix.md ├── 2018-12-21-74-Search-a-2D-Matrix.py ├── 2018-12-21-75-Sort-Colors.md ├── 2018-12-21-75-Sort-Colors.py ├── 2018-12-21-76-Minimum-Window-Substring.md ├── 2018-12-21-76-Minimum-Window-Substring.py ├── 2018-12-22-77-Combinations.md ├── 2018-12-22-77-Combinations.py ├── 2018-12-22-78-Subsets.md ├── 2018-12-22-78-Subsets.py ├── 2018-12-22-79-Word-Search.md ├── 2018-12-22-79-Word-Search.py ├── 2018-12-22-80-Remove-Duplicates-from-Sorted-Array-II.md ├── 2018-12-22-80-Remove-Duplicates-from-Sorted-Array-II.py ├── 2018-12-23-81-Search-in-Rotated-Sorted-Array-II.md ├── 2018-12-23-81-Search-in-Rotated-Sorted-Array-II.py ├── 2018-12-23-82-Remove-Duplicates-from-Sorted-List-II.md ├── 2018-12-23-82-Remove-Duplicates-from-Sorted-List-II.py ├── 2018-12-23-83-Remove-Duplicates-from-Sorted-List.md ├── 2018-12-23-83-Remove-Duplicates-from-Sorted-List.py ├── 2018-12-24-84-Largest-Rectangle-in-Histogram.md ├── 2018-12-24-84-Largest-Rectangle-in-Histogram.py ├── 2018-12-24-85-Maximal-Rectangle.md ├── 2018-12-24-85-Maximal-Rectangle.py ├── 2018-12-25-86-Partition-List.md ├── 2018-12-25-86-Partition-List.py ├── 2018-12-25-87-Scramble-String.md ├── 2018-12-25-87-Scramble-String.py ├── 2018-12-25-88-Merge-Sorted-Array.md ├── 2018-12-25-88-Merge-Sorted-Array.py ├── 2018-12-25-89-Gray-Code.md ├── 2018-12-25-89-Gray-Code.py ├── 2018-12-25-90-Subsets-II.md ├── 2018-12-25-90-Subsets-II.py ├── 2018-12-25-91-Decode-Ways.md ├── 2018-12-25-91-Decode-Ways.py ├── 2018-12-26-92-Reverse-Linked-List-II.md ├── 2018-12-26-92-Reverse-Linked-List-II.py ├── 2018-12-26-93-Restore-IP-Addresses.md ├── 2018-12-26-93-Restore-IP-Addresses.py ├── 2018-12-26-94-Binary-Tree-Inorder-Traversal.md ├── 2018-12-26-94-Binary-Tree-Inorder-Traversal.py ├── 2018-12-27-95-Unique-Binary-Search-Trees-II.md ├── 2018-12-27-95-Unique-Binary-Search-Trees-II.py ├── 2018-12-27-96-Unique-Binary-Search-Trees.md ├── 2018-12-27-96-Unique-Binary-Search-Trees.py ├── 2018-12-28-100-Same-Tree.md ├── 2018-12-28-100-Same-Tree.py ├── 2018-12-28-97-Interleaving-String.md ├── 2018-12-28-97-Interleaving-String.py ├── 2018-12-28-98-Validate-Binary-Search-Tree.md ├── 2018-12-28-98-Validate-Binary-Search-Tree.py ├── 2018-12-28-99-Recover-Binary-Search-Tree.md ├── 2018-12-28-99-Recover-Binary-Search-Tree.py ├── 2018-12-29-101-Symmetric-Tree.md ├── 2018-12-29-101-Symmetric-Tree.py ├── 2018-12-29-102-Binary-Tree-Level-Order-Traversal.md ├── 2018-12-29-102-Binary-Tree-Level-Order-Traversal.py ├── 2018-12-29-103-Binary-Tree-Zigzag-Level-Order-Traversal.md ├── 2018-12-29-103-Binary-Tree-Zigzag-Level-Order-Traversal.py ├── 2018-12-29-104-Maximum-Depth-of-Binary-Tree.md ├── 2018-12-29-104-Maximum-Depth-of-Binary-Tree.py ├── 2018-12-30-105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.md ├── 2018-12-30-105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py ├── 2018-12-30-106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.md ├── 2018-12-30-106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.py ├── 2018-12-30-107-Binary-Tree-Level-Order-Traversal-II.md ├── 2018-12-30-107-Binary-Tree-Level-Order-Traversal-II.py ├── 2018-12-30-108-Convert-Sorted-Array-to-Binary-Search-Tree.md ├── 2018-12-30-108-Convert-Sorted-Array-to-Binary-Search-Tree.py ├── 2018-12-30-109-Convert-Sorted-List-to-Binary-Search-Tree.md ├── 2018-12-30-109-Convert-Sorted-List-to-Binary-Search-Tree.py ├── 2018-12-31-110-Balanced-Binary-Tree.md ├── 2018-12-31-110-Balanced-Binary-Tree.py ├── 2018-12-31-111-Minimum-Depth-of-Binary-Tree.md ├── 2018-12-31-111-Minimum-Depth-of-Binary-Tree.py ├── 2018-12-31-112-Path-Sum.md ├── 2018-12-31-112-Path-Sum.py ├── 2018-12-31-113.-Path-Sum-II.md ├── 2018-12-31-113.-Path-Sum-II.py ├── 2018-12-31-114-Flatten-Binary-Tree-to-Linked-List.md ├── 2018-12-31-114-Flatten-Binary-Tree-to-Linked-List.py ├── 2018-12-31-115-Distinct-Subsequences.md ├── 2018-12-31-115-Distinct-Subsequences.py ├── 2019-01-01-116-Populating-Next-Right-Pointers-in-Each-Node.md ├── 2019-01-01-116-Populating-Next-Right-Pointers-in-Each-Node.py ├── 2019-01-01-117-Populating-Next-Right-Pointers-in-Each-Node-II.md ├── 2019-01-01-117-Populating-Next-Right-Pointers-in-Each-Node-II.py ├── 2019-01-01-118.-Pascals-Triangle.md ├── 2019-01-01-118.-Pascals-Triangle.py ├── 2019-01-01-119-Pascals-Triangle-II.md ├── 2019-01-01-119-Pascals-Triangle-II.py ├── 2019-01-01-120-Triangle.md ├── 2019-01-01-120-Triangle.py ├── 2019-01-02-121-Best-Time-to-Buy-and-Sell-Stock.md ├── 2019-01-02-121-Best-Time-to-Buy-and-Sell-Stock.py ├── 2019-01-02-122-Best-Time-to-Buy-and-Sell-Stock-II.md ├── 2019-01-02-122-Best-Time-to-Buy-and-Sell-Stock-II.py ├── 2019-01-02-123-Best-Time-to-Buy-and-Sell-Stock-III.md ├── 2019-01-02-123-Best-Time-to-Buy-and-Sell-Stock-III.py ├── 2019-01-03-124-Binary-Tree-Maximum-Path-Sum.md ├── 2019-01-03-124-Binary-Tree-Maximum-Path-Sum.py ├── 2019-01-03-125-Valid-Palindrome.md ├── 2019-01-03-125-Valid-Palindrome.py ├── 2019-01-03-126-Word-Ladder-II.md ├── 2019-01-03-126-Word-Ladder-II.py ├── 2019-01-03-127-Word-Ladder.md ├── 2019-01-03-127-Word-Ladder.py ├── 2019-01-05-128-Longest-Consecutive-Sequence.md ├── 2019-01-05-128-Longest-Consecutive-Sequence.py ├── 2019-01-05-129-Sum-Root-to-Leaf-Numbers.md ├── 2019-01-05-129-Sum-Root-to-Leaf-Numbers.py ├── 2019-01-05-130-Surrounded-Regions.md ├── 2019-01-05-130-Surrounded-Regions.py ├── 2019-01-06-131-Palindrome-Partitioning.md ├── 2019-01-06-131-Palindrome-Partitioning.py ├── 2019-01-06-132-Palindrome-Partitioning-II.md ├── 2019-01-06-132-Palindrome-Partitioning-II.py ├── 2019-01-07-133-Clone-Graph.md ├── 2019-01-07-133-Clone-Graph.py ├── 2019-01-07-134-Gas-Station.md ├── 2019-01-07-134-Gas-Station.py ├── 2019-01-08-135-Candy.md ├── 2019-01-08-135-Candy.py ├── 2019-01-08-136-Single-Number.md ├── 2019-01-08-136-Single-Number.py ├── 2019-01-09-137-Single-Number-II.md ├── 2019-01-09-137-Single-Number-II.py ├── 2019-01-10-138-Copy-List-with-Random-Pointer.md ├── 2019-01-10-138-Copy-List-with-Random-Pointer.py ├── 2019-01-10-139-Word-Break.md ├── 2019-01-10-139-Word-Break.py ├── 2019-01-10-140-Word-Break-II.md ├── 2019-01-10-140-Word-Break-II.py ├── 2019-01-10-141-Linked-List-Cycle.md ├── 2019-01-10-141-Linked-List-Cycle.py ├── 2019-01-12-142-Linked-List-Cycle-II.md ├── 2019-01-12-142-Linked-List-Cycle-II.py ├── 2019-01-12-143-Reorder-List.md ├── 2019-01-12-143-Reorder-List.py ├── 2019-01-12-144-Binary-Tree-Preorder-Traversal.md ├── 2019-01-12-144-Binary-Tree-Preorder-Traversal.py ├── 2019-01-12-145-Binary-Tree-Postorder-Traversal.md ├── 2019-01-12-145-Binary-Tree-Postorder-Traversal.py ├── 2019-01-13-146-LRU-Cache.md ├── 2019-01-13-146-LRU-Cache.py ├── 2019-01-13-147-Insertion-Sort-List.md ├── 2019-01-13-147-Insertion-Sort-List.py ├── 2019-01-13-148-Sort-List.md ├── 2019-01-13-148-Sort-List.py ├── 2019-01-14-149-Max-Points-on-a-Line.md ├── 2019-01-14-149-Max-Points-on-a-Line.py ├── 2019-01-14-150-Evaluate-Reverse-Polish-Notation.md ├── 2019-01-14-150-Evaluate-Reverse-Polish-Notation.py ├── 2019-01-15-151-Reverse-Words-in-a-String.md ├── 2019-01-15-151-Reverse-Words-in-a-String.py ├── 2019-01-15-152-Maximum-Product-Subarray.md ├── 2019-01-15-152-Maximum-Product-Subarray.py ├── 2019-01-15-153-Find-Minimum-in-Rotated-Sorted-Array.md ├── 2019-01-15-153-Find-Minimum-in-Rotated-Sorted-Array.py ├── 2019-01-15-154-Find-Minimum-in-Rotated-Sorted-Array-II.md ├── 2019-01-15-154-Find-Minimum-in-Rotated-Sorted-Array-II.py ├── 2019-01-15-155-Min-Stack.md ├── 2019-01-15-155-Min-Stack.py ├── 2019-01-16-160-Intersection-of-Two-Linked-Lists.md ├── 2019-01-16-160-Intersection-of-Two-Linked-Lists.py ├── 2019-01-16-162-Find-Peak-Element.md ├── 2019-01-16-162-Find-Peak-Element.py ├── 2019-01-16-164-Maximum-Gap.md ├── 2019-01-16-164-Maximum-Gap.py ├── 2019-01-16-165-Compare-Version-Numbers.md ├── 2019-01-16-165-Compare-Version-Numbers.py ├── 2019-01-16-166-Fraction-to-Recurring-Decimal.md ├── 2019-01-16-166-Fraction-to-Recurring-Decimal.py ├── 2019-01-16-167-Two-Sum-II-Input-array-is-sorted.md ├── 2019-01-16-167-Two-Sum-II-Input-array-is-sorted.py ├── 2019-01-16-168-Excel-Sheet-Column-Title.md ├── 2019-01-16-168-Excel-Sheet-Column-Title.py ├── 2019-01-16-169-Majority-Element.md ├── 2019-01-16-169-Majority-Element.py ├── 2019-01-16-171-Excel-Sheet-Column-Number.md ├── 2019-01-16-171-Excel-Sheet-Column-Number.py ├── 2019-01-17-172-Factorial-Trailing-Zeroes.md ├── 2019-01-17-172-Factorial-Trailing-Zeroes.py ├── 2019-01-17-173-Binary-Search-Tree-Iterator.md ├── 2019-01-17-173-Binary-Search-Tree-Iterator.py ├── 2019-01-17-174-Dungeon-Game.md ├── 2019-01-17-174-Dungeon-Game.py ├── 2019-01-17-179-Largest-Number.md ├── 2019-01-17-179-Largest-Number.py ├── 2019-01-18-187-Repeated-DNA-Sequences.md ├── 2019-01-18-187-Repeated-DNA-Sequences.py ├── 2019-01-19-188-Best-Time-to-Buy-and-Sell-Stock-IV.md ├── 2019-01-19-188-Best-Time-to-Buy-and-Sell-Stock-IV.py ├── 2019-01-19-189-Rotate-Array.md ├── 2019-01-19-189-Rotate-Array.py ├── 2019-01-19-190-Reverse-Bits.md ├── 2019-01-19-190-Reverse-Bits.py ├── 2019-01-19-191-Number-of-1-Bits.md ├── 2019-01-19-191-Number-of-1-Bits.py ├── 2019-01-20-198-House-Robber.md ├── 2019-01-20-198-House-Robber.py ├── 2019-01-20-199-Binary-Tree-Right-Side-View.md ├── 2019-01-20-199-Binary-Tree-Right-Side-View.py ├── 2019-01-20-200-Number-of-Islands.md ├── 2019-01-20-200-Number-of-Islands.py ├── 2019-01-20-201-Bitwise-AND-of-Numbers-Range.md ├── 2019-01-20-201-Bitwise-AND-of-Numbers-Range.py ├── 2019-01-20-202-Happy-Number.md ├── 2019-01-20-202-Happy-Number.py ├── 2019-01-20-203-Remove-Linked-List-Elements.md ├── 2019-01-20-203-Remove-Linked-List-Elements.py ├── 2019-01-20-204-Count-Primes.md ├── 2019-01-20-204-Count-Primes.py ├── 2019-01-21-205-Isomorphic-Strings.md ├── 2019-01-21-205-Isomorphic-Strings.py ├── 2019-01-21-206-Reverse-Linked-List.md ├── 2019-01-21-206-Reverse-Linked-List.py ├── 2019-01-21-207-Course-Schedule.md ├── 2019-01-21-207-Course-Schedule.py ├── 2019-01-22-208-Implement-Trie-Prefix-Tree.md ├── 2019-01-22-208-Implement-Trie-Prefix-Tree.py ├── 2019-01-22-209-Minimum-Size-Subarray-Sum.md ├── 2019-01-22-209-Minimum-Size-Subarray-Sum.py ├── 2019-01-22-210-Course-Schedule-II.md ├── 2019-01-22-210-Course-Schedule-II.py ├── 2019-01-22-211-Add-and-Search-Word-Data-structure-design.md ├── 2019-01-22-211-Add-and-Search-Word-Data-structure-design.py ├── 2019-01-22-212-Word-Search-II.md ├── 2019-01-22-212-Word-Search-II.py ├── 2019-01-22-213-House-Robber-II.md ├── 2019-01-22-213-House-Robber-II.py ├── 2019-01-23-214-Shortest-Palindrome.md ├── 2019-01-23-214-Shortest-Palindrome.py ├── 2019-01-23-215-Kth-Largest-Element-in-an-Array.md ├── 2019-01-23-215-Kth-Largest-Element-in-an-Array.py ├── 2019-01-24-216-Combination-Sum-III.md ├── 2019-01-24-216-Combination-Sum-III.py ├── 2019-01-24-217-Contains-Duplicate.md ├── 2019-01-24-217-Contains-Duplicate.py ├── 2019-01-24-218-The-Skyline-Problem.md ├── 2019-01-24-218-The-Skyline-Problem.py ├── 2019-01-25-219-Contains-Duplicate-II.md ├── 2019-01-25-219-Contains-Duplicate-II.py ├── 2019-01-25-220-Contains-Duplicate-III.md ├── 2019-01-25-220-Contains-Duplicate-III.py ├── 2019-01-26-221-Maximal-Square.md ├── 2019-01-26-221-Maximal-Square.py ├── 2019-01-27-222-Count-Complete-Tree-Nodes.md ├── 2019-01-27-222-Count-Complete-Tree-Nodes.py ├── 2019-01-28-223-Rectangle-Area.md ├── 2019-01-28-223-Rectangle-Area.py ├── 2019-01-28-224-Basic-Calculator.md ├── 2019-01-28-224-Basic-Calculator.py ├── 2019-01-28-225-Implement-Stack-using-Queues.md ├── 2019-01-28-225-Implement-Stack-using-Queues.py ├── 2019-01-28-226-Invert-Binary-Tree.md ├── 2019-01-28-226-Invert-Binary-Tree.py ├── 2019-01-28-227-Basic-Calculator-II.md ├── 2019-01-28-227-Basic-Calculator-II.py ├── 2019-01-29-228-Summary-Ranges.md ├── 2019-01-29-228-Summary-Ranges.py ├── 2019-01-31-229-Majority-Element-II.md ├── 2019-01-31-229-Majority-Element-II.py ├── 2019-01-31-230-Kth-Smallest-Element-in-a-BST.md ├── 2019-01-31-230-Kth-Smallest-Element-in-a-BST.py ├── 2019-01-31-231-Power-of-Two.md ├── 2019-01-31-231-Power-of-Two.py ├── 2019-02-01-232-Implement-Queue-using-Stacks.md ├── 2019-02-01-232-Implement-Queue-using-Stacks.py ├── 2019-02-01-233-Number-of-Digit-One.md ├── 2019-02-01-233-Number-of-Digit-One.py ├── 2019-02-01-234-Palindrome-Linked-List.md ├── 2019-02-01-234-Palindrome-Linked-List.py ├── 2019-02-01-235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.md ├── 2019-02-01-235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.py ├── 2019-02-01-236-Lowest-Common-Ancestor-of-a-Binary-Tree.md ├── 2019-02-01-236-Lowest-Common-Ancestor-of-a-Binary-Tree.py ├── 2019-02-01-237-Delete-Node-in-a-Linked-List.md ├── 2019-02-01-237-Delete-Node-in-a-Linked-List.py ├── 2019-02-02-238-Product-of-Array-Except-Self.md ├── 2019-02-02-238-Product-of-Array-Except-Self.py ├── 2019-02-02-239-Sliding-Window-Maximum.md ├── 2019-02-02-239-Sliding-Window-Maximum.py ├── 2019-02-02-240-Search-a-2D-Matrix-II.md ├── 2019-02-02-240-Search-a-2D-Matrix-II.py ├── 2019-02-02-241-Different-Ways-to-Add-Parentheses.md ├── 2019-02-02-241-Different-Ways-to-Add-Parentheses.py ├── 2019-02-02-242-Valid-Anagram.md ├── 2019-02-02-242-Valid-Anagram.py ├── 2019-02-02-257-Binary-Tree-Paths.md ├── 2019-02-02-257-Binary-Tree-Paths.py ├── 2019-02-02-258-Add-Digits.md ├── 2019-02-02-258-Add-Digits.py ├── 2019-02-03-260-Single-Number-III.md ├── 2019-02-03-260-Single-Number-III.py ├── 2019-02-03-263-Ugly-Number.md ├── 2019-02-03-263-Ugly-Number.py ├── 2019-02-04-264-Ugly-Number-II.md ├── 2019-02-04-264-Ugly-Number-II.py ├── 2019-02-04-268-Missing-Number.md ├── 2019-02-04-268-Missing-Number.py ├── 2019-02-04-273-Integer-to-English-Words.md ├── 2019-02-04-273-Integer-to-English-Words.py ├── 2019-02-05-274-H-Index.md ├── 2019-02-05-274-H-Index.py ├── 2019-02-05-275-H-Index-II.md ├── 2019-02-05-275-H-Index-II.py ├── 2019-02-05-278-First-Bad-Version.md ├── 2019-02-05-278-First-Bad-Version.py ├── 2019-02-06-279-Perfect-Squares.md ├── 2019-02-06-279-Perfect-Squares.py ├── 2019-02-07-282-Expression-Add-Operators.md ├── 2019-02-07-282-Expression-Add-Operators.py ├── 2019-02-07-283-Move-Zeroes.md ├── 2019-02-07-283-Move-Zeroes.py ├── 2019-02-07-284-Peeking-Iterator.md ├── 2019-02-07-284-Peeking-Iterator.py ├── 2019-02-07-287-Find-the-Duplicate-Number.md ├── 2019-02-07-287-Find-the-Duplicate-Number.py ├── 2019-02-08-289-Game-of-Life.md ├── 2019-02-08-289-Game-of-Life.py ├── 2019-02-08-290-Word-Pattern.md ├── 2019-02-08-290-Word-Pattern.py ├── 2019-02-08-292-Nim-Game.md ├── 2019-02-08-292-Nim-Game.py ├── 2019-02-08-295-Find-Median-from-Data-Stream.md ├── 2019-02-08-295-Find-Median-from-Data-Stream.py ├── 2019-02-08-297-Serialize-and-Deserialize-Binary-Tree.md ├── 2019-02-08-297-Serialize-and-Deserialize-Binary-Tree.py ├── 2019-02-08-299-Bulls-and-Cows.md ├── 2019-02-08-299-Bulls-and-Cows.py ├── 2019-02-08-300-Longest-Increasing-Subsequence.md ├── 2019-02-08-300-Longest-Increasing-Subsequence.py ├── 2019-02-10-301-Remove-Invalid-Parentheses.md ├── 2019-02-10-301-Remove-Invalid-Parentheses.py ├── 2019-02-10-303-Range-Sum-Query-Immutable.md ├── 2019-02-10-303-Range-Sum-Query-Immutable.py ├── 2019-02-11-304-Range-Sum-Query-2D-Immutable.md ├── 2019-02-11-304-Range-Sum-Query-2D-Immutable.py ├── 2019-02-11-306-Additive-Number.md ├── 2019-02-11-306-Additive-Number.py ├── 2019-02-12-307-Range-Sum-Query-Mutable.md ├── 2019-02-12-307-Range-Sum-Query-Mutable.py ├── 2019-02-13-309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.md ├── 2019-02-13-309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.py ├── 2019-02-17-310-Minimum-Height-Trees.md ├── 2019-02-17-310-Minimum-Height-Trees.py ├── 2019-02-18-312-Burst-Balloons.md ├── 2019-02-18-312-Burst-Balloons.py ├── 2019-02-19-313-Super-Ugly-Number.md ├── 2019-02-19-313-Super-Ugly-Number.py ├── 2019-02-20-binary-serach-tree.py ├── 2019-02-21-315-Count-of-Smaller-Numbers-After-Self.md ├── 2019-02-21-315-Count-of-Smaller-Numbers-After-Self.py ├── 2019-02-22-316-Remove-Duplicate-Letters.md ├── 2019-02-22-316-Remove-Duplicate-Letters.py ├── 2019-02-23-318-Maximum-Product-of-Word-Lengths.md ├── 2019-02-23-318-Maximum-Product-of-Word-Lengths.py ├── 2019-02-23-319-Bulb-Switcher.md ├── 2019-02-23-319-Bulb-Switcher.py ├── 2019-02-24-321-Create-Maximum-Number.md ├── 2019-02-24-321-Create-Maximum-Number.py ├── 2019-03-01-322-Coin-Change.md ├── 2019-03-01-322-Coin-Change.py ├── 2019-03-02-326-Power-of-Three.md ├── 2019-03-02-326-Power-of-Three.py ├── 2019-03-02-327-Count-of-Range-Sum.md ├── 2019-03-02-327-Count-of-Range-Sum.py ├── 2019-03-03-328-Odd-Even-Linked-List.md ├── 2019-03-03-328-Odd-Even-Linked-List.py ├── 2019-03-07-329-Longest-Increasing-Path-in-a-Matrix.md ├── 2019-03-07-329-Longest-Increasing-Path-in-a-Matrix.py ├── 2019-03-14-330-Patching-Array.md ├── 2019-03-14-330-Patching-Array.py ├── 2019-03-17-331-Verify-Preorder-Serialization-of-a-Binary-Tree.md ├── 2019-03-17-331-Verify-Preorder-Serialization-of-a-Binary-Tree.py ├── 2019-03-27-332-Reconstruct-Itinerary.md ├── 2019-03-27-332-Reconstruct-Itinerary.py ├── 2019-03-28-334-Increasing-Triplet-Subsequence.md ├── 2019-03-28-334-Increasing-Triplet-Subsequence.py ├── 2019-04-06-336-Palindrome-Pairs.md ├── 2019-04-06-336-Palindrome-Pairs.py ├── 2019-04-07-337-House-Robber-III.md ├── 2019-04-07-337-House-Robber-III.py ├── 2019-04-07-338-Counting-Bits.md ├── 2019-04-07-338-Counting-Bits.py ├── 2019-04-08-341-Flatten-Nested-List-Iterator.md ├── 2019-04-08-341-Flatten-Nested-List-Iterator.py ├── 2019-04-08-342-Power-of-Four.md ├── 2019-04-08-342-Power-of-Four.py ├── 2019-04-08-343-Integer-Break.md ├── 2019-04-08-343-Integer-Break.py ├── 2019-04-08-344-Reverse-String.md ├── 2019-04-08-344-Reverse-String.py ├── 2019-04-08-345-Reverse-Vowels-of-a-String.md ├── 2019-04-08-345-Reverse-Vowels-of-a-String.py ├── 2019-04-09-347-Top-K-Frequent-Elements.md ├── 2019-04-09-347-Top-K-Frequent-Elements.py ├── 2019-04-09-349-Intersection-of-Two-Arrays.md ├── 2019-04-09-349-Intersection-of-Two-Arrays.py ├── 2019-04-09-350-Intersection-of-Two-Arrays-II.md ├── 2019-04-09-350-Intersection-of-Two-Arrays-II.py ├── 2019-06-01-352-Data-Stream-as-Disjoint-Intervals.md ├── 2019-06-01-352-Data-Stream-as-Disjoint-Intervals.py ├── 2019-06-02-354-Russian-Doll-Envelopes.md ├── 2019-06-02-354-Russian-Doll-Envelopes.py ├── 2019-06-04-357-Count-Numbers-with-Unique-Digits.md ├── 2019-06-04-357-Count-Numbers-with-Unique-Digits.py ├── 2019-06-11-363-Max-Sum-of-Rectangle-No-Larger-Than-K.md ├── 2019-06-11-363-Max-Sum-of-Rectangle-No-Larger-Than-K.py ├── 2019-06-13-365-Water-and-Jug-Problem.md ├── 2019-06-13-365-Water-and-Jug-Problem.py ├── 2019-06-13-367-Valid-Perfect-Square.md ├── 2019-06-13-367-Valid-Perfect-Square.py ├── 2019-06-14-368-Largest-Divisible-Subset.md ├── 2019-06-14-368-Largest-Divisible-Subset.py ├── 2019-06-27-372-Super-Pow.md ├── 2019-06-27-372-Super-Pow.py ├── 2019-06-28-373-Find-K-Pairs-with-Smallest-Sums.md ├── 2019-06-28-373-Find-K-Pairs-with-Smallest-Sums.py ├── 2019-06-28-374-Guess-Number-Higher-or-Lower.md ├── 2019-06-28-374-Guess-Number-Higher-or-Lower.py ├── 2019-06-30-375-Guess-Number-Higher-or-Lower-II.md ├── 2019-06-30-375-Guess-Number-Higher-or-Lower-II.py ├── 2019-07-13-376-Wiggle-Subsequence.md ├── 2019-07-13-376-Wiggle-Subsequence.py ├── 2019-07-20-377-Combination-Sum-IV.md ├── 2019-07-20-377-Combination-Sum-IV.py ├── 2019-07-27-378-Kth-Smallest-Element-in-a-Sorted-Matrix.md ├── 2019-07-27-378-Kth-Smallest-Element-in-a-Sorted-Matrix.py ├── 2019-07-27-380-Insert-Delete-GetRandom-O1.md ├── 2019-07-27-380-Insert-Delete-GetRandom-O1.py ├── 2019-07-27-381-Insert-Delete-GetRandom-O1-Duplicates-allowed.md ├── 2019-07-27-381-Insert-Delete-GetRandom-O1-Duplicates-allowed.py ├── 2019-07-30-382-Linked-List-Random-Node.md ├── 2019-07-30-382-Linked-List-Random-Node.py ├── 2019-07-30-383-Ransom-Note.md ├── 2019-07-30-383-Ransom-Note.py ├── 2019-08-03-384-Shuffle-an-Array.md ├── 2019-08-03-384-Shuffle-an-Array.py ├── 2019-08-03-385-Mini-Parser.md ├── 2019-08-03-385-Mini-Parser.py ├── 2019-08-03-386-Lexicographical-Numbers.md ├── 2019-08-03-386-Lexicographical-Numbers.py ├── 2019-08-03-387-First-Unique-Character-in-a-String.md ├── 2019-08-03-387-First-Unique-Character-in-a-String.py ├── 2019-08-04-388-Longest-Absolute-File-Path.md ├── 2019-08-04-388-Longest-Absolute-File-Path.py ├── 2019-08-04-389-Find-the-Difference.md ├── 2019-08-04-389-Find-the-Difference.py ├── 2019-08-10-390-Elimination-Game.md ├── 2019-08-10-390-Elimination-Game.py ├── 2019-08-10-391-Perfect-Rectangle.md ├── 2019-08-10-391-Perfect-Rectangle.py ├── 2019-08-11-41-First-Missing-Positive.md ├── 2019-08-11-41-First-Missing-Positive.py ├── 2019-08-17-392-Is-Subsequence.md ├── 2019-08-17-392-Is-Subsequence.py ├── 2019-08-18-38-Count-and-Say.md ├── 2019-08-18-38-Count-and-Say.py ├── 2019-08-24-393-UTF-8-Validation.md ├── 2019-08-24-393-UTF-8-Validation.py ├── 2019-08-25-394-Decode-String.md ├── 2019-08-25-394-Decode-String.py ├── 2019-08-27-395-Longest-Substring-with-At-Least-K-Repeating-Characters.md ├── 2019-08-27-395-Longest-Substring-with-At-Least-K-Repeating-Characters.py ├── 2019-08-28-396-Rotate-Function.md ├── 2019-08-28-396-Rotate-Function.py ├── 2019-08-29-397-Integer-Replacement.md ├── 2019-08-29-397-Integer-Replacement.py ├── 2019-08-30-398-Random-Pick-Index.md ├── 2019-08-30-398-Random-Pick-Index.py ├── 2019-09-01-399-Evaluate-Division.md ├── 2019-09-01-399-Evaluate-Division.py ├── 2019-09-02-400-Nth-Digit.md ├── 2019-09-02-400-Nth-Digit.py ├── 2019-09-03-401-Binary-Watch.md ├── 2019-09-03-401-Binary-Watch.py ├── 2019-09-07-402-Remove-K-Digits.md ├── 2019-09-07-402-Remove-K-Digits.py ├── 2019-09-08-403-Frog-Jump.md ├── 2019-09-08-403-Frog-Jump.py ├── 2019-09-14-404-Sum-of-Left-Leaves.md ├── 2019-09-14-404-Sum-of-Left-Leaves.py ├── 2019-09-14-405-Convert-a-Number-to-Hexadecimal.md ├── 2019-09-14-405-Convert-a-Number-to-Hexadecimal.py ├── 2019-10-02-406-Queue-Reconstruction-by-Height.md ├── 2019-10-02-406-Queue-Reconstruction-by-Height.py ├── 2019-10-03-407-Trapping-Rain-Water-II.md ├── 2019-10-03-407-Trapping-Rain-Water-II.py ├── 2019-10-03-409-Longest-Palindrome.md ├── 2019-10-03-409-Longest-Palindrome.py ├── 2019-10-04-410-Split-Array-Largest-Sum.md ├── 2019-10-04-410-Split-Array-Largest-Sum.py ├── 2019-10-05-412-Fizz-Buzz.md ├── 2019-10-05-412-Fizz-Buzz.py ├── 2019-10-13-413-Arithmetic-Slices.md ├── 2019-10-13-413-Arithmetic-Slices.py ├── 2019-10-13-414-Third-Maximum-Number.md ├── 2019-10-13-414-Third-Maximum-Number.py ├── 2019-10-14-415-Add-Strings.md ├── 2019-10-14-415-Add-Strings.py ├── 2019-10-26-416-Partition-Equal-Subset-Sum.md ├── 2019-10-26-416-Partition-Equal-Subset-Sum.py ├── 2019-11-02-417-Pacific-Atlantic-Water-Flow.md ├── 2019-11-02-417-Pacific-Atlantic-Water-Flow.py ├── 2019-11-16-419-Battleships-in-a-Board.md ├── 2019-11-16-419-Battleships-in-a-Board.py ├── 2019-11-30-421-Maximum-XOR-of-Two-Numbers-in-an-Array.md ├── 2019-11-30-421-Maximum-XOR-of-Two-Numbers-in-an-Array.py ├── 2019-11-30-423-Reconstruct-Original-Digits-from-English.md ├── 2019-11-30-423-Reconstruct-Original-Digits-from-English.py ├── 2019-11-30-424-Longest-Repeating-Character-Replacement.md ├── 2019-11-30-424-Longest-Repeating-Character-Replacement.py ├── 2019-12-14-427-Construct-Quad-Tree.md ├── 2019-12-14-427-Construct-Quad-Tree.py ├── 2019-12-28-429-N-ary-Tree-Level-Order-Traversal.md ├── 2019-12-28-429-N-ary-Tree-Level-Order-Traversal.py ├── 2019-12-29-430-Flatten-a-Multilevel-Doubly-Linked-List.md ├── 2019-12-29-430-Flatten-a-Multilevel-Doubly-Linked-List.py ├── 2020-01-26-432-All-Oone-Data-Structure.py ├── 2020-01-30-433-Minimum-Genetic-Mutation.md ├── 2020-01-30-433-Minimum-Genetic-Mutation.py ├── 2020-03-31-435-Non-overlapping-Intervals.md ├── 2020-03-31-435-Non-overlapping-Intervals.py ├── 2020-04-11-436-Find-Right-Interval.md ├── 2020-04-11-436-Find-Right-Interval.py ├── 2020-05-01-437-Path-Sum-III.md ├── 2020-05-01-437-Path-Sum-III.py ├── 2020-05-05-438-Find-All-Anagrams-in-a-String.md ├── 2020-05-05-438-Find-All-Anagrams-in-a-String.py └── C │ ├── 2017-11-10-Two_Sums_easy.c │ ├── 2017-11-12-Add_Two_Numbers_medium.c │ ├── 2017-11-14-Longest Substring Without Repeating Characters medium.c │ ├── 2017-11-15-Median of Two Sorted Arrays hard.c │ ├── 2017-11-20-Longest Palindromic Substring medium.c │ ├── 2017-11-21-Reverse Integer easy.c │ ├── 2017-11-21-ZigZag Conversion medium.c │ ├── 2017-11-23-Palindrome Number easy.c │ ├── 2017-11-24-Container With Most Water medium.c │ ├── 2017-11-25-Integer to Roman medium.c │ ├── 2017-11-28-Translocation method encryption.c │ ├── 2017-11-29-3Sum medium.c │ ├── 2017-11-29-计算机设计大赛-易位法加密.c │ ├── 2017-11-30-16. 3Sum Closest medium.c │ ├── 2017-11-30-17. Letter Combinations of a Phone Number medium.c │ ├── 2017-11-7-Banker_Algorithem.c │ ├── 2017-11-8-(3n+1).c │ ├── 2017-11-8-Insert_sort.c │ ├── 2017-12-1-18. 4Sum medium.c │ ├── 2017-12-1-19. Remove Nth Node From End of List medium.c │ ├── 2017-12-1-20. Valid Parentheses easy.c │ ├── 2017-12-30-22. Generate Parentheses medium.c │ ├── 2017-12-30-23. Merge k Sorted Lists hard.c │ ├── 2017-12-5-21. Merge Two Sorted Lists easy.c │ ├── 2018-1-12-Banker's_Algorithm.c │ ├── 2018-1-14-FIFO_PageReplacement.c │ ├── 2018-1-18-13. Roman to Integer.c │ ├── 2018-1-18-28. Implement strStr.c │ ├── 2018-1-18-29. Divide Two Integers.c │ ├── 2018-1-18-8. String to Integer (atoi).c │ ├── 2018-1-18-Longest Common Prefix.c │ ├── 2018-1-2-24. Swap Nodes in Pairs.c │ ├── 2018-1-2-25. Reverse Nodes in k-Group hard.c │ ├── 2018-1-2-26. Remove Duplicates from Sorted Array easy.c │ ├── 2018-1-2-27. Remove Element easy.c │ ├── 2018-1-20-10. Regular Expression Matching.c │ ├── 2018-1-24-LRU Page replacement.c │ ├── 2018-1-24-LRU Page replacement.js │ ├── 2018-2-5-30. Substring with Concatenation of All Words.c │ ├── 2018-2-5-31.Next Permutation.c │ ├── 2018-2-5-32. Longest Valid Parentheses.c │ ├── 2018-2-6-33. Search in Rotated Sorted Array.c │ ├── 2018-2-6-34. Search for a Range.c │ ├── 2018-2-6-35. Search Insert Position.c │ ├── 2018-3-1-36. Valid Sudoku.c │ ├── 2018-3-19-CaesarsCipher.c │ ├── 2018-3-20-singleTablereplacement.c │ └── 2018-3-5-37. Sudoku Solver.c ├── MySql ├── 01-基础架构.md ├── 02-日志系统.md ├── 03-事务隔离.md ├── 04-索引.md └── 05-锁.md ├── Others ├── 2019-07-12-LD-买切糕.md ├── 2019-07-12-LD-买切糕.py └── 大数据工程师.md ├── README.md ├── receive.jpeg └── wechat.jpeg /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = D203 3 | max-line-length=158 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 何睿 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LeetCode/2018-08-16-Count and Say.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-08-16 11:24:50 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-08-16 12:32:49 6 | 7 | import itertools 8 | 9 | 10 | class Solution: 11 | def countAndSay(self, n): 12 | """ 13 | :type n: int 14 | :rtype: str 15 | """ 16 | result = '1' 17 | for i in range(n-1): 18 | result = ''.join([str(len(list(g)))+key for key, 19 | g in itertools.groupby(result)]) 20 | 21 | return result 22 | 23 | 24 | if __name__ == "__main__": 25 | test = Solution() 26 | result = test.countAndSay(4) 27 | print(result) 28 | -------------------------------------------------------------------------------- /LeetCode/2018-08-23-Direct-Insertion-Sort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-08-23 14:13:36 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-08-23 14:13:36 6 | 7 | import random 8 | 9 | 10 | def DirectInsertionSort(): 11 | 12 | # 直接插入排序,递增排序: 13 | number_list = random.sample(range(0, 500), 20) 14 | print("%-*s" % (15, "UnSorted List"), number_list) 15 | length = len(number_list) 16 | for index in range(1, length): 17 | before = index-1 18 | compare = number_list[index] 19 | while before >= 0 and compare <= number_list[before]: 20 | number_list[before+1] = number_list[before] 21 | before -= 1 22 | number_list[before+1] = compare 23 | print("%-*s" % (15, "Sorted List"), number_list) 24 | 25 | 26 | if __name__ == "__main__": 27 | DirectInsertionSort() 28 | -------------------------------------------------------------------------------- /LeetCode/2018-08-24-Bubble-Sort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-08-24 09:11:10 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-08-24 09:11:10 6 | 7 | import random 8 | 9 | 10 | def BubbleSort(): 11 | number = 20 12 | number_list = random.sample(range(0, 1000), number) 13 | print("%-*s" % (15, "UnSorted List"), number_list) 14 | for index_max in range(number-2, -1, -1): 15 | flag = False 16 | for index in range(0, index_max+1): 17 | if number_list[index] > number_list[index+1]: 18 | temp = number_list[index+1] 19 | number_list[index+1] = number_list[index] 20 | number_list[index] = temp 21 | flag = True 22 | if not flag: 23 | break 24 | print("%-*s" % (15, "Sorted List"), number_list) 25 | 26 | if __name__=="__main__": 27 | BubbleSort() -------------------------------------------------------------------------------- /LeetCode/2018-08-26-Switch.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-08-26 11:23:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-08-26 11:31:42 6 | 7 | import random 8 | from pprint import pprint 9 | 10 | 11 | def switch(): 12 | # 将所有的偶数放到前面,基数放到后面 13 | length = 30 14 | number_list = random.sample(range(-1000, 1000), length) 15 | print(number_list) 16 | i = 0 17 | j = length-1 18 | while i < j: 19 | while number_list[i] % 2 == 0: 20 | i += 1 21 | while number_list[j] % 2 != 0: 22 | j -= 1 23 | temp = number_list[i] 24 | number_list[i] = number_list[j] 25 | number_list[j] = temp 26 | i += 1 27 | j -= 1 28 | print(number_list) 29 | 30 | 31 | if __name__ == "__main__": 32 | switch() 33 | -------------------------------------------------------------------------------- /LeetCode/2018-09-09-iflytek.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-09-09 15:39:48 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-09-09 15:39:48 6 | 7 | import sys 8 | import math 9 | 10 | lines = [list(map(int, line.strip().split())) 11 | for line in sys.stdin.readlines()] 12 | test = lines[1] 13 | n = lines[0][0] 14 | die = 0 15 | day = 0 16 | 17 | i = n-2 18 | j = n-1 19 | temp = [] 20 | while i > -1: 21 | if test[i] > test[j] and test[j] != 0: 22 | die += 1 23 | test[j] = 0 24 | i -= 1 25 | j -= 1 26 | for item in test: 27 | if item != 0: 28 | temp.append(item) 29 | if die != 0: 30 | day += 1 31 | while die != 0: 32 | die = 0 33 | i = len(temp)-2 34 | j = len(temp)-1 35 | while i > -1: 36 | if temp[i] > temp[j] and temp[j] != 0: 37 | die += 1 38 | temp[j] = 0 39 | i -= 1 40 | j -= 1 41 | if die != 0: 42 | day += 1 43 | temp_1 = temp 44 | temp = [] 45 | for item in temp_1: 46 | if item != 0: 47 | temp.append(item) 48 | del temp_1 49 | print(day) 50 | -------------------------------------------------------------------------------- /LeetCode/2018-11-11-Reverse-Linked-List.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-11-11 16:22:54 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-11-11 16:22:54 6 | 7 | class ListNode: 8 | def __init__(self, x): 9 | self.val = x 10 | self.next = None 11 | 12 | class Solution: 13 | def reverseList(self, head): 14 | """ 15 | :type head: ListNode 16 | :rtype: ListNode 17 | """ 18 | 19 | new_head = None 20 | head_next = head.next 21 | while head and head_next : 22 | head.next = new_head 23 | new_head = head 24 | head = head_next 25 | head_next = head_next.next 26 | head.next = new_head 27 | new_head = head 28 | return new_head -------------------------------------------------------------------------------- /LeetCode/2018-11-12-155-Min-Stack.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-11-12 20:28:38 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-11-12 21:02:47 6 | 7 | 8 | class MinStack(object): 9 | 10 | def __init__(self): 11 | """ 12 | initialize your data structure here. 13 | """ 14 | self.stack = [] 15 | 16 | def push(self, x): 17 | """ 18 | :type x: int 19 | :rtype: void 20 | """ 21 | curmin = self.getMin() 22 | if curmin == None or curmin > x: 23 | curmin = x 24 | self.stack.append((x, curmin)) 25 | 26 | def pop(self): 27 | """ 28 | :rtype: void 29 | """ 30 | self.stack.pop() 31 | 32 | def top(self): 33 | """ 34 | :rtype: int 35 | """ 36 | 37 | if len(self.stack) == 0: 38 | return None 39 | else: 40 | return self.stack[len(self.stack)-1][0] 41 | 42 | def getMin(self): 43 | """ 44 | :rtype: int 45 | """ 46 | if len(self.stack) == 0: 47 | return None 48 | else: 49 | return self.stack[len(self.stack)-1][1] 50 | 51 | -------------------------------------------------------------------------------- /LeetCode/2018-11-12-876-Middle-of-the-Linked-List.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-11-12 14:46:42 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-11-12 14:46:42 6 | 7 | 8 | 9 | class ListNode(object): 10 | def __init__(self, x): 11 | self.val = x 12 | self.next = None 13 | 14 | 15 | class Solution(object): 16 | def middleNode(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: ListNode 20 | """ 21 | if head == None: 22 | return None 23 | if head.next == None: 24 | return head 25 | slow, fast = head, head 26 | while True: 27 | if fast.next == None: 28 | return slow 29 | if fast.next.next == None: 30 | return slow.next 31 | slow = slow.next 32 | fast = fast.next.next 33 | 34 | return True 35 | -------------------------------------------------------------------------------- /LeetCode/2018-11-12-Linked-List-Cycle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-11-12 14:14:34 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-11-12 14:42:45 6 | 7 | 8 | class ListNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.next = None 12 | 13 | 14 | class Solution(object): 15 | def hasCycle(self, head): 16 | """ 17 | :type head: ListNode 18 | :rtype 19 | """ 20 | if head == None or head.next == None: 21 | return False 22 | slow = head 23 | fast = head.next 24 | while slow != fast: 25 | if fast == None or fast.next == None: 26 | return False 27 | slow = slow.next 28 | fast = fast.next.next 29 | 30 | return True -------------------------------------------------------------------------------- /LeetCode/2018-11-13-844-Backspace-String-Compare.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-11-13 20:51:10 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-11-13 20:51:10 6 | 7 | 8 | class Solution(object): 9 | def backspaceCompare(self, S, T): 10 | """ 11 | :type S: str 12 | :type T: str 13 | :rtype: bool 14 | """ 15 | stack_s = [] 16 | stack_t = [] 17 | for item in S: 18 | if item == "#": 19 | if stack_s: 20 | stack_s.pop() 21 | else: 22 | stack_s.append(item) 23 | for item in T: 24 | if item == "#": 25 | if stack_t: 26 | stack_t.pop() 27 | else: 28 | stack_t.append(item) 29 | return stack_s == stack_t 30 | -------------------------------------------------------------------------------- /LeetCode/2018-11-28-39-Combination-Sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-11-28 18:20:58 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-18 07:11:56 6 | 7 | 8 | from typing import List 9 | 10 | 11 | class Solution: 12 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 13 | res = [] 14 | candidates.sort() 15 | self.dfs(candidates, target, 0, [], res) 16 | return res 17 | 18 | def dfs(self, candidates, target, index, path, res): 19 | 20 | if target == 0: 21 | res.append(list(path)) 22 | 23 | for i in range(index, len(candidates)): 24 | if candidates[i] > target: 25 | return 26 | 27 | path.append(candidates[i]) 28 | self.dfs(candidates, target - candidates[i], i, path, res) 29 | path.pop() 30 | -------------------------------------------------------------------------------- /LeetCode/2018-11-30-40-Combination-Sum-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-11-30 18:26:44 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-11-30 22:57:55 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 12 | res = [] 13 | candidates.sort() 14 | self.__dfs(0, [], res, target, candidates) 15 | return res 16 | 17 | def __dfs(self, start, path, res, target, candidates): 18 | 19 | if target == 0: 20 | res.append(list(path)) 21 | return 22 | 23 | for i in range(start, len(candidates)): 24 | 25 | if i > start and candidates[i] == candidates[i - 1]: 26 | continue 27 | num = candidates[i] 28 | if num > target: 29 | return 30 | path.append(num) 31 | self.__dfs(i + 1, path, res, target - num, candidates) 32 | path.pop() 33 | -------------------------------------------------------------------------------- /LeetCode/2018-12-12-46-Permutations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-12 10:44:38 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-12 11:06:24 6 | 7 | 8 | class Solution: 9 | def permute(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: List[List[int]] 13 | """ 14 | # 如果只有一个值,直接返回 15 | if len(nums) == 1: 16 | return [nums] 17 | # 声明最终需要返回的答案 18 | res = [] 19 | # 遍历数组中的元素 20 | for i, num in enumerate(nums): 21 | # 去掉已经遍历的元素 22 | subnum = nums[:i]+nums[i+1:] 23 | # 把刚刚去掉的元素和剩下的元素所有可能的结果相加 24 | for subres in self.permute(subnum): 25 | res.append([num]+subres) 26 | return res 27 | -------------------------------------------------------------------------------- /LeetCode/2018-12-12-47-Permutations-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-12 11:05:40 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-12 12:12:24 6 | 7 | 8 | class Solution: 9 | def permuteUnique(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: List[List[int]] 13 | """ 14 | # 如果只有一个值,直接返回 15 | if len(nums) == 1: 16 | return [nums] 17 | # 声明最终需要返回的答案 18 | res = [] 19 | # 遍历数组中的元素 20 | for i, num in enumerate(nums): 21 | if i != 0 and num in nums[0:i]: 22 | continue 23 | # 去掉已经遍历的元素 24 | subnum = nums[:i]+nums[i+1:] 25 | # 把刚刚去掉的元素和剩下的元素所有可能的结果相加 26 | for subres in self.permuteUnique(subnum): 27 | res.append([num]+subres) 28 | return res 29 | 30 | if __name__ == "__main__": 31 | so = Solution() 32 | print(so.permuteUnique([3,3,0,3])) -------------------------------------------------------------------------------- /LeetCode/2018-12-13-49-Group-Anagrams.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-13 16:05:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-13 16:32:08 6 | 7 | 8 | class Solution: 9 | def groupAnagrams(self, strs): 10 | """ 11 | :type strs: List[str] 12 | :rtype: List[List[str]] 13 | """ 14 | res = [] 15 | strdict = {} 16 | for item in strs: 17 | key = ''.join(sorted(item)) 18 | if key in strdict.keys(): 19 | strdict[key].append(item) 20 | else: 21 | strdict[key] = [] 22 | strdict[key].append(item) 23 | for key in strdict: 24 | res.append(strdict[key]) 25 | return res 26 | 27 | if __name__ == "__main__": 28 | so = Solution() 29 | res = so.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) 30 | print(res) -------------------------------------------------------------------------------- /LeetCode/2018-12-13-50-Pow-x-n.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-13 17:19:45 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-13 19:05:32 6 | 7 | 8 | class Solution: 9 | def myPow(self, x, n): 10 | """ 11 | :type x: float 12 | :type n: int 13 | :rtype: float 14 | """ 15 | # 如果n等于0,则不论x为何值,返回1 16 | if n == 0: 17 | return 1 18 | # 如果n为负数,则转换为(1/x)^(-n)的形式 19 | if n < 0: 20 | x = 1/x 21 | n = -n 22 | # 初始化res为1 23 | res = 1 24 | while n > 1: 25 | # 如果n为奇数,res则需要乘以x一次 26 | if n % 2: 27 | res *= x 28 | # x自乘一次 29 | x *= x 30 | # n整除2 31 | n //= 2 32 | return res*x 33 | 34 | 35 | if __name__ == "__main__": 36 | so = Solution() 37 | res = so.myPow(2, 10) 38 | print(res) 39 | -------------------------------------------------------------------------------- /LeetCode/2018-12-14-53-Maximum-Subarray.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-14 22:29:33 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-14 22:36:14 6 | 7 | 8 | class Solution: 9 | def maxSubArray(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | sum_ = nums[0] 15 | tempsum_ = 0 16 | for item in nums: 17 | tempsum_ += item 18 | if tempsum_ > sum_: 19 | sum_ = tempsum_ 20 | if tempsum_ < 0: 21 | tempsum_ = 0 22 | return sum_ 23 | -------------------------------------------------------------------------------- /LeetCode/2018-12-15-55-Jump-Game.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-15 17:13:28 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-15 17:19:47 6 | 7 | 8 | class Solution: 9 | def canJump(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: bool 13 | """ 14 | # 记录最远位置 15 | maxindex = 0 16 | for i in range(len(nums)): 17 | # 如果能偶到达当前位置并且当前位置能够到达的最远位置大于maxindex 18 | if maxindex >= i and i+nums[i] > maxindex: 19 | # 更新maxindex 20 | maxindex = i+nums[i] 21 | # 一旦maxindex大于等于最大索引,我们返回False 22 | if maxindex >= len(nums)-1: 23 | return True 24 | # 如果到末尾maxinde都小于最大索引,返回False 25 | return False 26 | 27 | 28 | if __name__ == "__main__": 29 | so = Solution() 30 | res = so.canJump([3, 2, 1, 0, 4]) 31 | print(res) 32 | -------------------------------------------------------------------------------- /LeetCode/2018-12-16-58-Length-of-Last-Word.md: -------------------------------------------------------------------------------- 1 | # LeetCode 58. Length of Last Word 2 | 3 | ## Description 4 | 5 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 6 | 7 | If the last word does not exist, return 0. 8 | 9 | Note: A word is defined as a character sequence consists of non-space characters only. 10 | 11 | Example: 12 | 13 | Input: "Hello World" 14 | Output: 5 15 | 16 | ## 描述 17 | 18 | 给定字符串s由大写/小写字母和空格字符''组成,返回字符串中最后一个单词的长度。 19 | 20 | 如果最后一个单词不存在,则返回0。 21 | 22 | 注意:单词定义为字符序列仅由非空格字符组成。 23 | 24 | ### 思路 25 | 26 | * 这道题属于easy难度,真正的笔试出现的机率很小 27 | * 在python中,用空格分开每个单词,返回最后一个单词的长度 28 | 29 | ```python 30 | class Solution: 31 | def lengthOfLastWord(self, s): 32 | """ 33 | :type s: str 34 | :rtype: int 35 | """ 36 | try: 37 | split_words = s.split() 38 | return len(split_words[-1]) 39 | except: 40 | return 0 41 | ``` 42 | 43 | 源代码文件在[这里](https://github.com/ruicore/Algorithm/blob/master/Leetcode/2018-12-16-58-Length-of-Last-Word.py). 44 | ©本文是原创文章,欢迎转载,转载需保留[文章来源](https://www.ruicore.cn/),作者信息和本声明. -------------------------------------------------------------------------------- /LeetCode/2018-12-16-58-Length-of-Last-Word.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-16 16:59:53 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-16 17:09:53 6 | 7 | import re 8 | 9 | class Solution: 10 | def lengthOfLastWord(self, s): 11 | """ 12 | :type s: str 13 | :rtype: int 14 | """ 15 | try: 16 | split_words = s.split() 17 | return len(split_words[-1]) 18 | except: 19 | return 0 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/2018-12-17-60-Permutation-Sequence.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-17 10:15:58 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-17 11:00:08 6 | 7 | import math 8 | 9 | 10 | class Solution: 11 | def getPermutation(self, n, k): 12 | """ 13 | :type n: int 14 | :type k: int 15 | :rtype: str 16 | """ 17 | nums = [str(i) for i in range(1, n+1)] 18 | res = [] 19 | denominator, numerator = k, k 20 | while denominator: 21 | numerator = math.factorial(n-1) 22 | quotient = denominator//numerator 23 | remainder = denominator % numerator 24 | if remainder: 25 | res.append(nums[quotient]) 26 | del nums[quotient] 27 | else: 28 | res.append(nums[quotient-1]) 29 | del nums[quotient-1] 30 | denominator = remainder 31 | n -= 1 32 | return ''.join(res+nums[::-1]) 33 | 34 | 35 | if __name__ == "__main__": 36 | so = Solution() 37 | res = so.getPermutation(4, 5) 38 | print(res) 39 | -------------------------------------------------------------------------------- /LeetCode/2018-12-17-62-Unique-Paths.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-17 15:47:16 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-17 15:47:16 6 | 7 | 8 | class Solution: 9 | def __init__(self): 10 | self.res = [] 11 | 12 | def uniquePaths(self, m, n): 13 | """ 14 | :type m: int 15 | :type n: int 16 | :rtype: int 17 | """ 18 | if m == 0 or n == 0: 19 | return 0 20 | self.res = [[0 for _ in range(n)] for _ in range(m)] 21 | return self.recursion(m, n) 22 | 23 | def recursion(self, m, n): 24 | # 递归结束条件,当到达最左边的时候或者到达最上层的时候,结束递归 25 | if m == 1 or n == 1: 26 | return 1 27 | # 递归检查,检查当前位置是否已经遍历过,如果是则直接返回 28 | if self.res[m-1][n-1] > 0: 29 | return self.res[m-1][n-1] 30 | # 获得走到此位置左边的走法 31 | left = self.recursion(m, n-1) 32 | # 获得此位置右边的走法 33 | top = self.recursion(m-1, n) 34 | # 记录当前位置的走法 35 | self.res[m-1][n-1] = left+top 36 | # 返回 37 | return self.res[m-1][n-1] 38 | 39 | 40 | if __name__ == "__main__": 41 | so = Solution() 42 | res = so.uniquePaths(7, 3) 43 | print(res) 44 | -------------------------------------------------------------------------------- /LeetCode/2018-12-18-66-Plus-One.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-18 17:28:42 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-18 17:36:33 6 | 7 | 8 | class Solution: 9 | def plusOne(self, digits): 10 | """ 11 | :type digits: List[int] 12 | :rtype: List[int] 13 | """ 14 | # 结果数组 15 | res = [] 16 | # 数组最后一个元素的索引 17 | index = len(digits)-1 18 | # 获取最后一个元素的值 19 | last = digits[index] 20 | # 当需要进位的时候才进行循环 21 | while last+1 == 10: 22 | # 需要进位,在首位插入0 23 | res.insert(0, 0) 24 | # index指向数组的前一个元素 25 | index -= 1 26 | # 如果index越界,重新赋值为0,即重新指向首位置 27 | if index == -1: 28 | index += 1 29 | # 在输入数组的首位插入0占位 30 | digits.insert(0, 0) 31 | # last继续指向输入数组的末尾位置,此时index已经自减一次 32 | last = digits[index] 33 | digits[index] += 1 34 | # 将res和digits数组中的元素合并 35 | res = digits[:index+1]+res 36 | return res 37 | -------------------------------------------------------------------------------- /LeetCode/2018-12-19-69-Sqrt-x.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-19 13:30:16 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-19 13:56:03 6 | 7 | 8 | class Solution: 9 | def mySqrt(self, x): 10 | """ 11 | :type x: int 12 | :rtype: int 13 | """ 14 | # 如果输入是1,则直接返回1 15 | if x == 1: 16 | return 1 17 | # 左边界,右边界,中间值,注意位运算9>>1=4,为整型 18 | left, right, middle = 0, x, x >> 1 19 | while True: 20 | # 对中间的值求平方 21 | multi = middle*middle 22 | # 如果平方小于x,说明sqrt(x)在[middle,right]之间 23 | if multi < x: 24 | left = middle 25 | # 如果平方大于x,说明sqrt(x)在[left,middle]之间 26 | elif multi > x: 27 | right = middle 28 | # 求middle+1的平方 29 | intmultib = (middle+1)*(middle+1) 30 | # 如果x落在了[middle,middle+1)之间,结束循环,返回middle 31 | if multi <= x < intmultib: 32 | return middle 33 | middle = left+((right-left) >> 1) 34 | 35 | 36 | if __name__ == "__main__": 37 | so = Solution() 38 | res = so.mySqrt(190983754751) 39 | print(res) -------------------------------------------------------------------------------- /LeetCode/2018-12-19-70-Climbing-Stairs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-19 15:20:20 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-19 15:59:32 6 | 7 | 8 | class Solution: 9 | def climbStairs(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | # 如果只有一层,返回1 15 | if n == 1: 16 | return 1 17 | # 如果有两层,返回2 18 | if n == 2: 19 | return 2 20 | total, preone, pretwo = 0, 2, 1 21 | # 循环遍历,到达当前的层数的路径数 = 前一层的路径数+前两层的路径数 22 | for _ in range(3, n+1): 23 | total = preone + pretwo 24 | pretwo, preone = preone, total 25 | 26 | return total 27 | -------------------------------------------------------------------------------- /LeetCode/2018-12-19-71-Simplify-Path.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-19 16:29:44 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-19 16:43:47 6 | 7 | 8 | class Solution: 9 | def simplifyPath(self, path): 10 | """ 11 | :type path: str 12 | :rtype: str 13 | """ 14 | if not path: 15 | return None 16 | path = path.split("/") 17 | stack = [] 18 | for item in path: 19 | if not item or item == '.': 20 | continue 21 | elif item == "..": 22 | if stack: 23 | stack.pop() 24 | else: 25 | stack.append(item) 26 | return '/'+'/'.join(stack) 27 | 28 | if __name__ == "__main__": 29 | so = Solution() 30 | a = "/../" 31 | res = so.simplifyPath(a) 32 | print(res) -------------------------------------------------------------------------------- /LeetCode/2018-12-22-77-Combinations.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-22 10:15:22 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-22 11:26:53 6 | 7 | 8 | class Solution: 9 | def combine(self, n, k): 10 | """ 11 | :type n: int 12 | :type k: int 13 | :rtype: List[List[int]] 14 | """ 15 | res, nums = [], [i+1 for i in range(n)] 16 | self.recursion(res, [], nums, 0, n, k) 17 | return res 18 | 19 | def recursion(self, res, path, nums, start, end, depth): 20 | if depth == 1: 21 | for i in range(start, end): 22 | res.append(path+[nums[i]]) 23 | for i in range(start, end): 24 | self.recursion(res, path+[nums[i]], nums, i+1, end, depth-1) 25 | 26 | 27 | if __name__ == "__main__": 28 | so = Solution() 29 | res = so.combine(4, 2) 30 | print(res) 31 | -------------------------------------------------------------------------------- /LeetCode/2018-12-22-78-Subsets.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-22 11:41:12 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-22 12:08:29 6 | 7 | import copy 8 | 9 | 10 | class Solution: 11 | def subsets(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: List[List[int]] 15 | """ 16 | res = [[]] 17 | length = len(nums) 18 | self.recursion(res, nums, [], 0, length) 19 | return res 20 | 21 | def recursion(self, res, nums, path, start, end): 22 | if start == end: 23 | return 24 | for i in range(start, end): 25 | path.append(nums[i]) 26 | res.append(copy.deepcopy(path)) 27 | self.recursion(res, nums, path, i+1, end,) 28 | path.pop() 29 | 30 | 31 | if __name__ == "__main__": 32 | so = Solution() 33 | res = so.subsets([1, 2, 3]) 34 | print(res) 35 | -------------------------------------------------------------------------------- /LeetCode/2018-12-22-80-Remove-Duplicates-from-Sorted-Array-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-22 17:55:43 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-23 10:35:05 6 | 7 | 8 | class Solution: 9 | def removeDuplicates(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | # 如果是空则返回0 15 | if not nums: 16 | return 0 17 | index, count = 1, 1 18 | for i in range(1, len(nums)): 19 | # 如果两个字符相等 20 | if nums[i-1] == nums[i]: 21 | # count计数自增一次 22 | count += 1 23 | # 如果不等,count重置为1 24 | else: 25 | count = 1 26 | # 如果count小于等于2,则把nums[i]放到有效位置的后一个位置 27 | if count <= 2: 28 | nums[index] = nums[i] 29 | index += 1 30 | # 删除无用元素[也可不用删除,LeetCode不会检查后面的元素] 31 | del nums[index:] 32 | return index 33 | 34 | 35 | if __name__ == "__main__": 36 | nums = [0, 0, 1, 1, 1, 1, 2, 3, 3] 37 | so = Solution() 38 | res = so.removeDuplicates(nums) 39 | print(res, nums) 40 | -------------------------------------------------------------------------------- /LeetCode/2018-12-23-83-Remove-Duplicates-from-Sorted-List.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-23 21:18:30 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-23 21:19:39 6 | 7 | class Solution: 8 | def deleteDuplicates(self, head): 9 | if head == None or head.next == None: 10 | return head 11 | p = head 12 | while p.next: 13 | # 如果相等则删除 14 | if p.val == p.next.val: 15 | p.next = p.next.next 16 | else: 17 | # 否则p指向下一个元素 18 | p = p.next 19 | return head -------------------------------------------------------------------------------- /LeetCode/2018-12-25-88-Merge-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-25 17:10:16 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-25 17:10:16 6 | 7 | 8 | class Solution: 9 | def merge(self, nums1, m, nums2, n): 10 | """ 11 | :type nums1: List[int] 12 | :type m: int 13 | :type nums2: List[int] 14 | :type n: int 15 | :rtype: void Do not return anything, modify nums1 in-place instead. 16 | """ 17 | p, q = m-1, n-1 18 | while p >= 0 and q >= 0: 19 | if nums1[p] > nums2[q]: 20 | nums1[p+q+1] = nums1[p] 21 | p = p-1 22 | else: 23 | nums1[p+q+1] = nums2[q] 24 | q = q-1 25 | nums1[:q+1] = nums2[:q+1] 26 | 27 | 28 | if __name__ == "__main__": 29 | so = Solution() 30 | nums1 = [1, 2, 3, 0, 0, 0] 31 | nums2 = [2, 5, 6] 32 | so.merge(nums1, 3, nums2, 3) 33 | print(nums1) 34 | -------------------------------------------------------------------------------- /LeetCode/2018-12-25-89-Gray-Code.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-25 20:55:39 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-25 21:02:34 6 | 7 | class Solution: 8 | def grayCode(self, n): 9 | """ 10 | :type n: int 11 | :rtype: List[int] 12 | """ 13 | i = 0 14 | res = [] 15 | for i in range(2**n): 16 | # 17 | res.append(i^(i>>1)) 18 | return res 19 | 20 | if __name__ == "__main__": 21 | so = Solution() 22 | res = so.grayCode(2) 23 | print(res) -------------------------------------------------------------------------------- /LeetCode/2018-12-25-90-Subsets-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-25 21:24:06 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-25 21:41:42 6 | 7 | import copy 8 | 9 | 10 | class Solution: 11 | def subsetsWithDup(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: List[List[int]] 15 | """ 16 | res = [[]] 17 | nums = sorted(nums) 18 | self.recursion(res, [], nums, 0, len(nums)) 19 | return res 20 | 21 | def recursion(self, res, path, nums, start, end): 22 | if start == end: 23 | return 24 | for i in range(start, end): 25 | if i != start and nums[i] == nums[i-1]: 26 | continue 27 | else: 28 | path.append(nums[i]) 29 | res.append(copy.deepcopy(path)) 30 | self.recursion(res, path, nums, i+1, end) 31 | path.pop() 32 | 33 | 34 | if __name__ == "__main__": 35 | so = Solution() 36 | res = so.subsetsWithDup([1, 1, 6, 2]) 37 | print(res) 38 | -------------------------------------------------------------------------------- /LeetCode/2018-12-26-92-Reverse-Linked-List-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-26 11:44:18 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-26 13:36:47 6 | 7 | 8 | class ListNode(): 9 | def __init__(self, x): 10 | self.val = x 11 | self.next = None 12 | 13 | 14 | class Solution: 15 | def reverseBetween(self, head, m, n): 16 | """ 17 | :type head: ListNode 18 | :type m: int 19 | :type n: int 20 | :rtype: ListNode 21 | """ 22 | # 需要交换的次数 23 | move, reverse = m-1, n-m 24 | # pre初始化指向第一个被换节点的前一个节点,point初始化为第一个被换节点 25 | # 声明一个辅助头节点 26 | res = ListNode(0) 27 | pre, point = res, head 28 | pre.next = head 29 | # 把pre,point放到指定位置 30 | while move > 0: 31 | pre = pre.next 32 | point = point.next 33 | move -= 1 34 | # 需要交换的次数 35 | while reverse: 36 | temp = point.next 37 | point.next = temp.next 38 | temp.next = pre.next 39 | pre.next = temp 40 | reverse -= 1 41 | return res.next 42 | -------------------------------------------------------------------------------- /LeetCode/2018-12-26-94-Binary-Tree-Inorder-Traversal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-26 15:40:49 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-26 21:10:26 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def inorderTraversal(self, root): 19 | """ 20 | :type root: TreeNode 21 | :rtype: List[int] 22 | """ 23 | current, stack, res = root, [], [] 24 | if not root: 25 | return res 26 | while current or stack: 27 | # 遍历左边 28 | while current: 29 | stack.append(current) 30 | current = current.left 31 | # 取中间值 32 | current = stack.pop() 33 | res.append(current.val) 34 | # 遍历右边 35 | current = current.right 36 | return res 37 | 38 | 39 | if __name__ == "__main__": 40 | root = TreeNode(2) 41 | so = Solution() 42 | res = so.inorderTraversal(root) 43 | print(res) 44 | -------------------------------------------------------------------------------- /LeetCode/2018-12-27-96-Unique-Binary-Search-Trees.md: -------------------------------------------------------------------------------- 1 | # LeetCode 96. Unique Binary Search Trees 2 | 3 | ## Description 4 | 5 | Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 6 | 7 | Example: 8 | 9 | ```python 10 | Input: 3 11 | Output: 5 12 | Explanation: 13 | Given n = 3, there are a total of 5 unique BST's: 14 | 15 | 1 3 3 2 1 16 | \ / / / \ \ 17 | 3 2 1 1 3 2 18 | / / \ \ 19 | 2 1 2 3 20 | ``` 21 | 22 | ## 描述 23 | 24 | * 给定一个自然数n,返回从1到n可能构成的二叉搜索树的个数. 25 | * 此题目使用动态规划. 26 | 27 | ```python 28 | class Solution: 29 | def numTrees(self, n): 30 | """ 31 | :type n: int 32 | :rtype: int 33 | """ 34 | nums = [0 for _ in range(n+1)] 35 | nums[0] = 1 36 | nums[1] = 1 37 | for i in range(2, n+1): 38 | for j in range(i): 39 | # 递归关系式 40 | nums[i] += nums[i-j-1]*nums[j] 41 | return nums[n] 42 | ``` 43 | 44 | 源代码文件在[这里](https://github.com/ruicore/Algorithm/blob/master/Leetcode/2018-12-27-96-Unique-Binary-Search-Trees.py). 45 | ©本文首发于[何睿的博客](https://www.ruicore.cn/leetcode-96-unique-binary-search-trees/),欢迎转载,转载需保留文章来源,作者信息和本声明. 46 | -------------------------------------------------------------------------------- /LeetCode/2018-12-27-96-Unique-Binary-Search-Trees.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-27 17:11:58 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-27 17:51:07 6 | 7 | 8 | class Solution: 9 | def numTrees(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | nums = [0 for _ in range(n+1)] 15 | nums[0] = 1 16 | nums[1] = 1 17 | for i in range(2, n+1): 18 | for j in range(i): 19 | # 递归关系式 20 | nums[i] += nums[i-j-1]*nums[j] 21 | return nums[n] 22 | -------------------------------------------------------------------------------- /LeetCode/2018-12-28-100-Same-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-28 19:06:08 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-28 19:12:16 6 | 7 | class TreeNode: 8 | def __init__(self, x): 9 | self.val = x 10 | self.left = None 11 | self.right = None 12 | 13 | class Solution: 14 | def isSameTree(self, p, q): 15 | """ 16 | :type p: TreeNode 17 | :type q: TreeNode 18 | :rtype: bool 19 | """ 20 | # 如果第一个树和第二个树都是空,说明两个树是相等的,返回True. 21 | if not p and not q: 22 | return True 23 | # 如果有一个数为空另一个树不为空,说明两个树一定不会相等 24 | if not p or not q: 25 | return False 26 | # 如果两个树的节点值不相等,则两条树不会相等,返回False 27 | if p.val != q.val: 28 | return False 29 | # 如果以上条件都通过了,说明两个树的当前节点相等 30 | # 我们分别判断这两条树的左子树是否相等,右子树是否相等 31 | left = self.isSameTree(p.left,q.left) 32 | right = self.isSameTree(p.right,q.right) 33 | # 返回最终结果 34 | return left and right -------------------------------------------------------------------------------- /LeetCode/2018-12-28-98-Validate-Binary-Search-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-28 11:00:13 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-28 11:49:48 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def isValidBST(self, root): 19 | """ 20 | :type root: TreeNode 21 | :rtype: bool 22 | """ 23 | if not root: 24 | return True 25 | return self.recursion(root, '','') 26 | 27 | def recursion(self, root, maxvalue, minvalue): 28 | # 如果到达叶节点的子树,返回True 29 | if not root: 30 | return True 31 | if (maxvalue != '' and root.val >= maxvalue) or (minvalue != '' and root.val <= minvalue): 32 | return False 33 | # 判断root的左子树,左边的所有节点都必须小于根节点的值 34 | left = self.recursion(root.left, root.val, minvalue) 35 | # 判断root的右子树,右边的所有节点都必须大于根节点的值 36 | right = self.recursion(root.right, maxvalue, root.val) 37 | return left and right 38 | -------------------------------------------------------------------------------- /LeetCode/2018-12-29-101-Symmetric-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-29 09:30:27 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-29 09:42:54 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def isSymmetric(self, root): 19 | """ 20 | :type root: TreeNode 21 | :rtype: bool 22 | """ 23 | # 如果为空树,返回ture 24 | if not root: 25 | return True 26 | return self.recursion(root.left, root.right) 27 | 28 | def recursion(self, p, q): 29 | # 如果两个子树都为空,返回True 30 | if p == None and q == None: 31 | return True 32 | # 如果有一个子树为空,另一个子树不为空,返回False 33 | if (p == None and q != None) or (p != None and q == None): 34 | return False 35 | # 能够到达这里,说明两个子树都不为空,如果值不相等,返回False 36 | if p.val != q.val: 37 | return False 38 | # 判断当前子树p的左子树与子树q的右子树是否为镜像子树 39 | leftree = self.recursion(p.left, q.right) 40 | # 判断当前子树p的右子树与子树q的左子树是否为镜像子树 41 | rightree = self.recursion(p.right, q.left) 42 | return leftree and rightree 43 | -------------------------------------------------------------------------------- /LeetCode/2018-12-29-104-Maximum-Depth-of-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-29 19:41:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-29 19:53:07 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def maxDepth(self, root): 19 | """ 20 | :type root: TreeNode 21 | :rtype: int 22 | """ 23 | # 树的最大高度为max(左子树最大高度+1,右子树最大高度+1) 24 | if not root: 25 | return 0 26 | left = self.maxDepth(root.left) 27 | right = self.maxDepth(root.right) 28 | return max(left+1, right+1) 29 | -------------------------------------------------------------------------------- /LeetCode/2018-12-30-108-Convert-Sorted-Array-to-Binary-Search-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-30 13:18:09 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-30 13:30:43 6 | 7 | 8 | class TreeNode: 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | 15 | class Solution: 16 | def sortedArrayToBST(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: TreeNode 20 | """ 21 | if not nums: 22 | return None 23 | 24 | return self.recursion(0, len(nums)-1, nums) 25 | 26 | def recursion(self, left, right, nums): 27 | # 递归结束条件,当left大于right时,返回空节点 28 | if left > right: 29 | return None 30 | # 取中间值作为当前根节点 31 | middle = left+((right-left) >> 1) 32 | # 声明根节点 33 | root = TreeNode(nums[middle]) 34 | # 生成左子树 35 | leftree = self.recursion(left, middle-1, nums) 36 | # 生成右子树 37 | rightree = self.recursion(middle+1, right, nums) 38 | root.left = leftree 39 | root.right = rightree 40 | # 返回根节点 41 | return root 42 | -------------------------------------------------------------------------------- /LeetCode/2018-12-31-110-Balanced-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-31 08:29:38 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-31 09:04:14 6 | 7 | 8 | class TreeNode: 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | 15 | class Solution: 16 | def isBalanced(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: bool 20 | """ 21 | if not root: 22 | return True 23 | return False if self.height(root) == -1 else True 24 | 25 | def height(self, root): 26 | # 如果走到了空节点,返回0表示当前高度 27 | if not root: 28 | return 0 29 | # 左子树高度 30 | left = self.height(root.left) 31 | # 右子树高度 32 | right = self.height(root.right) 33 | # 如果左右子树的高度超过了1,说明以当前root为根节点的树不是平衡二叉树 34 | # 说明当前这整棵树就不是平衡二叉树 35 | if abs(left-right) > 1: 36 | return -1 37 | # 只要有一棵树不是平衡二叉树,则一直返回-1,当前的树就不是平衡二叉树 38 | if left == -1 or right == -1: 39 | return -1 40 | return max(left, right)+1 41 | -------------------------------------------------------------------------------- /LeetCode/2018-12-31-111-Minimum-Depth-of-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-31 09:24:34 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-31 09:24:34 6 | 7 | 8 | class TreeNode: 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | 15 | class Solution: 16 | def minDepth(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: int 20 | """ 21 | if not root: 22 | return 0 23 | return self.height(root) 24 | 25 | def height(self, root): 26 | # 到达空节点,返回0 27 | if not root: 28 | return 0 29 | # 当前节点左边的高度 30 | left = self.height(root.left) 31 | # 当前节点右边的高度 32 | right = self.height(root.right) 33 | # 如果root没有左子树,返回右子树的高度 34 | if not root.left: 35 | return right+1 36 | # 如果没有右子树,返回左子树的高度 37 | if not root.right: 38 | return left+1 39 | else: 40 | # 返回高度中的最小值 41 | return min(left, right)+1 42 | -------------------------------------------------------------------------------- /LeetCode/2018-12-31-113.-Path-Sum-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-31 11:00:05 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-31 11:12:15 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def pathSum(self, root, sum): 19 | """ 20 | :type root: TreeNode 21 | :type sum: int 22 | :rtype: List[List[int]] 23 | """ 24 | if not root: 25 | return [] 26 | res = [] 27 | self.recursion(root, [], res, sum) 28 | return res 29 | 30 | def recursion(self, root, path, res, target): 31 | # 如果为空,则直接返回 32 | if not root: 33 | return 34 | # 到达叶节点,进行判断 35 | if not root.left and not root.right: 36 | path.append(root.val) 37 | if sum(path) == target: 38 | res.append(path) 39 | return 40 | # 检查左子树 41 | self.recursion(root.left, path+[root.val], res, target) 42 | # 检查右子树 43 | self.recursion(root.right, path+[root.val], res, target) 44 | -------------------------------------------------------------------------------- /LeetCode/2018-12-31-114-Flatten-Binary-Tree-to-Linked-List.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2018-12-31 11:24:07 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2018-12-31 11:48:55 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def flatten(self, root): 19 | """ 20 | :type root: TreeNode 21 | :rtype: void Do not return anything, modify root in-place instead. 22 | """ 23 | if not root: 24 | return 25 | # 对左边进行转换 26 | self.flatten(root.left) 27 | # 对右边进行转换 28 | self.flatten(root.right) 29 | # 如果此时左边已经没有节点,直接返回 30 | if not root.left: 31 | return 32 | else: 33 | # 首先找到左子树的最右边的节点 34 | node = root.left 35 | while node.right: 36 | node = node.right 37 | # 将跟节点右子树放到左子树的最右节点 38 | node.right = root.right 39 | # 将根节点的左子树放到根节点的右子树 40 | root.right = root.left 41 | # 将根节点的左子树置为空 42 | root.left = None 43 | -------------------------------------------------------------------------------- /LeetCode/2019-01-01-118.-Pascals-Triangle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-01 12:11:35 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-01 12:21:44 6 | 7 | 8 | class Solution: 9 | def generate(self, numRows): 10 | """ 11 | :type numRows: int 12 | :rtype: List[List[int]] 13 | """ 14 | # 如果行数等于0,则返回空 15 | if numRows == 0: 16 | return [] 17 | # 如果行数为1,则最终结果只有一行 18 | elif numRows == 1: 19 | return [[1]] 20 | res = [[1], [1, 1]] 21 | # 生成一行的数 22 | for i in range(2, numRows): 23 | res.append([1 for _ in range(i+1)]) 24 | # 当前位置的值等于上一行当前位置的值+上一行当前位置前一个位置的值 25 | for j in range(1, i): 26 | res[i][j] = res[i-1][j-1]+res[i-1][j] 27 | return res 28 | -------------------------------------------------------------------------------- /LeetCode/2019-01-01-119-Pascals-Triangle-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-01 12:35:48 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-01 12:50:51 6 | 7 | 8 | class Solution: 9 | def getRow(self, rowIndex): 10 | """ 11 | :type rowIndex: int 12 | :rtype: List[int] 13 | """ 14 | if rowIndex == 0: 15 | return [1] 16 | # pre用来存储上一行的信息 17 | pre = [1, 1] 18 | if rowIndex == 1: 19 | return pre 20 | for i in range(2, rowIndex+1): 21 | res = [1 for _ in range(i+1)] 22 | for j in range(1, i): 23 | res[j] = pre[j]+pre[j-1] 24 | pre = res 25 | return res 26 | -------------------------------------------------------------------------------- /LeetCode/2019-01-01-120-Triangle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-01 13:01:16 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-01 14:03:49 6 | 7 | import sys 8 | 9 | 10 | class Solution: 11 | def minimumTotal(self, triangle): 12 | """ 13 | :type triangle: List[List[int]] 14 | :rtype: int 15 | """ 16 | rows = len(triangle) 17 | for i in range(1, rows): 18 | col = len(triangle[i]) 19 | for j in range(col): 20 | # 如果没有越界 21 | if j-1 >= 0: 22 | one = triangle[i-1][j-1] 23 | # 如果越界则置为最大值 24 | else: 25 | one = sys.maxsize 26 | # 如果没有越界 27 | if j < i: 28 | two = triangle[i-1][j] 29 | # 如果越界则置为最大值 30 | else: 31 | two = sys.maxsize 32 | # 当前位置只能来源于当前位置对应的上一层的左右两个位置,取其最小值于当前位置的值相加,就是走到当前位置的最小路径和 33 | triangle[i][j] = triangle[i][j]+min(one, two) 34 | return min(triangle[rows-1]) 35 | 36 | 37 | if __name__ == "__main__": 38 | so = Solution() 39 | res = so.minimumTotal([[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]) 40 | print(res) 41 | -------------------------------------------------------------------------------- /LeetCode/2019-01-03-124-Binary-Tree-Maximum-Path-Sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-03 09:17:34 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-03 11:02:07 6 | 7 | import sys 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def __init__(self): 19 | self.res = -sys.maxsize 20 | 21 | def maxPathSum(self, root): 22 | """ 23 | :type root: TreeNode 24 | :rtype: int 25 | """ 26 | self.recursion(root) 27 | return self.res 28 | 29 | def recursion(self, root): 30 | # 当走到空节点的时候返回最小值 31 | if not root: 32 | return -sys.maxsize 33 | # 求左子树的最大序列,且仅使用一个孩子节点(最后一层即叶节点) 34 | left = max(0, self.recursion(root.left)) 35 | # 求右子树的最大序列,且仅使用一个孩子节点(最后一层即也节点) 36 | right = max(0, self.recursion(root.right)) 37 | # 最终结果是可以取本节点的,于是我们取其中的最大值 38 | self.res = max(self.res, root.val+left+right) 39 | # 返回的结果只能取其中一个子树,于是我么取最大值 40 | return root.val + max(left, right) 41 | -------------------------------------------------------------------------------- /LeetCode/2019-01-03-125-Valid-Palindrome.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-03 11:16:37 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-03 11:34:21 6 | 7 | 8 | class Solution: 9 | def isPalindrome(self, s): 10 | """ 11 | :type s: str 12 | :rtype: bool 13 | """ 14 | if not s: 15 | return True 16 | left, right = 0, len(s)-1 17 | while left < right: 18 | # 如果当前字符是数字或者字母 19 | if (s[left].isalpha() or s[left].isdigit()) and (s[right].isalpha() or s[right].isdigit()): 20 | # 如果相等则left向后走一步,right向前走一步 21 | if s[left].lower() == s[right].lower(): 22 | left += 1 23 | right -= 1 24 | else: 25 | # 否则返回False 26 | return False 27 | # 如果左边不是数字或者字符,则认为是满足回文符串的条件 28 | elif not (s[left].isalpha() or s[left].isdigit()): 29 | left += 1 30 | # 如果右边不是数字或者字符,则认为是满足回文字符串的条件 31 | elif not (s[right].isalpha() or s[right].isdigit()): 32 | right -= 1 33 | return True 34 | 35 | 36 | if __name__ == "__main__": 37 | so = Solution() 38 | res = so.isPalindrome("0P") 39 | -------------------------------------------------------------------------------- /LeetCode/2019-01-03-127-Word-Ladder.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-03 14:54:52 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-04 14:56:19 6 | 7 | 8 | class Solution: 9 | 10 | def ladderLength(self, beginWord, endWord, wordList): 11 | """ 12 | :type beginWord: str 13 | :type endWord: str 14 | :type wordList: List[str] 15 | :rtype: int 16 | """ 17 | wordset = set(wordList) 18 | if endWord not in wordset: 19 | return 0 20 | res = 1 21 | left, right = set(), set() 22 | left.add(beginWord) 23 | right.add(endWord) 24 | while left or right: 25 | newset = set() 26 | left, right = right, left 27 | for word in left: 28 | for i in range(len(word)): 29 | for j in range(0, 26): 30 | newword = word[0:i]+chr(j+97)+word[i+1:] 31 | if newword in wordset: 32 | newset.add(newword) 33 | wordset.remove(newword) 34 | if newword in right: 35 | return res+1 36 | res += 1 37 | left = newset 38 | return 0 39 | -------------------------------------------------------------------------------- /LeetCode/2019-01-05-128-Longest-Consecutive-Sequence.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-05 16:22:43 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-05 17:14:04 6 | 7 | from pprint import pprint 8 | 9 | 10 | class Solution: 11 | def longestConsecutive(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: int 15 | """ 16 | # 哈希表,结果 17 | mydict, res, = {}, 0 18 | # 遍历所有数字 19 | for item in nums: 20 | # 重复的数字不算 21 | if item in mydict: 22 | continue 23 | # 获取当前数字左边一个数字构成的最大连续串,若不存在则返回0 24 | leftborder = mydict.get(item-1, 0) 25 | # 获取当前数字右边一个数字构成的最大连续串,如不存在则返回0 26 | rightborder = mydict.get(item+1, 0) 27 | # 连续串的长度更新为左右最大连续串加一 28 | length = leftborder+rightborder+1 29 | mydict[item] = length 30 | res = max(res, length) 31 | # 更新左边界 32 | mydict[item-leftborder] = length 33 | # 更新右边界 34 | mydict[item+rightborder] = length 35 | return res 36 | 37 | 38 | if __name__ == "__main__": 39 | so = Solution() 40 | res = so.longestConsecutive([1, 2, 0, 1]) 41 | print(res) 42 | -------------------------------------------------------------------------------- /LeetCode/2019-01-05-129-Sum-Root-to-Leaf-Numbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-05 18:04:40 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-05 20:36:32 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def __init__(self): 19 | self.res = 0 20 | def sumNumbers(self, root): 21 | """ 22 | :type root: TreeNode 23 | :rtype: int 24 | """ 25 | if not root: 26 | return self.res 27 | self.dfs( [], root) 28 | return self.res 29 | 30 | def dfs(self, path, root): 31 | # 到达叶子节点 32 | if not root.left and not root.right: 33 | path.append(str(root.val)) 34 | self.res += int(''.join(path)) 35 | return 36 | # 左子树 37 | if root.left: 38 | self.dfs( path+[str(root.val)], root.left) 39 | # 右子树 40 | if root.right: 41 | self.dfs( path+[str(root.val)], root.right) -------------------------------------------------------------------------------- /LeetCode/2019-01-06-131-Palindrome-Partitioning.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-06 17:49:23 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-06 21:41:22 6 | 7 | 8 | class Solution: 9 | def partition(self, s): 10 | """ 11 | :type s: str 12 | :rtype: List[List[str]] 13 | """ 14 | res = [] 15 | self.dfs(res, [], s) 16 | return res 17 | 18 | def dfs(self, res, path, s): 19 | if not s: 20 | res.append(path) 21 | return 22 | for i in range(1, len(s)+1): 23 | sub = s[0:i] 24 | if sub == sub[::-1]: 25 | self.dfs(res, path+[sub], s[i:]) 26 | -------------------------------------------------------------------------------- /LeetCode/2019-01-08-135-Candy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-08 09:48:07 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-09 16:37:40 6 | 7 | 8 | class Solution: 9 | def candy(self, ratings): 10 | """ 11 | :type ratings: List[int] 12 | :rtype: int 13 | """ 14 | children = len(ratings) 15 | # 首先给每一个孩子分一颗糖果 16 | res = [1 for _ in range(children)] 17 | # 然后正向遍历,如果当前孩子的评分大于前面一个孩子的评分,则把前一个孩子分的糖果数目加一分给当前孩子 18 | # 这样就满足了每个分高的孩子的糖果大于前一个孩子的糖果 19 | for i in range(1, children): 20 | if ratings[i] > ratings[i-1]: 21 | res[i] = res[i-1]+1 22 | # 然后反向遍历,如果当前孩子评分比后面一个孩子高,并且档当前孩子已经分得的糖不多有后面一个孩子 23 | # 我们给当前孩子分其后面一个孩子糖果加一个数的糖 24 | for i in range(children-2, -1, -1): 25 | if ratings[i] > ratings[i+1] and res[i] <= res[i+1]: 26 | res[i] = res[i+1]+1 27 | # 最后我们返回其总和即可 28 | return sum(res) 29 | -------------------------------------------------------------------------------- /LeetCode/2019-01-08-136-Single-Number.md: -------------------------------------------------------------------------------- 1 | # LeetCode 136. Single Number 2 | 3 | ## Description 4 | 5 | Given a non-empty array of integers, every element appears twice except for one. Find that single one. 6 | 7 | Note: 8 | 9 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 10 | 11 | Example 1: 12 | 13 | Input: [2,2,1] 14 | Output: 1 15 | Example 2: 16 | 17 | Input: [4,1,2,1,2] 18 | Output: 4 19 | 20 | ## 描述 21 | 22 | ### 思路 23 | 24 | * [异或运算](https://zh.wikipedia.org/zh-hans/%E9%80%BB%E8%BE%91%E5%BC%82%E6%88%96). 25 | * 0或1和0做异或仍然保持不变,和1做异或变为1,我么初始化为res = 0,更新res ^=i ,如果i出现了偶数次异或会的到res = 0,奇数次会得到该数本身. 26 | 27 | ```python 28 | # -*- coding: utf-8 -*- 29 | # @Author: 何睿 30 | # @Create Date: 2019-01-08 09:48:14 31 | # @Last Modified by: 何睿 32 | # @Last Modified time: 2019-01-08 10:18:15 33 | 34 | class Solution: 35 | def singleNumber(self, nums): 36 | """ 37 | :type nums: List[int] 38 | :rtype: int 39 | """ 40 | res =0 41 | for num in nums: 42 | res ^=num 43 | return res 44 | ``` 45 | 46 | 源代码文件在[这里](https://github.com/ruicore/Algorithm/blob/master/Leetcode/2019-01-08-136-Single-Number.py). 47 | ©本文首发于[何睿的博客](https://www.ruicore.cn/leetcode-136-single-number/),欢迎转载,转载需保留文章来源,作者信息和本声明. 48 | -------------------------------------------------------------------------------- /LeetCode/2019-01-08-136-Single-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-08 09:48:14 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-08 10:18:15 6 | 7 | class Solution: 8 | def singleNumber(self, nums): 9 | """ 10 | :type nums: List[int] 11 | :rtype: int 12 | """ 13 | res =0 14 | for num in nums: 15 | res ^=num 16 | return res 17 | 18 | -------------------------------------------------------------------------------- /LeetCode/2019-01-09-137-Single-Number-II.md: -------------------------------------------------------------------------------- 1 | # LeetCode 137. Single Number II 2 | 3 | ## Description 4 | 5 | Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 6 | 7 | Note: 8 | 9 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 10 | 11 | Example 1: 12 | 13 | Input: [2,2,3,2] 14 | Output: 3 15 | Example 2: 16 | 17 | Input: [0,1,0,1,0,1,99] 18 | Output: 99 19 | 20 | ```python 21 | # -*- coding: utf-8 -*- 22 | # @Author: 何睿 23 | # @Create Date: 2019-01-09 22:05:23 24 | # @Last Modified by: 何睿 25 | # @Last Modified time: 2019-01-09 22:21:57 26 | 27 | 28 | class Solution: 29 | def singleNumber(self, nums): 30 | """ 31 | :type nums: List[int] 32 | :rtype: int 33 | """ 34 | one, two = 0, 0 35 | for num in nums: 36 | one = (one ^ num) & ~two 37 | two = (two ^ num) & ~one 38 | return one 39 | ``` 40 | 41 | 源代码文件在[这里](https://github.com/ruicore/Algorithm/blob/master/Leetcode/2019-01-09-137-Single-Number-II.py). 42 | ©本文首发于[何睿的博客](https://www.ruicore.cn/leetcode-137-single-number-ii/),欢迎转载,转载需保留文章来源,作者信息和本声明. 43 | -------------------------------------------------------------------------------- /LeetCode/2019-01-09-137-Single-Number-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-09 22:05:23 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-09 22:21:57 6 | 7 | 8 | class Solution: 9 | def singleNumber(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | one, two = 0, 0 15 | for num in nums: 16 | one = (one ^ num) & ~two 17 | two = (two ^ num) & ~one 18 | return one 19 | -------------------------------------------------------------------------------- /LeetCode/2019-01-10-139-Word-Break.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-10 10:34:57 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-10 11:27:44 6 | 7 | 8 | class Solution(object): 9 | def wordBreak(self, s, wordDict): 10 | """ 11 | :type s: str 12 | :type wordDict: List[str] 13 | :rtype: bool 14 | """ 15 | # 使用set,在set查找时间复杂度为O(1) 16 | wordset, nums = set(wordDict), len(s) 17 | # line[i]表示s[0:i]是否可以被差分 18 | line = [False for _ in range(nums+1)] 19 | line[0] = True 20 | for i in range(1, nums+1): 21 | for j in range(0, i): 22 | if line[j] and s[j:i] in wordset: 23 | line[i] = True 24 | break 25 | # 返回最后一个值 26 | return line[nums] 27 | -------------------------------------------------------------------------------- /LeetCode/2019-01-10-140-Word-Break-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-10 11:42:06 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-10 14:52:53 6 | 7 | 8 | class Solution(object): 9 | def wordBreak(self, s, wordDict): 10 | """ 11 | :type s: str 12 | :type wordDict: List[str] 13 | :rtype: List[str] 14 | """ 15 | wordset, ans = set(wordDict), {} 16 | return self.recursion(ans, s, wordset) 17 | 18 | def recursion(self, ans, s, wordset): 19 | if not s: 20 | return None 21 | if s in ans: 22 | return ans.get(s) 23 | res = [] 24 | for i in range(1, len(s)+1): 25 | if s[:i] in wordset: 26 | # 从当前位置的下面一层的所有组合 27 | combs = self.recursion(ans, s[i:], wordset) 28 | # 如果下面的一层有结果 29 | if combs: 30 | # 将当前的字符串与后面的所有字符组合进行组合 31 | for item in combs: 32 | res.append(s[:i]+" "+item) 33 | elif i == len(s): 34 | res.append(s[:i]) 35 | ans[s] = res 36 | return res 37 | -------------------------------------------------------------------------------- /LeetCode/2019-01-10-141-Linked-List-Cycle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-10 18:12:23 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-10 18:16:58 6 | 7 | 8 | class Solution(object): 9 | def hasCycle(self, head): 10 | """ 11 | :type head: ListNode 12 | :rtype 13 | """ 14 | # 如果没有节点或者只有一个节点,返回False 15 | if head == None or head.next == None: 16 | return False 17 | # 声明两个指针,slow指针每次走一步,fast指针每次走两步 18 | slow, fast = head, head.next 19 | while slow != fast: 20 | # 如果走到了末尾,返回False 21 | if fast == None or fast.next == None: 22 | return False 23 | # slow向后走一步 24 | slow = slow.next 25 | # fast向后走两步 26 | fast = fast.next.next 27 | 28 | return True 29 | -------------------------------------------------------------------------------- /LeetCode/2019-01-12-144-Binary-Tree-Preorder-Traversal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-12 18:59:10 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-12 19:18:42 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | class Solution: 17 | def preorderTraversal(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: List[int] 21 | """ 22 | # 如果为空则返回一个空的数组 23 | if not root: 24 | return 25 | stack, res = [root], [] 26 | while stack: 27 | # 先取根节点 28 | top = stack.pop() 29 | res.append(top.val) 30 | # 根据栈后进先出的特点,先将right指针压入栈,则right值后出来 31 | if top.right: 32 | stack.append(top.right) 33 | # 后入栈则先出 34 | if top.left: 35 | stack.append(top.left) 36 | return res -------------------------------------------------------------------------------- /LeetCode/2019-01-12-145-Binary-Tree-Postorder-Traversal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-12 19:30:10 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-12 19:42:54 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | class Solution: 17 | def postorderTraversal(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: List[int] 21 | """ 22 | if not root: 23 | return [] 24 | last, res, stack = root, [], [root] 25 | while stack: 26 | # top 指向栈顶元素 27 | top = stack[-1] 28 | # 栈顶元素弹出的条件是其左右子树同时为空或者其左右子树已经遍历过了 29 | if (not top.left and not top.right) or (last == top.right or last == top.left): 30 | top = stack.pop() 31 | res.append(top.val) 32 | last = top 33 | else: 34 | # 根据栈的特性,先进的元素后出 35 | if top.right: 36 | stack.append(top.right) 37 | # 后进的元素先出 38 | if top.left: 39 | stack.append(top.left) 40 | return res 41 | -------------------------------------------------------------------------------- /LeetCode/2019-01-14-150-Evaluate-Reverse-Polish-Notation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-14 17:15:18 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-14 17:50:02 6 | 7 | 8 | class Solution: 9 | def evalRPN(self, tokens): 10 | """ 11 | :type tokens: List[str] 12 | :rtype: int 13 | """ 14 | stack1, stack2 = [], [] 15 | for i in range(len(tokens) - 1, -1, -1): 16 | stack1.append(tokens[i]) 17 | operateset = set(["+", "-", "*", "/"]) 18 | while stack1: 19 | top = stack1.pop() 20 | if top in operateset: 21 | num1, num2 = stack2.pop(), stack2.pop() 22 | stack2.append(self.operate(top, num1, num2)) 23 | else: 24 | stack2.append(int(top)) 25 | return stack2[-1] 26 | 27 | def operate(self, op, num1, num2): 28 | if op == "+": 29 | return num2 + num1 30 | if op == "-": 31 | return num2 - num1 32 | if op == "*": 33 | return num2 * num1 34 | if op == "/": 35 | return int(num2 / num1) if num1 != 0 else 0 36 | -------------------------------------------------------------------------------- /LeetCode/2019-01-15-151-Reverse-Words-in-a-String.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-15 09:50:21 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-15 10:01:15 6 | 7 | 8 | class Solution(object): 9 | def reverseWords(self, s): 10 | """ 11 | :type s: str 12 | :rtype: str 13 | """ 14 | relist = s.split(" ") 15 | if not relist: 16 | return '' 17 | res = '' 18 | for i in range(len(relist) - 1, -1, -1): 19 | if relist[i]: 20 | res += relist[i] + " " 21 | return res[:-1] 22 | -------------------------------------------------------------------------------- /LeetCode/2019-01-15-153-Find-Minimum-in-Rotated-Sorted-Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-15 13:52:03 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-15 16:00:40 6 | 7 | 8 | class Solution: 9 | def findMin(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | # 如果为空,则直接返回 15 | if not nums: 16 | return 0 17 | # left为最左边的索引,right为最右边的索引 18 | left, right = 0, len(nums) - 1 19 | # 首先获取中间值 20 | middle = left + ((right - left) >> 1) 21 | # 如果是连续递增的请情况,返回数组的第一个值 22 | if nums[0] <= nums[middle] <= nums[-1]: 23 | return nums[0] 24 | # 如果是连续递减的情况,返回最后一个值 25 | if nums[-1] <= nums[middle] <= nums[0]: 26 | return nums[-1] 27 | while left < right: 28 | middle = left + ((right - left) >> 1) 29 | # 结束条件,交换的位置满足下面的条件 30 | if nums[middle] < nums[middle + 1] < nums[middle - 1]: 31 | return nums[middle] 32 | if nums[middle] > nums[0]: 33 | left = middle + 1 34 | # 注意这里不是middle-1,因为有可能middle就是要求的枢纽位置 35 | if nums[middle] < nums[-1]: 36 | right = middle 37 | return nums[left] 38 | -------------------------------------------------------------------------------- /LeetCode/2019-01-15-155-Min-Stack.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-15 16:40:08 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-15 17:49:45 6 | 7 | class MinStack(object): 8 | # 栈中存储的是元组(当前位置的值,当前位置到栈底所有值的最小值) 9 | def __init__(self): 10 | """ 11 | initialize your data structure here. 12 | """ 13 | self.stack = [] 14 | 15 | def push(self, x): 16 | """ 17 | :type x: int 18 | :rtype: void 19 | """ 20 | # 获取最小值 21 | curmin = self.getMin() 22 | if curmin == None or curmin > x: 23 | curmin = x 24 | # 存入元组 25 | self.stack.append((x, curmin)) 26 | 27 | def pop(self): 28 | """ 29 | :rtype: void 30 | """ 31 | self.stack.pop() 32 | 33 | def top(self): 34 | """ 35 | :rtype: int 36 | """ 37 | 38 | if len(self.stack) == 0: 39 | return None 40 | else: 41 | return self.stack[len(self.stack)-1][0] 42 | 43 | def getMin(self): 44 | """ 45 | :rtype: int 46 | """ 47 | if len(self.stack) == 0: 48 | return None 49 | else: 50 | return self.stack[len(self.stack)-1][1] 51 | -------------------------------------------------------------------------------- /LeetCode/2019-01-16-162-Find-Peak-Element.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-16 10:40:41 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-16 11:21:29 6 | 7 | 8 | class Solution(object): 9 | def findPeakElement(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | count = len(nums) 15 | middle, left, right = 0, 0, count - 1 16 | while left <= right: 17 | # 取中间值 18 | middle = left + ((right - left) >> 1) 19 | # 如果当前是递增的序列,说明较大值在右边(不包括当前节点) 20 | if middle < count - 1 and nums[middle] < nums[middle + 1]: 21 | left = middle + 1 22 | # 如果当前是递减的徐磊,说明较大值在左边(包括当前节点) 23 | if middle < count - 1 and nums[middle] > nums[middle + 1]: 24 | right = middle 25 | # 结束条件:到达了边界或者当前值比左右两个值大 26 | if (middle==0 or nums[middle] > nums[middle - 1]) and (middle == count-1 or nums[middle] > nums[middle + 1]): 27 | return middle 28 | return middle 29 | -------------------------------------------------------------------------------- /LeetCode/2019-01-16-165-Compare-Version-Numbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-16 14:36:33 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-16 14:57:42 6 | 7 | 8 | class Solution: 9 | def compareVersion(self, version1, version2): 10 | """ 11 | :type version1: str 12 | :type version2: str 13 | :rtype: int 14 | """ 15 | list1, list2 = version1.split('.'), version2.split(".") 16 | count1, count2 = len(list1), len(list2) 17 | short = count1 if count1 < count2 else count2 18 | for i in range(short): 19 | if int(list1[i]) > int(list2[i]): 20 | return 1 21 | if int(list1[i]) < int(list2[i]): 22 | return -1 23 | if count1 > count2: 24 | i = count2 25 | while i < count1: 26 | if int(list1[i]) > 0: 27 | return 1 28 | i+=1 29 | elif count1 < count2: 30 | i = count1 31 | while i < count2: 32 | if int(list2[i]) > 0: 33 | return -1 34 | i+=1 35 | return 0 36 | -------------------------------------------------------------------------------- /LeetCode/2019-01-16-166-Fraction-to-Recurring-Decimal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-16 14:57:31 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-16 15:16:35 6 | 7 | 8 | class Solution: 9 | def fractionToDecimal(self, numerator, denominator): 10 | if numerator == 0: 11 | return '0' 12 | # 确定是不是负数 13 | isnegative = True if numerator * denominator < 0 else False 14 | # 返回商和余数 15 | quotient, remainder = divmod(abs(numerator), abs(denominator)) 16 | # 生成点号左边的部分 17 | s = str(quotient) 18 | if isnegative: s = "-" + s 19 | if remainder: s += '.' 20 | # start用于记录循环开始的位置 21 | start = len(s) 22 | nums = {remainder: start} 23 | while remainder: 24 | # 对剩下的数字进行计算 25 | quotient, remainder = divmod(remainder * 10, abs(denominator)) 26 | # 添加到已经生成的结果中 27 | s += str(quotient) 28 | # 如果当前的余数已经出现过了 29 | if remainder in nums: 30 | s = s[:nums[remainder]] + '(' + s[nums[remainder]:] + ')' 31 | return s 32 | start += 1 33 | nums[remainder] = start 34 | return s -------------------------------------------------------------------------------- /LeetCode/2019-01-16-167-Two-Sum-II-Input-array-is-sorted.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-16 15:49:20 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-16 15:53:13 6 | 7 | 8 | class Solution: 9 | def twoSum(self, numbers, target): 10 | """ 11 | :type numbers: List[int] 12 | :type target: int 13 | :rtype: List[int] 14 | """ 15 | left, right = 0, len(numbers) - 1 16 | while left < right: 17 | _sum = numbers[left] + numbers[right] 18 | if _sum > target: 19 | right -= 1 20 | elif _sum < target: 21 | left += 1 22 | else: 23 | return [left + 1, right + 1] 24 | -------------------------------------------------------------------------------- /LeetCode/2019-01-16-168-Excel-Sheet-Column-Title.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-16 18:54:24 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-16 19:00:18 6 | 7 | 8 | class Solution: 9 | def convertToTitle(self, n): 10 | """ 11 | :type n: int 12 | :rtype: str 13 | """ 14 | # 此题目相当于进制转换 15 | s = [] 16 | while n > 0: 17 | # 索引转换 18 | n -= 1 19 | s.append(chr(65 + int(n % 26))) 20 | n = n // 26 21 | return ''.join(reversed(s)) 22 | -------------------------------------------------------------------------------- /LeetCode/2019-01-16-169-Majority-Element.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-16 20:27:19 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-16 20:47:38 6 | 7 | 8 | class Solution: 9 | def majorityElement(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | # 中间值一定会是超过一半的值 15 | return sorted(nums)[len(nums) // 2] 16 | 17 | def majorityElement2(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | # 超过了一半的值会使得count大于0 23 | majority, count = nums[0], 1 24 | for item in nums: 25 | if item == majority: 26 | count += 1 27 | else: 28 | count -= 1 29 | if count == 0: 30 | majority = item 31 | count = 1 32 | return majority 33 | -------------------------------------------------------------------------------- /LeetCode/2019-01-16-171-Excel-Sheet-Column-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-16 21:43:13 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-16 21:50:21 6 | 7 | 8 | class Solution: 9 | def titleToNumber(self, s): 10 | """ 11 | :type s: str 12 | :rtype: int 13 | """ 14 | base, res, count = 1, 0, len(s) 15 | for i in range(count): 16 | res += base * (ord(s[count - i - 1]) - 64) 17 | base *= 26 18 | return res 19 | -------------------------------------------------------------------------------- /LeetCode/2019-01-17-172-Factorial-Trailing-Zeroes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-17 09:47:59 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-17 09:51:51 6 | 7 | 8 | class Solution: 9 | def trailingZeroes(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | res = 0 15 | while n > 0: 16 | res += n // 5 17 | n //= 5 18 | return res 19 | -------------------------------------------------------------------------------- /LeetCode/2019-01-17-173-Binary-Search-Tree-Iterator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-17 10:00:34 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-17 10:38:45 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | # 二叉树的中序遍历 17 | # 我们一路将二叉树的左节点压入栈,当弹出栈的时候,我们压入右节点 18 | class BSTIterator: 19 | def __init__(self, root): 20 | """ 21 | :type root: TreeNode 22 | """ 23 | self.stack = [] 24 | self._append(root) 25 | 26 | def next(self): 27 | """ 28 | @return the next smallest number 29 | :rtype: int 30 | """ 31 | res = self.stack.pop() 32 | self._append(res.right) 33 | return res.val 34 | 35 | def hasNext(self): 36 | """ 37 | @return whether we have a next smallest number 38 | :rtype: bool 39 | """ 40 | if self.stack: 41 | return True 42 | return False 43 | 44 | # 辅助函数,压入栈 45 | def _append(self, root): 46 | while root: 47 | self.stack.append(root) 48 | root = root.left -------------------------------------------------------------------------------- /LeetCode/2019-01-17-174-Dungeon-Game.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-17 14:11:43 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-17 19:43:57 6 | 7 | import sys 8 | 9 | 10 | class Solution(object): 11 | def calculateMinimumHP(self, dungeon): 12 | """ 13 | :type dungeon: List[List[int]] 14 | :rtype: int 15 | """ 16 | if not dungeon: 17 | return 0 18 | # 这道题目使用动态规划 19 | row, col = len(dungeon), len(dungeon[0]) 20 | # 声明一个二维数组 21 | b = [[sys.maxsize for _ in range(col + 1)] for _ in range(row + 1)] 22 | # 初始化右下角的位置为1,1表示这里需要1个生命值 23 | b[row][col - 1], b[row - 1][col] = 1, 1 24 | for i in range(row - 1, -1, -1): 25 | for j in range(col - 1, -1, -1): 26 | # 当前位置的生命值由其下面一个和右边一个生命值决定 27 | need = min(b[i + 1][j], b[i][j + 1]) - dungeon[i][j] 28 | # 如果need为正说明这个地方需要消耗生命值 29 | # 如果need为负说明这个位置会提供生命值 30 | b[i][j] = max(1, need) 31 | 32 | return b[0][0] 33 | -------------------------------------------------------------------------------- /LeetCode/2019-01-17-179-Largest-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-17 21:52:16 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-18 17:25:13 6 | 7 | 8 | import functools 9 | 10 | 11 | class Solution: 12 | def largestNumber(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: str 16 | """ 17 | # 对数组进行排序 18 | nums.sort(key=functools.cmp_to_key(self._sort)) 19 | res = ''.join(map(str, nums)) 20 | if res[0] == '0': return '0' 21 | return res 22 | 23 | def _sort(self, num1, num2): 24 | # 修改排序规则 25 | a = str(num1) + str(num2) 26 | b = str(num2) + str(num1) 27 | if a > b: return -1 28 | if a < b: return 1 29 | return 0 -------------------------------------------------------------------------------- /LeetCode/2019-01-18-187-Repeated-DNA-Sequences.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-18 19:56:00 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-18 20:10:34 6 | 7 | 8 | class Solution: 9 | def findRepeatedDnaSequences(self, s): 10 | """ 11 | :type s: str 12 | :rtype: List[str] 13 | """ 14 | # wordset哈希set存储已经出现过的子字符串 15 | # res用于存储结果中的子字符串 16 | wordset, res, count = set(),set(), len(s) 17 | i = 0 18 | # 每一个窗口的长度为10 19 | while i + 10 <= count: 20 | # 如果当前字符串已经出现过,就把当前字符串添加到结果字符串中 21 | if s[i:i + 10] in wordset: 22 | res.add(s[i:i + 10]) 23 | else: 24 | # 如果没有出现过,就添加到记录中 25 | wordset.add(s[i:i + 10]) 26 | i += 1 27 | # 返回需要list类型 28 | return list(res) 29 | -------------------------------------------------------------------------------- /LeetCode/2019-01-19-188-Best-Time-to-Buy-and-Sell-Stock-IV.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-19 12:53:32 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-19 14:31:38 6 | 7 | 8 | class Solution: 9 | def maxProfit(self, k, prices): 10 | """ 11 | :type k: int 12 | :type prices: List[int] 13 | :rtype: int 14 | """ 15 | #交易次数为0或者交易天数小于2时无法进行交易,返回0 16 | if len(prices) < 2 or k == 0: 17 | return 0 18 | # n天最多可以交易n//2次,当允许的交易次数大于这个天数的时候,这道题就转换 19 | # 成了不限制交易次数 20 | if k >= (len(prices) // 2): 21 | return sum(i - j for i, j in zip(prices[1:], prices[:-1]) if i - j > 0) 22 | # 生命矩阵,动态规划 23 | # 为了避免出现内存超出限制,根据本题的特点,矩阵只需要两行就够了 24 | row, col = 2, len(prices) 25 | trans = [[0 for _ in range(col)] for _ in range(row)] 26 | # 进行k次交易 27 | for i in range(k): 28 | maxdiff = trans[i % 2][0] - prices[0] 29 | for j in range(1, col): 30 | maxdiff = max(maxdiff, trans[i % 2][j - 1] - prices[j - 1]) 31 | trans[(i + 1) % 2][j] = max(trans[(i + 1) % 2][j - 1],maxdiff + prices[j]) 32 | return max(trans[0][col - 1], trans[1][col - 1]) 33 | -------------------------------------------------------------------------------- /LeetCode/2019-01-19-189-Rotate-Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-19 17:54:06 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-19 18:26:39 6 | 7 | 8 | class Solution: 9 | def rotate(self, nums, k): 10 | """ 11 | :type nums: List[int] 12 | :type k: int 13 | :rtype: void Do not return anything, modify nums in-place instead. 14 | """ 15 | k %= len(nums) 16 | self.reverse(nums, 0, len(nums) - 1) 17 | self.reverse(nums, 0, k - 1) 18 | self.reverse(nums, k, len(nums) - 1) 19 | 20 | def reverse(self, nums, start, end): 21 | while start < end: 22 | nums[start], nums[end] = nums[end], nums[start] 23 | start, end = start + 1, end - 1 24 | -------------------------------------------------------------------------------- /LeetCode/2019-01-19-190-Reverse-Bits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-19 18:17:49 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-19 19:30:51 6 | 7 | 8 | class Solution: 9 | # @param n, an integer 10 | # @return an integer 11 | def reverseBits(self, n): 12 | if not n: return 0 13 | res = 0 14 | for _ in range(32): 15 | res <<= 1 16 | if n & 1: res += 1 17 | n >>= 1 18 | return res -------------------------------------------------------------------------------- /LeetCode/2019-01-19-191-Number-of-1-Bits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-19 18:24:59 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-19 19:29:49 6 | 7 | class Solution(object): 8 | def hammingWeight(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | if not n:return 0 14 | res =0 15 | for _ in range(32): 16 | if n & 1:res+=1 17 | n>>=1 18 | return res -------------------------------------------------------------------------------- /LeetCode/2019-01-20-198-House-Robber.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-20 12:32:39 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-20 14:07:25 6 | 7 | 8 | class Solution: 9 | def rob(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | rob, notrob = 0, 0 15 | for item in nums: 16 | temp = max(rob, notrob) 17 | rob = item + notrob 18 | notrob = temp 19 | return max(rob, notrob) 20 | -------------------------------------------------------------------------------- /LeetCode/2019-01-20-199-Binary-Tree-Right-Side-View.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-20 14:32:25 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-20 14:34:24 6 | 7 | from collections import deque 8 | 9 | 10 | class Solution: 11 | def rightSideView(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: List[int] 15 | """ 16 | if not root: return [] 17 | res, queue = [], deque() 18 | queue.append(root) 19 | while queue: 20 | res.append(queue[-1].val) 21 | num = len(queue) 22 | for _ in range(num): 23 | node = queue.popleft() 24 | if node.left: queue.append(node.left) 25 | if node.right: queue.append(node.right) 26 | return res -------------------------------------------------------------------------------- /LeetCode/2019-01-20-200-Number-of-Islands.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-20 18:21:07 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-20 18:32:37 6 | 7 | 8 | class Solution: 9 | def numIslands(self, grid): 10 | """ 11 | :type grid: List[List[str]] 12 | :rtype: int 13 | """ 14 | if not grid: return 0 15 | res, row, col = 0, len(grid), len(grid[0]) 16 | for i in range(row): 17 | for j in range(col): 18 | if grid[i][j] == "1": 19 | res += 1 20 | self.dfs(grid, i, j) 21 | return res 22 | 23 | def dfs(self, grid, row, col): 24 | if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] == "0": 25 | return 26 | grid[row][col] = "0" 27 | self.dfs(grid, row - 1, col) 28 | self.dfs(grid, row + 1, col) 29 | self.dfs(grid, row, col + 1) 30 | self.dfs(grid, row, col - 1) 31 | -------------------------------------------------------------------------------- /LeetCode/2019-01-20-201-Bitwise-AND-of-Numbers-Range.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-20 21:06:34 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-21 18:21:42 6 | 7 | 8 | class Solution: 9 | def rangeBitwiseAnd(self, m, n): 10 | """ 11 | :type m: int 12 | :type n: int 13 | :rtype: int 14 | """ 15 | diff = 0 16 | while m - n: 17 | diff += 1 18 | m >>= 1 19 | n >>= 1 20 | return m << diff 21 | -------------------------------------------------------------------------------- /LeetCode/2019-01-20-202-Happy-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-20 21:06:07 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-21 18:50:47 6 | 7 | 8 | class Solution: 9 | def isHappy(self, n): 10 | """ 11 | :type n: int 12 | :rtype: bool 13 | """ 14 | numset = set() 15 | newn = self.square(self.divide(n)) 16 | # 如果求和的结果没有出现过 17 | while newn not in numset: 18 | numset.add(newn) 19 | newn = self.square(self.divide(newn)) 20 | # 如果等于1,返回True 21 | if newn == 1: return True 22 | # 若求和的结果已经出现且不等于1,返回False 23 | return False 24 | 25 | # 拆分函数,返回list 26 | def divide(self, n): 27 | res = [] 28 | while n: 29 | res.append(n % 10) 30 | n //= 10 31 | return res 32 | 33 | # 返回所有数子的平方和 34 | def square(self, nums): 35 | return sum([x**2 for x in nums]) 36 | -------------------------------------------------------------------------------- /LeetCode/2019-01-20-203-Remove-Linked-List-Elements.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-20 21:12:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-20 21:23:10 6 | 7 | 8 | # Definition for singly-linked list. 9 | class ListNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.next = None 13 | 14 | 15 | class Solution: 16 | def removeElements(self, head, val): 17 | """ 18 | :type head: ListNode 19 | :type val: int 20 | :rtype: ListNode 21 | """ 22 | # 添加一个辅助节点 23 | node = ListNode(0) 24 | node.next = head 25 | res = node 26 | while node and node.next: 27 | if node.next.val == val: 28 | temp = node.next 29 | node.next = temp.next 30 | del temp 31 | else: 32 | node = node.next 33 | return res.next 34 | -------------------------------------------------------------------------------- /LeetCode/2019-01-20-204-Count-Primes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-20 21:59:59 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-21 19:19:56 6 | 7 | 8 | class Solution: 9 | def countPrimes(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | if n < 3: return 0 15 | res, isprime = 0, [True] * (n + 1) 16 | isprime[1] = False 17 | for i in range(2, int(n**0.5) + 1): 18 | if isprime[i]: 19 | for j in range(i * i, n + 1, i): 20 | isprime[j] = False 21 | for i in range(2, n): 22 | if isprime[i]: res += 1 23 | 24 | return res 25 | -------------------------------------------------------------------------------- /LeetCode/2019-01-21-205-Isomorphic-Strings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-21 11:56:34 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-21 19:36:15 6 | 7 | 8 | class Solution: 9 | def isIsomorphic(self, s, t): 10 | """ 11 | :type s: str 12 | :type t: str 13 | :rtype: bool 14 | """ 15 | # 字典,键为s中的字符,值为t中的字符 16 | # 键和值必须一一对应 17 | res = {} 18 | for x, y in zip(s, t): 19 | # 若键存在,则其值一定要和y相等 20 | if x in res: 21 | if not res.get(x) == y: return False 22 | else: 23 | # 若y已经作为其他键的值,直接返回False,因为这里要求键值一一对应 24 | if y in res.values(): return False 25 | else: res[x] = y 26 | # 上面的条件都满足,返回True 27 | return True 28 | -------------------------------------------------------------------------------- /LeetCode/2019-01-21-206-Reverse-Linked-List.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-21 12:02:31 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-21 20:17:25 6 | 7 | 8 | class Solution: 9 | def reverseList(self, head): 10 | """ 11 | :type head: ListNode 12 | :rtype: ListNode 13 | """ 14 | if not head:return None 15 | new_head = None 16 | head_next = head.next 17 | while head and head_next: 18 | head.next = new_head 19 | new_head = head 20 | head = head_next 21 | head_next = head_next.next 22 | head.next = new_head 23 | new_head = head 24 | return new_head -------------------------------------------------------------------------------- /LeetCode/2019-01-22-209-Minimum-Size-Subarray-Sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-22 11:37:16 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-22 11:37:16 6 | 7 | import sys 8 | 9 | 10 | class Solution: 11 | def minSubArrayLen(self, s, nums): 12 | """ 13 | :type s: int 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | # 初始化长度 18 | length = sys.maxsize 19 | _sum, left, right = 0, 0, 0 20 | while right < len(nums): 21 | _sum += nums[right] 22 | # 如果当前的和已经大于等于s 23 | if _sum >= s: 24 | # 我们将左指针向右移动,和小于s时跳出 25 | while _sum >= s and left <= right: 26 | _sum -= nums[left] 27 | left += 1 28 | # 更新长度 29 | length = min(right - left + 2, length) 30 | right += 1 31 | # 如果length始终没有发生改变返回0,否则返回length本身 32 | return length if length != sys.maxsize else 0 33 | -------------------------------------------------------------------------------- /LeetCode/2019-01-22-213-House-Robber-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-22 19:43:49 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-22 20:06:11 6 | 7 | 8 | class Solution: 9 | def rob(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | if not nums: return 0 15 | if len(nums) == 1: return nums[0] 16 | frob, fnotrob, rob, notrob = nums[0], 0, 0, 0 17 | for item in nums[1:]: 18 | _max = max(frob, fnotrob) 19 | frob = item + fnotrob 20 | fnotrob = _max 21 | _max = max(rob, notrob) 22 | rob = item + notrob 23 | notrob = _max 24 | return max(fnotrob, rob) 25 | -------------------------------------------------------------------------------- /LeetCode/2019-01-23-214-Shortest-Palindrome.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-23 19:08:33 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-25 22:38:27 6 | 7 | 8 | # 有关KMP的算法详解请关注: 9 | # https://www.youtube.com/watch?v=V5-7GzOfADQ&t=70s 10 | # https://www.youtube.com/watch?v=GTJr8OvyEVQ 11 | 12 | class Solution: 13 | def shortestPalindrome(self, s): 14 | """ 15 | :type s: str 16 | :rtype: str 17 | """ 18 | # KMP next 数组 19 | _next = [0] * (2 * len(s) + 1) 20 | # 重新拼接字符串 21 | news = s + "$" + "".join(list(reversed(s))) 22 | j = 0 23 | # 构造_next数组 24 | for i in range(1, len(news)): 25 | if news[i] == news[j]: 26 | _next[i] = j + 1 27 | j += 1 28 | else: 29 | while j != 0 and news[i] != news[j]: 30 | j = _next[j - 1] 31 | if news[i] == news[j]: 32 | _next[i] = j + 1 33 | j += 1 34 | return news[len(s) + 1:len(s) + len(s) - _next[-1] + 1] + s 35 | -------------------------------------------------------------------------------- /LeetCode/2019-01-23-215-Kth-Largest-Element-in-an-Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-23 22:57:06 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-26 20:23:38 6 | 7 | 8 | class Solution: 9 | def findKthLargest(self, nums, k): 10 | """ 11 | :type nums: List[int] 12 | :type k: int 13 | :rtype: int 14 | """ 15 | left, right = 0, len(nums) - 1 16 | # 17 | pivot = self._quicksort(nums, left, right) 18 | while pivot != k - 1: 19 | # 如果当前确定的位置在k的左边,说明要求的元素应该在右边 20 | if pivot < k - 1: 21 | left = pivot + 1 22 | # 如果当前确定的位置在k的右边,说明要求的元素应该在左边 23 | elif pivot > k - 1: 24 | right = pivot - 1 25 | pivot = self._quicksort(nums, left, right) 26 | return nums[pivot] 27 | 28 | # 快速排序 29 | def _quicksort(self, nums, left, right): 30 | pivot, j = right, left 31 | for i in range(left, right): 32 | if nums[i] > nums[pivot]: 33 | if j != i: 34 | nums[i], nums[j] = nums[j], nums[i] 35 | j += 1 36 | nums[j], nums[pivot] = nums[pivot], nums[j] 37 | # 返回当前已经确定元素的索引 38 | return j 39 | -------------------------------------------------------------------------------- /LeetCode/2019-01-24-216-Combination-Sum-III.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-24 06:37:54 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-26 20:38:26 6 | 7 | 8 | class Solution: 9 | def combinationSum3(self, k, n): 10 | """ 11 | :type k: int 12 | :type n: int 13 | :rtype: List[List[int]] 14 | """ 15 | return self.recursion([i for i in range(1, 10)], k, n) 16 | 17 | def recursion(self, nums, k, _sum): 18 | if k <= 0: return 19 | if k == 1: 20 | if _sum in nums: return [[_sum]] 21 | else: return [] 22 | res = [] 23 | # 递归求解 24 | for i in range(len(nums)): 25 | # 从当前元素后面位置中寻找解 26 | for item in self.recursion(nums[i + 1:], k - 1, _sum - nums[i]): 27 | res.append(item + [nums[i]]) 28 | return res 29 | -------------------------------------------------------------------------------- /LeetCode/2019-01-24-217-Contains-Duplicate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-24 19:13:41 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-26 20:56:11 6 | 7 | 8 | class Solution: 9 | def containsDuplicate(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: bool 13 | """ 14 | # 如果没有重复,那么这两种数据结构的元素个数应该相等 15 | return len(set(nums)) - len(nums) != 0 16 | -------------------------------------------------------------------------------- /LeetCode/2019-01-25-219-Contains-Duplicate-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-25 19:04:39 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-26 22:37:41 6 | 7 | 8 | class Solution: 9 | def containsNearbyDuplicate(self, nums, k): 10 | """ 11 | :type nums: List[int] 12 | :type k: int 13 | :rtype: bool 14 | """ 15 | # 如果没有数字或者只有一个数字,则不可能有满足题意的解 16 | if nums == [] or len(nums) == 1: return False 17 | # 如果没有重复元素,也不可能有满足题意的解 18 | if len(nums) == len(set(nums)): return False 19 | # 我们用一个dict存储重复的值 20 | dic = {} 21 | for index, num in enumerate(nums): 22 | if num not in dic: 23 | dic[num] = [] 24 | dic[num].append(index) 25 | # 如果相同的值索引差小于等于k,返回True 26 | if len(dic[num]) > 1 and dic[num][-1] - dic[num][-2] <= k: 27 | return True 28 | # 如果遍历整个数组都没有找到满足条件的值,返回False 29 | return False -------------------------------------------------------------------------------- /LeetCode/2019-01-25-220-Contains-Duplicate-III.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-25 19:57:09 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-25 21:09:12 6 | 7 | import collections 8 | 9 | 10 | class Solution: 11 | def containsNearbyAlmostDuplicate(self, nums, k, t): 12 | """ 13 | :type nums: List[int] 14 | :type k: int 15 | :type t: int 16 | :rtype: bool 17 | """ 18 | if not nums or k <= 0 or t < 0: return False 19 | # 创建一个有序字典 20 | dic = collections.OrderedDict() 21 | for n in nums: 22 | # 这里使用了桶的思想 23 | key = n if not t else n // t 24 | for m in (dic.get(key - 1), dic.get(key), dic.get(key + 1)): 25 | if m is not None and abs(n - m) <= t: 26 | return True 27 | # False表示先进先出 28 | if len(dic) == k: dic.popitem(False) 29 | dic[key] = n 30 | return False 31 | -------------------------------------------------------------------------------- /LeetCode/2019-01-26-221-Maximal-Square.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-26 21:25:03 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-27 20:17:15 6 | 7 | 8 | class Solution: 9 | def maximalSquare(self, matrix): 10 | """ 11 | :type matrix: List[List[str]] 12 | :rtype: int 13 | """ 14 | # 如果矩阵为空,直接返回0 15 | if not matrix: return 0 16 | # 获取矩阵的行数和列数 17 | row, col = len(matrix), len(matrix[0]) 18 | # 动态规划矩阵,矩阵中的值表示正方形的边长 19 | board = [[0 for _ in range(col + 1)] for _ in range(row + 1)] 20 | # res表示最大边长 21 | res = 0 22 | for i in range(1, row + 1): 23 | for j in range(1, col + 1): 24 | # 如果当前位置是'1' 25 | if matrix[i - 1][j - 1] == "1": 26 | left = board[i - 1][j] 27 | up = board[i][j - 1] 28 | dia = board[i - 1][j - 1] 29 | # 动态规划矩阵,当前位置的值为当前位置左边 30 | # 当前位置上边,当前位置斜上边位置的最小值载加上1 31 | board[i][j] += 1 + min(left, up, dia) 32 | # 不断更新最大边长的值 33 | res = max(res, board[i][j]) 34 | # 返回最大边长的平方,即正方形的面积 35 | return res**2 -------------------------------------------------------------------------------- /LeetCode/2019-01-27-222-Count-Complete-Tree-Nodes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-27 20:02:19 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-27 20:13:03 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | class Solution: 17 | def countNodes(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: int 21 | """ 22 | if not root: return 0 23 | # 获取左子树的高度 24 | left = self.depth(root.left) 25 | # 获取右子树的高度 26 | right = self.depth(root.right) 27 | # 如果左右子树的高度相等,则左子树一定是一颗满二叉树 28 | if left == right: 29 | return 2**left + self.countNodes(root.right) 30 | # 如果左右子树高度不相等,则右子树一定是一颗满二叉树 31 | if left != right: 32 | return 2**right + self.countNodes(root.left) 33 | 34 | def depth(self, root): 35 | # 获取完全二叉树的高度 36 | if not root: return 0 37 | res = 0 38 | while root: 39 | res += 1 40 | root = root.left 41 | return res 42 | -------------------------------------------------------------------------------- /LeetCode/2019-01-28-223-Rectangle-Area.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-28 20:01:58 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-28 22:42:49 6 | 7 | 8 | class Solution: 9 | def computeArea(self, A, B, C, D, E, F, G, H): 10 | """ 11 | :type A: int 12 | :type B: int 13 | :type C: int 14 | :type D: int 15 | :type E: int 16 | :type F: int 17 | :type G: int 18 | :type H: int 19 | :rtype: int 20 | """ 21 | # 第一个矩形的面积,第二个矩形的面积 22 | area1, area2 = (C - A) * (D - B), (G - E) * (H - F) 23 | # 重叠的长,重叠的宽 24 | _long, _width = min(C, G) - max(A, E), min(D, H) - max(B, F) 25 | # 如果长宽中有一个小于零,说明并不存在重叠的矩形,设置其面积为0,否则其面积为长*宽 26 | overlap = _long * _width if _long > 0 and _width > 0 else 0 27 | return area1 + area2 - overlap 28 | -------------------------------------------------------------------------------- /LeetCode/2019-01-28-226-Invert-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-28 20:30:22 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-28 20:39:41 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | class Solution: 17 | def invertTree(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: TreeNode 21 | """ 22 | # 如果为空,直接返回 23 | if root: return 24 | # 转换左子树 25 | left = self.invertTree(root.left) 26 | # 转换右子树 27 | right = self.invertTree(root.right) 28 | # 交换左右子树 29 | root.left, root.right = right, left 30 | return root 31 | -------------------------------------------------------------------------------- /LeetCode/2019-01-31-231-Power-of-Two.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-01-31 17:04:06 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-01-31 17:29:56 6 | 7 | 8 | class Solution: 9 | def isPowerOfTwo(self, n): 10 | """ 11 | :type n: int 12 | :rtype: bool 13 | """ 14 | # 无论是2的多少次方,用二进制表示,只会有一个1 15 | res = 0 16 | while n > 0: 17 | res += (n & 1) 18 | n >>= 1 19 | return res == 1 -------------------------------------------------------------------------------- /LeetCode/2019-02-01-233-Number-of-Digit-One.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-01 12:57:09 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-01 14:28:55 6 | 7 | 8 | class Solution: 9 | def countDigitOne(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | res = 0 15 | # 如果是负数,直接返回零 16 | if n <= 0: return res 17 | # 当前位置左边的所有数,当前位置的值,当前位置右边的值 18 | left, right, middle, factor = 1, 1, 1, 1 19 | # 循环条件,当left不为零(即左边还有数的时候) 20 | while left: 21 | # 取左边部分 22 | left = n // (factor * 10) 23 | # 取当前位置的值 24 | middle = n // factor % 10 25 | # 取当前位置右边的值 26 | right = n % factor 27 | # 如果当前位置的值为0 28 | if middle == 0: 29 | res += left * factor 30 | # 如果当前的值为1 31 | elif middle == 1: 32 | res += left * factor + right + 1 33 | # 如果当前的值大于等于2 34 | else: 35 | res += (left + 1) * factor 36 | factor *= 10 37 | # 返回最终的结果 38 | return res -------------------------------------------------------------------------------- /LeetCode/2019-02-01-235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-01 18:26:43 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-01 18:44:19 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | class Solution: 17 | def lowestCommonAncestor(self, root, p, q): 18 | """ 19 | :type root: TreeNode 20 | :type p: TreeNode 21 | :type q: TreeNode 22 | :rtype: TreeNode 23 | """ 24 | # 根据二叉搜索树的性质, lowest common ancestor 节点的值一定在p和q之间 25 | # 如果当前节点的值大于p和q节点的值,说明LCA在当前节点左边 26 | # 如果当前节点的值小于p和q节点的值,说明LCA在当前节点右边 27 | 28 | if p.val < q.val: 29 | return self._recursion(root, p, q) 30 | else: 31 | return self._recursion(root, q, p) 32 | 33 | def _recursion(self, root, p, q): 34 | # p节点的值一定小于q节点的值 35 | if p.val <= root.val <= q.val: return root 36 | if root.val < p.val and root.val < q.val: 37 | return self._recursion(root.right, p, q) 38 | if root.val > p.val and root.val > q.val: 39 | return self._recursion(root.left, p, q) 40 | -------------------------------------------------------------------------------- /LeetCode/2019-02-01-236-Lowest-Common-Ancestor-of-a-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-01 18:56:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-01 20:20:55 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | class Solution: 17 | def lowestCommonAncestor(self, root, p, q): 18 | """ 19 | :type root: TreeNode 20 | :type p: TreeNode 21 | :type q: TreeNode 22 | :rtype: TreeNode 23 | """ 24 | # 如果为空返回None 25 | if not root: return None 26 | # 如果当前节点等于p.val 或 q.val 返回当前节点索引 27 | if root.val == p.val or root.val == q.val: return root 28 | # 递归遍历左子树 29 | left = self.lowestCommonAncestor(root.left, p, q) 30 | # 递归遍历右子树 31 | right = self.lowestCommonAncestor(root.right, p, q) 32 | # 如果左右都不为空,说明当前节点符合条件 33 | if left and right: return root 34 | # 如果左边不为空右边为空 35 | if left and not right: return left 36 | # 如果左边为空右边不为空 37 | if not left and right: return right 38 | # 如果左右都为空 39 | if not left and not right: return None 40 | -------------------------------------------------------------------------------- /LeetCode/2019-02-01-237-Delete-Node-in-a-Linked-List.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-01 20:42:50 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-01 21:12:10 6 | 7 | 8 | # Definition for singly-linked list. 9 | class ListNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.next = None 13 | 14 | 15 | class Solution: 16 | def deleteNode(self, node): 17 | """ 18 | :type node: ListNode 19 | :rtype: void Do not return anything, modify node in-place instead. 20 | """ 21 | # 记录最后一个节点前面一个节点 22 | pretail = node 23 | # 把要删除节点的值放到最后一节点 24 | while node.next: 25 | pretail = node 26 | node.val, node.next.val = node.next.val, node.val 27 | node = node.next 28 | # 删除嘴后一个节点 29 | temp = pretail.next 30 | del temp 31 | # 最后一个节点的前一个节点next指针置为None 32 | pretail.next = None 33 | -------------------------------------------------------------------------------- /LeetCode/2019-02-02-238-Product-of-Array-Except-Self.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-02 08:52:08 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-02 09:01:08 6 | 7 | 8 | class Solution: 9 | def productExceptSelf(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: List[int] 13 | """ 14 | # 声明结果数组,第一个位置(索引0)一定要初始化为1 15 | res = [1 for _ in range(len(nums))] 16 | # 辅助变量 17 | _product = nums[-1] 18 | # 正向遍历,获取当前位置左边的所有数字乘积的值 19 | for i in range(1, len(nums)): 20 | res[i] = res[i - 1] * nums[i - 1] 21 | # 反向遍历,_product表示当前位置右边的数所有乘积的值 22 | for i in range(len(nums) - 2, -1, -1): 23 | # 当前位置的值等与当前位置左右两边所有数的乘积 24 | res[i] = _product * res[i] 25 | _product *= nums[i] 26 | # 返回结果 27 | return res 28 | -------------------------------------------------------------------------------- /LeetCode/2019-02-02-240-Search-a-2D-Matrix-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-02 13:01:11 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-02 13:45:27 6 | 7 | 8 | class Solution: 9 | def searchMatrix(self, matrix, target): 10 | """ 11 | :type matrix: List[List[int]] 12 | :type target: int 13 | :rtype: bool 14 | """ 15 | if not matrix or not matrix[0]: return False 16 | # 从矩阵的右上角开始寻找(左下角也可以) 17 | # 从右上角开始,如果向左走则所有的元素递减;如果向下走所有的元素递增 18 | row, col = 0, len(matrix[0]) - 1 19 | while row < len(matrix) and col >= 0: 20 | # 如果相等,返回True 21 | if matrix[row][col] == target: return True 22 | # 如果当前位置元素更大,由于当列的元素都大于当前元素 23 | # 即target不在当前列中,col自减一次 24 | if matrix[row][col] > target: col -= 1 25 | # 如果当前位置的元素更小,由于当前元素在行的末尾 26 | # (当前元素后面的元素已经被列判定给否定了) 27 | # 当前元素前面的元素前面的元素都小于当前元素 28 | # 即target不在当前行中,row自增一次 29 | if matrix[row][col] < target: row += 1 30 | return False -------------------------------------------------------------------------------- /LeetCode/2019-02-02-242-Valid-Anagram.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-02 16:55:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-02 18:05:09 6 | 7 | 8 | class Solution: 9 | def isAnagram(self, s, t): 10 | """ 11 | :type s: str 12 | :type t: str 13 | :rtype: bool 14 | """ 15 | if len(s) != len(t): return False 16 | # 题目明确只会给定26个小写字母 17 | scount, tcount = [0 for _ in range(26)], [0 for _ in range(26)] 18 | for x, y in zip(s, t): 19 | # 统计s中字母出现的次数 20 | scount[ord(x) - ord('a')] += 1 21 | # 统计t中字母出现的次数 22 | tcount[ord(y) - ord('a')] += 1 23 | # 返回s和t中字母出现的次数是否一一对应相等 24 | return scount == tcount 25 | -------------------------------------------------------------------------------- /LeetCode/2019-02-02-257-Binary-Tree-Paths.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-02 20:29:47 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-02 20:46:54 6 | 7 | 8 | # Definition for a binary tree node. 9 | class TreeNode: 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | 16 | class Solution: 17 | def binaryTreePaths(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: List[str] 21 | """ 22 | self.res = [] 23 | self.__dfs(root, '') 24 | return self.res 25 | 26 | def __dfs(self, root, _str): 27 | # 走到None节点直接返回 28 | if not root: 29 | return 30 | # 如果走到叶子节点,我们将最后的结果添加到结果数组中 31 | if not root.left and not root.right: 32 | self.res.append(_str + str(root.val)) 33 | return 34 | # 递归遍历左子树 35 | self.__dfs(root.left, _str + str(root.val) + "->") 36 | # 递归遍历右子树 37 | self.__dfs(root.right, _str + str(root.val) + "->") 38 | -------------------------------------------------------------------------------- /LeetCode/2019-02-02-258-Add-Digits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-02 23:27:58 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-02 23:29:33 6 | 7 | 8 | class Solution: 9 | def addDigits(self, num): 10 | """ 11 | :type num: int 12 | :rtype: int 13 | """ 14 | if num == 0: return 0 15 | b = num % 9 16 | return b if b != 0 else 9 17 | -------------------------------------------------------------------------------- /LeetCode/2019-02-03-260-Single-Number-III.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-03 09:02:18 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-03 09:02:18 6 | 7 | 8 | class Solution: 9 | def singleNumber(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: List[int] 13 | """ 14 | res = [0, 0] 15 | diff = 0 16 | for num in nums: 17 | diff ^= num 18 | # 制造分离因子 19 | diff = diff & (~(diff - 1)) 20 | for num in nums: 21 | if (num & diff) == 0: 22 | res[0] ^= num 23 | else: 24 | res[1] ^= num 25 | return res 26 | -------------------------------------------------------------------------------- /LeetCode/2019-02-03-263-Ugly-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-03 09:30:18 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-03 10:05:52 6 | 7 | 8 | class Solution: 9 | def isUgly(self, num): 10 | """ 11 | :type num: int 12 | :rtype: bool 13 | """ 14 | if num <= 0: return False 15 | for factor in [2, 3, 5]: 16 | while not num % factor: 17 | num /= factor 18 | if num == 1: return True 19 | return False -------------------------------------------------------------------------------- /LeetCode/2019-02-04-264-Ugly-Number-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-04 13:35:56 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-04 14:25:45 6 | 7 | 8 | class Solution: 9 | def nthUglyNumber(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | uglynum = [1] 15 | # i:2的次数,j:3的次数,k:5的次数,count:丑数的个数 16 | i, j, k, count = 0, 0, 0, 1 17 | while count < n: 18 | # 我们以对应的上一个数为基底,分别对应乘上2,3,5, 19 | uglyi, uglyj, uglyk = uglynum[i] * 2, uglynum[j] * 3, uglynum[k] * 5 20 | # 然后我们选择最小的数 21 | uglynext = min(uglyi, uglyj, uglyk) 22 | # 我们更新基地 23 | if uglynext == uglyi: i += 1 24 | if uglynext == uglyj: j += 1 25 | if uglynext == uglyk: k += 1 26 | uglynum.append(uglynext) 27 | count += 1 28 | # 返回最后一个数字 29 | return uglynum[-1] 30 | -------------------------------------------------------------------------------- /LeetCode/2019-02-04-268-Missing-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-04 15:30:54 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-04 16:05:54 6 | 7 | 8 | class Solution: 9 | def missingNumber(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | return len(nums) * (len(nums) + 1) // 2 - sum(nums) 15 | 16 | def missingNumber2(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: int 20 | """ 21 | # 位运算 0^0^1^2^2^3^3^4^4 = 1 22 | # 即偶数次亦或结果为0,奇数次为本身 23 | # 给定的数范围从0到n共n个(丢失了一个),我们然i从0自增到n-1,另res初始化为n。 24 | # 对所有的数进行异或运算,重复出现的数字两两配对,抑或的结果为0 25 | # 落单的数字亦或会被保留 26 | res = len(nums) 27 | for i in range(len(nums)): 28 | res ^= i ^ nums[i] 29 | return res 30 | -------------------------------------------------------------------------------- /LeetCode/2019-02-05-274-H-Index.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-05 12:24:54 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-05 19:45:16 6 | 7 | 8 | class Solution: 9 | def hIndex(self, citations: 'List[int]') -> 'int': 10 | # 如果输入为空,返回0 11 | if not citations: return 0 12 | h = 0 13 | # 对输入的数据排序 14 | citations.sort() 15 | # 从后向前遍历 16 | for item in citations[-1::-1]: 17 | # 根据题意,至少有h个元素大于h 18 | h += 1 19 | # 如果出现当前元素小于h时,说明已经不满足给定的条件,函数返回 20 | if item < h: 21 | h -= 1 22 | break 23 | return h 24 | -------------------------------------------------------------------------------- /LeetCode/2019-02-05-275-H-Index-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-05 12:27:25 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-05 19:58:17 6 | 7 | 8 | class Solution: 9 | def hIndex(self, citations: 'List[int]') -> 'int': 10 | # 如果给定的数组为空,返回0 11 | if not citations: return 0 12 | count = len(citations) 13 | # 采用二分查找的思想 14 | left, right, milldle = 0, count - 1, 0 15 | while left <= right: 16 | # 去掉左边的所有非零项 17 | while left < count and citations[left] == 0: 18 | left += 1 19 | milldle = ((right - left) >> 1) + left 20 | # 如果当前位置元素值大于等于从当前位置往后数(包括当前元素)的元素个数 21 | if citations[milldle] >= (count - milldle): 22 | right = milldle - 1 23 | # 如果当前位置元素值小于从当前位置往后数(包括当前元素)的元素个数 24 | elif citations[milldle] < (count - milldle): 25 | left = milldle + 1 26 | # 返回元素个数 27 | return count - left 28 | -------------------------------------------------------------------------------- /LeetCode/2019-02-05-278-First-Bad-Version.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-05 16:35:35 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-05 16:35:35 6 | 7 | 8 | # The isBadVersion API is already defined for you. 9 | # @param version, an integer 10 | # @return a bool 11 | def isBadVersion(version): 12 | return True 13 | 14 | 15 | class Solution: 16 | def firstBadVersion(self, n): 17 | """ 18 | :type n: int 19 | :rtype: int 20 | """ 21 | # 二分查找,左边界,右边界 22 | left, right, middle = 1, n, 0 23 | while left <= right: 24 | middle = ((right - left) >> 1) + left 25 | # isBadVersion 函数由主调函数提供 26 | # 如果当前位置的右边 27 | if not isBadVersion(middle): 28 | # 结束条件 29 | if isBadVersion(middle + 1): 30 | return middle + 1 31 | left = middle + 1 32 | # 如果在当前位置的左边 33 | else: 34 | right = middle - 1 35 | # 如果第一个元素就坏了,返回1 36 | if right == 0: return 1 -------------------------------------------------------------------------------- /LeetCode/2019-02-07-283-Move-Zeroes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-07 13:55:55 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-07 14:07:46 6 | 7 | 8 | class Solution: 9 | def moveZeroes(self, nums: 'List[int]') -> 'None': 10 | """ 11 | Do not return anything, modify nums in-place instead. 12 | """ 13 | # 获取第一个0的索引 14 | first = 0 15 | while first < len(nums): 16 | if nums[first] == 0: 17 | break 18 | first += 1 19 | # 如果0已经在嘴后一个位置或者没有0 20 | if first >= len(nums) - 1: 21 | return 22 | # 把第一个0和0后面的非零数替换 23 | # 并将first自增一次,指向下一个0 24 | for i in range(len(nums)): 25 | if nums[i] and i > first: 26 | nums[i], nums[first] = nums[first], nums[i] 27 | first += 1 -------------------------------------------------------------------------------- /LeetCode/2019-02-08-290-Word-Pattern.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-08 11:19:39 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-09 09:43:27 6 | 7 | 8 | class Solution: 9 | def wordPattern(self, pattern: 'str', str: 'str') -> 'bool': 10 | # 字典,记录对应关系 11 | match = {} 12 | # 将给定的单词用空格区分 13 | word = str.split(" ") 14 | # 如果长度不相等,直接返回False 15 | if len(pattern) != len(word): return False 16 | for i in range(len(pattern)): 17 | # 如果模式串pattern[i]不在字典中(键) 18 | if pattern[i] not in match: 19 | # 如果此时的单词在字典的值中,说明已经有模式串的字符与当前单词匹配,返回False 20 | if word[i] in match.values(): 21 | return False 22 | # 如果单词没有出现在字典的值中,添加当前模式串与单词的对应关系 23 | match[pattern[i]] = word[i] 24 | else: 25 | # 如果当前模式串的键已经在字典中,检查字典的值和当前单词是否相等,不等返回False 26 | if match[pattern[i]] != word[i]: 27 | return False 28 | return True 29 | -------------------------------------------------------------------------------- /LeetCode/2019-02-08-292-Nim-Game.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-08 11:59:57 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-08 12:23:10 6 | 7 | 8 | class Solution: 9 | def canWinNim(self, n: 'int') -> 'bool': 10 | # 如果是4的倍数,一定会失败 11 | if not n % 4: return False 12 | # 否则一定赢,返回True 13 | return True -------------------------------------------------------------------------------- /LeetCode/2019-02-08-295-Find-Median-from-Data-Stream.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-08 13:58:09 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-08 13:58:09 6 | 7 | # 二分搜索库 8 | import bisect 9 | 10 | 11 | class MedianFinder: 12 | def __init__(self): 13 | """ 14 | initialize your data structure here. 15 | """ 16 | # 声明一个数组 17 | self.list = [] 18 | # 数组中元素的个数 19 | self.count = 0 20 | 21 | def addNum(self, num: 'int') -> 'None': 22 | # 将元素个数自增一次 23 | self.count += 1 24 | # 插入新元素 25 | bisect.insort_left(self.list, num) 26 | 27 | def findMedian(self) -> 'float': 28 | # 如果是奇数,返回中间值 29 | if self.count % 2: 30 | return self.list[self.count // 2] 31 | else: 32 | # 如果是偶数,返回中间两个数的平均值 33 | num1 = self.count // 2 34 | return (self.list[num1] + self.list[num1 - 1]) / 2 35 | -------------------------------------------------------------------------------- /LeetCode/2019-02-08-299-Bulls-and-Cows.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-08 18:00:07 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-08 18:22:24 6 | 7 | 8 | class Solution: 9 | def getHint(self, secret: 'str', guess: 'str') -> 'str': 10 | A, B = 0, 0 11 | # 字典,用于统计secret出现的字符个数 12 | # unused用于统计guess中还没有和secret匹配的字符(指对应位置字符不等) 13 | match, unused = {}, [] 14 | for x, y in zip(secret, guess): 15 | # 如果对应位置的字符相等,A自增一次 16 | if x == y: 17 | A += 1 18 | else: 19 | # 否则我们统计secret中当前字符出现的次数 20 | match[x] = match.get(x, 0) + 1 21 | # 并将guess中的当前字符添加到unused中 22 | unused.append(y) 23 | # 我们遍历unsed中的字符 24 | for item in unused: 25 | # 如果当前字符出现在了match字典中 26 | if item in match and match[item] > 0: 27 | # B自增一次 28 | B += 1 29 | # 字典中对应字符次数减少一次,表示当前字符已经被匹配了一次 30 | match[item] -= 1 31 | return str(A) + "A" + str(B) + "B" 32 | -------------------------------------------------------------------------------- /LeetCode/2019-02-08-300-Longest-Increasing-Subsequence.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-08 18:23:33 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-08 18:23:33 6 | 7 | 8 | class Solution: 9 | def lengthOfLIS(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | # 数组的个数 15 | length = len(nums) 16 | # 如果数组中没有元素或者只有一个元素,直接返回数组长度 17 | if length <= 1: return length 18 | # 动态规划,数组没个位置初始化为1 19 | # 表示连续递增的序列长度最下为1 20 | count = [1] * length 21 | res = 0 22 | for i in range(1, length): 23 | # 初始化为1 24 | _max = 1 25 | # 从当前位置遍历到i 26 | for j in range(0, i): 27 | # 第i个数的最大值为0到i-1中所有小于当前元素能够称的连续序列加一的最大值 28 | if nums[j] < nums[i]: _max = max(count[j] + 1, _max) 29 | # 更新当前位置的最大值 30 | count[i] = _max 31 | # 记录所有值的最大值 32 | res = max(res, _max) 33 | return res -------------------------------------------------------------------------------- /LeetCode/2019-02-10-303-Range-Sum-Query-Immutable.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-10 21:56:48 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-10 22:02:19 6 | 7 | 8 | class NumArray: 9 | def __init__(self, nums: 'List[int]'): 10 | # 对给定的数组的前面的数求和 11 | if not nums: 12 | self.sum = [] 13 | else: 14 | self.sum = [nums[0]] * len(nums) 15 | for i in range(1, len(nums)): 16 | self.sum[i] = self.sum[i - 1] + nums[i] 17 | 18 | def sumRange(self, i: 'int', j: 'int') -> 'int': 19 | # 做差返回对应序列的值 20 | return self.sum[j] - self.sum[i - 1] if i > 0 else self.sum[j] 21 | -------------------------------------------------------------------------------- /LeetCode/2019-02-13-309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-13 14:21:33 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-13 17:36:21 6 | 7 | import sys 8 | 9 | 10 | class Solution: 11 | def maxProfit(self, prices: 'List[int]') -> 'int': 12 | # 少于两天无法进行交易 13 | if len(prices) < 2: return 0 14 | colldown, hold, sold = 0, -sys.maxsize, 0 15 | for day in range(len(prices)): 16 | oldhold = hold 17 | # 当天持有:当天可以什么都不做,持有昨天持有的股票 18 | # 或者当天买进股票 19 | # 所以:当天价值可以来自前一天持有的价值,或者前一天休息今天买入的价值 20 | hold = max(oldhold, colldown - prices[day]) 21 | # 当天休息:当天的价值可以来自于前一天休息的价值 22 | # 或者前一天卖出的价值 23 | colldown = max(colldown, sold) 24 | # 当天卖出:当前价值来自前一天持有加上今天的价值 25 | sold = oldhold + prices[day] 26 | return max(colldown, sold) -------------------------------------------------------------------------------- /LeetCode/2019-02-19-313-Super-Ugly-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-19 15:35:20 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-19 16:11:26 6 | 7 | 8 | class Solution: 9 | def nthSuperUglyNumber(self, n: 'int', primes: 'List[int]') -> 'int': 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | # 处理特殊情况,如果n为1或者primes为空,返回1 15 | if n < 2 or not primes: return 1 16 | # 声明一个数组,用于存储获取的丑数 17 | uglynum = [1] 18 | # 辅助变量,primes的个数,当前生成的丑数的个数 19 | num, count = len(primes), 1 20 | # index数组用于存储primes中每个数上一次产生有效数的下一个位置 21 | index = [0 for _ in range(num)] 22 | while count < n: 23 | # 动态规划,用primes中的每个数从上一次产生有效位置的地方产生下一个数 24 | _next = [primes[i] * uglynum[index[i]] for i in range(num)] 25 | # 下一个丑数是产生的丑数中最小的数 26 | uglynext = min(_next) 27 | # 更新索引值 28 | for i in range(num): 29 | if uglynext == _next[i]: index[i] += 1 30 | uglynum.append(uglynext) 31 | count += 1 32 | # 返回最后一个丑数 33 | return uglynum[-1] 34 | -------------------------------------------------------------------------------- /LeetCode/2019-02-23-319-Bulb-Switcher.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-02-23 18:46:36 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-02-23 19:46:07 6 | 7 | 8 | class Solution: 9 | def bulbSwitch(self, n: int) -> int: 10 | return int(n**0.5) 11 | 12 | def bulbSwitch2(self, n: int) -> int: 13 | count, i = 0, 3 14 | # 首项为3,公差为 2 的等差数列 15 | # n 为这些数字的和 16 | while n > 0: 17 | # 每次从 n 中去掉一项 18 | n -= i 19 | i += 2 20 | # 记录去掉的次数 21 | count += 1 22 | # 次数就是剩下的亮着的灯泡个数 23 | return count 24 | 25 | def bulbSwitch3(self, n: int) -> int: 26 | # 最直观的思路,用一个数组表示灯泡的开关情况,0 表示关,1 表示开 27 | # !!! 此方法会超时 28 | bulbs = [0 for i in range(n)] 29 | for i in range(n): 30 | j = i 31 | # 每轮调整 i 整数倍的位置 32 | while j < n: 33 | bulbs[j] ^= 1 34 | j += i + 1 35 | # 统计最后剩下的 1 的个数 36 | return bulbs.count(1) 37 | -------------------------------------------------------------------------------- /LeetCode/2019-03-02-326-Power-of-Three.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-03-02 15:38:41 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-03-02 15:39:03 6 | 7 | import math 8 | 9 | class Solution: 10 | def isPowerOfThree(self, n: int) -> bool: 11 | return 3**round(math.log(n, 3)) == n if n > 0 else False 12 | -------------------------------------------------------------------------------- /LeetCode/2019-03-02-327-Count-of-Range-Sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-03-02 15:54:22 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-03-02 20:40:27 6 | 7 | import bisect 8 | 9 | 10 | class Solution: 11 | def countRangeSum(self, nums: [int], lower: int, upper: int) -> int: 12 | presum, _sum, count = [0], 0, 0 13 | for num in nums: 14 | _sum += num 15 | right = bisect.bisect_right(presum, _sum - lower) 16 | left = bisect.bisect_left(presum, _sum - upper) 17 | count += right - left 18 | bisect.insort(presum, _sum) 19 | return count -------------------------------------------------------------------------------- /LeetCode/2019-03-14-330-Patching-Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-03-14 20:40:22 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-03-14 21:57:33 6 | 7 | 8 | class Solution: 9 | def minPatches(self, nums: [int], n: int) -> int: 10 | # tmp 表示所有数字的和,count表示需要添加数字,i 为索引 11 | # 定义[0,8) 8 为和的边界 12 | tmp, count, i = 0, 0, 0 13 | # 循环条件 14 | while tmp < n: 15 | # 如果 num[i] 在当前和的范围之内,那么把 num[i] 添加到 16 | # 当前的和范围内是最经济的做法 17 | if i < len(nums) and nums[i] <= tmp + 1: 18 | tmp += nums[i] 19 | i += 1 20 | # 否则,我们需要把当前和的边界的数字作为一个新的数字添加到和中 21 | else: 22 | tmp += tmp + 1 23 | count += 1 24 | return count -------------------------------------------------------------------------------- /LeetCode/2019-03-17-331-Verify-Preorder-Serialization-of-a-Binary-Tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-03-17 09:44:27 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-03-17 10:03:55 6 | 7 | 8 | class Solution: 9 | def isValidSerialization(self, preorder: str) -> bool: 10 | # stack:用于记录遍历到的节点值 11 | # count:stack 中剩余的节点个数 12 | stack, count = [], 0 13 | for item in preorder.split(","): 14 | stack.append(item) 15 | count += 1 16 | # 如果 stack 中末位两个元素是 #,说明这两个节点前面是一个叶子节点 17 | # 将两个 # 弹出 ,将叶子节点置为 None,即 # 18 | # 如果是前序遍历,那么 stack 最后一定会剩下一个 # 19 | while count > 1 and stack[-1] == "#" and stack[-2] == "#": 20 | stack.pop() 21 | stack.pop() 22 | if not stack: return False 23 | stack[-1] = "#" 24 | count -= 2 25 | # 当且仅当 stack 中只剩下一个元素且为 # 时返回 True. 26 | return True if len(stack) == 1 and stack[0] == "#" else False -------------------------------------------------------------------------------- /LeetCode/2019-03-27-332-Reconstruct-Itinerary.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-03-27 19:47:01 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-03-27 19:47:01 6 | 7 | import collections 8 | 9 | 10 | class Solution: 11 | def findItinerary(self, tickets): 12 | targets = collections.defaultdict(list) 13 | for a, b in sorted(tickets)[::-1]: 14 | targets[a] += b, 15 | route = [] 16 | 17 | def visit(airport): 18 | while targets[airport]: 19 | visit(targets[airport].pop()) 20 | route.append(airport) 21 | 22 | visit('JFK') 23 | return route[::-1] -------------------------------------------------------------------------------- /LeetCode/2019-03-28-334-Increasing-Triplet-Subsequence.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-03-28 10:02:55 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-03-28 11:08:49 6 | 7 | 8 | class Solution: 9 | def increasingTriplet(self, nums: [int]) -> bool: 10 | # 声明三个索引变量,用于记录满足条件的之 11 | i, j, k = 0, 1, 1 12 | # 元素的个数 13 | count = len(nums) 14 | # 找到数组中最前面递增的两个数 15 | while i < count and j < count and nums[i] >= nums[j]: 16 | i += 1 17 | j += 1 18 | # k 更新为 j 后面的那一个数 19 | k = j + 1 20 | while k < count: 21 | # 如果 nums[k] 比 nums[j] 大,说明已经有三个数满足条件 22 | if nums[k] > nums[j]: return True 23 | # 如果 nums[k] 在 nums[i] 和 nums[j] 中间,我们丢掉 nums[j] 24 | # 更新现有的 j 为 k,因为如果接下来有个数比 nums[j]大,那么一定比 nums[k] 大 25 | if nums[i] < nums[k] <= nums[j]: j = k 26 | # 如果 nums[k] 比 nums[i] 还小,我们更新 i 27 | if nums[k] <= nums[i]: i = k 28 | k += 1 29 | # 前面没有满足条件的数,返回 False 30 | return False -------------------------------------------------------------------------------- /LeetCode/2019-04-06-336-Palindrome-Pairs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-06 12:11:30 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-07 10:20:01 6 | 7 | 8 | class Solution: 9 | def palindromePairs(self, words: [str]) -> [[int]]: 10 | # 结果数组 11 | result = [] 12 | # 字典,用于获取索引 13 | worddict = {word: i for i, word in enumerate(words)} 14 | for i, word in enumerate(words): 15 | count = len(word) 16 | for j in range(count + 1): 17 | # 获取字段的前半部分,后半部分 18 | prefix, subfix = word[:j], word[j:] 19 | # 前半部分的反转,后半部分的反转 20 | reprefix, resubfix = prefix[::-1], subfix[::-1] 21 | # 如果前半部分是 palindrome 并且后半部分的反转在字典中 22 | if prefix == reprefix and resubfix in worddict: 23 | m = worddict[resubfix] 24 | # 不能取到字符本身 25 | if m != i: result.append([m, i]) 26 | # 如果后半部分是回文字符串,并且前半部分的逆序在字典中 27 | if j != count and subfix == resubfix and reprefix in worddict: 28 | result.append([i, worddict[reprefix]]) 29 | return result -------------------------------------------------------------------------------- /LeetCode/2019-04-07-337-House-Robber-III.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-07 10:43:47 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-07 11:00:22 6 | 7 | 8 | class Solution: 9 | def rob(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | return max(self.recursion(root)) 15 | 16 | def recursion(self, root): 17 | # result[0] 表示偷当前的房子,result[1] 表示不偷当前的房子 18 | if not root: return [0, 0] 19 | result = [0, 0] 20 | left = self.recursion(root.left) 21 | right = self.recursion(root.right) 22 | # 偷当前的房子 :result[0] :当前节点的值+ 左右子树中不偷子树根节点房子的最大值 23 | result[0] = root.val + left[1] + right[1] 24 | # 不偷当前的房子:result[1] 那么左右子树的根节点偷不偷都可以,选最大值 25 | result[1] = max(left[0], left[1]) + max(right[0], right[1]) 26 | return result -------------------------------------------------------------------------------- /LeetCode/2019-04-07-338-Counting-Bits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-07 11:54:35 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-07 12:22:34 6 | 7 | 8 | class Solution: 9 | def countBits(self, num: int) -> [int]: 10 | # 结果数组 11 | result, count = [0], 1 12 | while count * 2 <= num: 13 | # 从 resut 数组中索引对应的二进制数前面加 14 | # 一个 1 构成范围从 count 到 count*2 -1 的数(包括两端) 15 | for i in range(count, count * 2): 16 | result.append(1 + result[i - count]) 17 | count *= 2 18 | # 处理剩下的数 19 | for i in range(count, num + 1): 20 | result.append(1 + result[i - count]) 21 | return result -------------------------------------------------------------------------------- /LeetCode/2019-04-08-342-Power-of-Four.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-08 16:58:04 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-08 17:11:49 6 | 7 | 8 | class Solution: 9 | def isPowerOfFour(self, num: 'int') -> 'bool': 10 | # num 数字不为零 11 | # num 的二级制只有一个 1 12 | # num 中 1 的位置出现在第 1 位,或第 3 位,或第5 ... 位 13 | return num != 0 and num & ( 14 | num - 1) == 0 and num & 0b1010101010101010101010101010101 == num 15 | -------------------------------------------------------------------------------- /LeetCode/2019-04-08-343-Integer-Break.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-08 17:35:39 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-08 18:15:43 6 | 7 | 8 | class Solution: 9 | def integerBreak(self, n: int) -> int: 10 | # 前 5 个数的最大乘积 11 | tmp = [1, 2, 4, 6, 9] 12 | for i in range(5, n - 1): 13 | # 动态规划:第 i 个数 的最大乘积为 3 * 往前数第三个数 14 | tmp.append(3 * tmp[i - 3]) 15 | return tmp[n - 2] 16 | 17 | def integerBreak2(self, n: int) -> int: 18 | # 思路与上面的思路一致,优化了空间 19 | if n == 2: return 1 20 | if n == 3: return 2 21 | tmp = [4, 6, 9] 22 | for i in range(n - 6): 23 | tmp[i % 3] *= 3 24 | return tmp[(n - 1) % 3] 25 | -------------------------------------------------------------------------------- /LeetCode/2019-04-08-344-Reverse-String.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-08 21:47:07 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-08 21:54:18 6 | 7 | 8 | class Solution: 9 | def reverseString(self, s: [str]) -> None: 10 | """ 11 | Do not return anything, modify s in-place instead. 12 | """ 13 | # 中间位置的索引,最后一个位置的索引 14 | half, count = len(s) // 2, len(s) - 1 15 | for i in range(half): 16 | s[i], s[count - i] = s[count - i], s[i] -------------------------------------------------------------------------------- /LeetCode/2019-04-08-345-Reverse-Vowels-of-a-String.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-08 22:07:12 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-08 22:07:12 6 | 7 | 8 | class Solution: 9 | def reverseVowels(self, s: str) -> str: 10 | # 所有的元音字母 11 | vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} 12 | index = [i for i in range(len(s)) if s[i] in vowels] 13 | half, count = len(index) // 2, len(index) - 1 14 | s = list(s) 15 | # 交换所有的原因字母 16 | for i in range(half): 17 | s[index[i]], s[index[count - i]] = s[index[count - i]], s[index[i]] 18 | return ''.join(s) -------------------------------------------------------------------------------- /LeetCode/2019-04-09-347-Top-K-Frequent-Elements.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-09 12:37:36 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-09 15:57:00 6 | 7 | from collections import Counter 8 | 9 | 10 | class Solution: 11 | def topKFrequent(self, nums: [int], k: int) -> [int]: 12 | # 桶 13 | bucket = dict() 14 | # 构建字典,键位数字,值为该数字出现过的次数 15 | table = Counter(nums) 16 | result, count = [], 0 17 | # 以元素出现的次数位键,该次数下的所有元素构成的 List 为值 18 | for num, times in table.items(): 19 | if times not in bucket: bucket[times] = [] 20 | bucket[times].append(num) 21 | # 出现的最大次数 22 | maxtime = max(table.values()) 23 | 24 | for time in range(maxtime, 0, -1): 25 | # 如果该次数下有元素 26 | if time in bucket: 27 | # 提取当前次数下的所有元素到结果中 28 | result.extend(bucket[time]) 29 | count += len(bucket[time]) 30 | if count == k: break 31 | return result -------------------------------------------------------------------------------- /LeetCode/2019-04-09-349-Intersection-of-Two-Arrays.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-09 16:11:29 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-09 16:15:56 6 | 7 | 8 | class Solution: 9 | def intersection(self, nums1: [int], nums2: [int]) -> [int]: 10 | # python 内置集合运算 11 | return list(set(nums1) & set(nums2)) -------------------------------------------------------------------------------- /LeetCode/2019-04-09-350-Intersection-of-Two-Arrays-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-04-09 16:31:05 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-04-09 16:43:17 6 | 7 | 8 | class Solution: 9 | def intersect(self, nums1: [int], nums2: [int]) -> [int]: 10 | nums1.sort(), nums2.sort() 11 | count1, count2 = len(nums1), len(nums2) 12 | i, j, res = 0, 0, [] 13 | # 相同的部分一定在前面 14 | while i < count1 and j < count2: 15 | # 如果相等,添加到结果数组中 16 | if nums1[i] == nums2[j]: 17 | res.append(nums1[i]) 18 | i, j = i + 1, j + 1 19 | # 如果数组二的数大,将数组一的索引自增一次 20 | elif nums1[i] < nums2[j]: 21 | i += 1 22 | # 如果数组一的数大,将数组二的索引自增一次 23 | elif nums1[i] > nums2[j]: 24 | j += 1 25 | 26 | return res -------------------------------------------------------------------------------- /LeetCode/2019-06-02-354-Russian-Doll-Envelopes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-02 13:04:40 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-02 15:26:38 6 | 7 | import bisect 8 | from typing import List 9 | 10 | 11 | class Solution: 12 | def maxEnvelopes(self, envelopes: List[List[int]]) -> int: 13 | 14 | if not envelopes: return 0 15 | 16 | # 以信封的宽度和高度排序,宽度小的在前,宽度一样,高度大的在前 17 | envelopes.sort(key=lambda x: (x[0], -x[1])) 18 | 19 | tails = list() 20 | 21 | # 所有的高度构成一个数组,寻找此数组中的连续最长递增序列 22 | for _, num in envelopes: 23 | index = bisect.bisect_left(tails, num) 24 | if index == len(tails): 25 | tails.append(num) 26 | else: 27 | tails[index] = num 28 | return len(tails) 29 | -------------------------------------------------------------------------------- /LeetCode/2019-06-04-357-Count-Numbers-with-Unique-Digits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-04 13:40:45 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-04 14:57:30 6 | 7 | 8 | class Solution: 9 | def countNumbersWithUniqueDigits(self, n: int) -> int: 10 | # n 最大为 9 11 | n = n if n < 10 else 9 12 | # 当 n 为 0 时,只有 0 满足条件 13 | if n == 0: return 1 14 | # count 记录当限定位数为 i 时,能够形成的做多的 unique number 个数 15 | # res 记录总和 16 | count, res = 9, 10 17 | for i in range(2, n + 1): 18 | count *= 11 - i 19 | res += count 20 | 21 | return res 22 | -------------------------------------------------------------------------------- /LeetCode/2019-06-13-365-Water-and-Jug-Problem.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-13 11:03:29 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-13 12:20:44 6 | 7 | 8 | class Solution: 9 | def canMeasureWater(self, x: int, y: int, z: int) -> bool: 10 | if z == 0 or (z <= x + y and z % self.__gcd(x, y) == 0): 11 | return True 12 | return False 13 | 14 | def __gcd(self, x: int, y: int) -> int: 15 | return x if y == 0 else self.__gcd(y, x % y) 16 | -------------------------------------------------------------------------------- /LeetCode/2019-06-13-367-Valid-Perfect-Square.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-13 14:35:51 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-13 14:42:06 6 | 7 | 8 | class Solution: 9 | def isPerfectSquare(self, num: int) -> bool: 10 | left, right = 1, num 11 | while left <= right: 12 | middle = left + ((right - left) >> 1) 13 | tmp = middle ** 2 14 | if tmp == num: 15 | return True 16 | elif tmp < num: 17 | left = middle + 1 18 | else: 19 | right = middle - 1 20 | 21 | return False -------------------------------------------------------------------------------- /LeetCode/2019-06-14-368-Largest-Divisible-Subset.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-14 11:17:30 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-14 13:09:36 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def largestDivisibleSubset(self, nums: List[int]) -> List[int]: 12 | if not nums: return [] 13 | 14 | max_count, end = 1, 0 15 | count, path = [1] * len(nums), [0] * len(nums) 16 | 17 | nums.sort() 18 | for i in range(1, len(nums)): 19 | for j in range(i - 1, -1, -1): 20 | if nums[i] % nums[j] == 0 and count[j] + 1 > count[i]: 21 | count[i] = count[j] + 1 22 | path[i] = j 23 | if count[i] >= max_count: 24 | max_count = count[i] 25 | end = i 26 | 27 | res = [] 28 | for _ in range(max_count): 29 | res.append(nums[end]) 30 | end = path[end] 31 | 32 | return res -------------------------------------------------------------------------------- /LeetCode/2019-06-27-372-Super-Pow.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-27 20:41:08 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-27 21:26:34 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def superPow(self, a: int, b: List[int]) -> int: 12 | res = 1 13 | for num in b: 14 | res = self.pow(res, 10) * self.pow(a, num) % 1337 15 | return res 16 | 17 | def pow(self, x: int, n: int) -> int: 18 | if n == 0: 19 | return 1 20 | if n == 1: 21 | return x % 1337 22 | return x**n % 1337 -------------------------------------------------------------------------------- /LeetCode/2019-06-28-374-Guess-Number-Higher-or-Lower.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-28 16:24:44 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-28 16:29:54 6 | 7 | class Solution(object): 8 | def guessNumber(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | left, right = 1, n 14 | 15 | num = left + ((right - left) >> 1) 16 | res = guess(num) 17 | if res == 0: return num 18 | 19 | while res: 20 | if res == 1: 21 | left = num + 1 22 | if res == -1: 23 | right = num - 1 24 | num = left + ((right - left) >> 1) 25 | res = guess(num) 26 | 27 | return num -------------------------------------------------------------------------------- /LeetCode/2019-06-30-375-Guess-Number-Higher-or-Lower-II.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-06-30 10:54:08 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-06-30 14:56:28 6 | 7 | 8 | class Solution(object): 9 | def getMoneyAmount(self, n): 10 | """ 11 | :type n: int 12 | :rtype: int 13 | """ 14 | 15 | dp = [[0] * (n + 1) for _ in range(n + 1)] 16 | 17 | for right in range(1, n + 1): 18 | for left in range(right - 1, 0, -1): 19 | dp[left][right] = min(x + max(dp[left][x - 1], dp[x + 1][right]) for x in range(left, right)) 20 | 21 | return dp[1][n] -------------------------------------------------------------------------------- /LeetCode/2019-07-13-376-Wiggle-Subsequence.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-07-13 07:52:43 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-07-13 08:15:12 6 | 7 | 8 | from typing import List 9 | 10 | 11 | class Solution: 12 | def wiggleMaxLength(self, nums: List[int]) -> int: 13 | if not nums: return 0 14 | 15 | dp = [[0, 1] for _ in range(len(nums))] 16 | 17 | for i in range(1, len(nums)): 18 | for j in range(i, -1, -1): 19 | diff = nums[i] - nums[j] 20 | if diff * dp[j][0] <= 0 and diff != 0 and (dp[j][1] + 1) > dp[i][1]: 21 | dp[i][0] = diff // abs(diff) 22 | dp[i][1] = dp[j][1] + 1 23 | break 24 | 25 | return dp[-1][1] 26 | 27 | -------------------------------------------------------------------------------- /LeetCode/2019-07-20-377-Combination-Sum-IV.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-07-20 07:58:21 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-07-20 08:33:22 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def combinationSum4(self, nums: List[int], target: int) -> int: 12 | if not nums: 13 | return 0 14 | dp = [0 for _ in range(target + 1)] 15 | dp[0] = 1 16 | for i in range(1, target + 1): 17 | # dp[i] = sum(map(lambda j: dp[i - j], filter(lambda j: i - j >= 0, nums))) 18 | dp[i] = sum(dp[i - j] for j in nums if i - j >= 0) 19 | 20 | return dp[-1] 21 | -------------------------------------------------------------------------------- /LeetCode/2019-07-30-382-Linked-List-Random-Node.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-07-30 07:41:23 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-07-30 07:46:44 6 | 7 | import random 8 | # Definition for singly-linked list. 9 | 10 | 11 | class ListNode: 12 | def __init__(self, x): 13 | self.val = x 14 | self.next = None 15 | 16 | 17 | class Solution: 18 | 19 | def __init__(self, head: ListNode): 20 | """ 21 | @param head The linked list's head. 22 | Note that the head is guaranteed to be not null, so it contains at least one node. 23 | """ 24 | self.head = head 25 | 26 | def getRandom(self) -> int: 27 | """ 28 | Returns a random node's value. 29 | """ 30 | head = self.head 31 | num = head.val 32 | node = head.next 33 | count = 1 34 | while node: 35 | count += 1 36 | if random.randint(1, count) % count == 0: 37 | num = node.val 38 | node = node.next 39 | 40 | return num 41 | -------------------------------------------------------------------------------- /LeetCode/2019-07-30-383-Ransom-Note.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-07-30 07:58:59 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-07-30 08:03:10 6 | 7 | from collections import Counter 8 | 9 | 10 | class Solution: 11 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 12 | return not (Counter(ransomNote) - Counter(magazine)) 13 | -------------------------------------------------------------------------------- /LeetCode/2019-08-03-384-Shuffle-an-Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-03 10:48:30 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-03 10:53:15 6 | 7 | import copy 8 | import random 9 | 10 | from typing import List 11 | 12 | 13 | class Solution: 14 | 15 | def __init__(self, nums: List[int]): 16 | self.shuffle_ = nums 17 | self.original = copy.copy(nums) 18 | 19 | def reset(self) -> List[int]: 20 | """ 21 | Resets the array to its original configuration and return it. 22 | """ 23 | return self.original 24 | 25 | def shuffle(self) -> List[int]: 26 | """ 27 | Returns a random shuffling of the array. 28 | """ 29 | random.shuffle(self.shuffle_) 30 | return self.shuffle_ 31 | -------------------------------------------------------------------------------- /LeetCode/2019-08-03-386-Lexicographical-Numbers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-03 15:05:01 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-03 15:32:23 6 | 7 | 8 | from typing import List 9 | 10 | 11 | class Solution: 12 | def lexicalOrder(self, n: int) -> List[int]: 13 | start = 1 14 | for _ in range(1, n + 1): 15 | yield start 16 | if start * 10 <= n: 17 | start *= 10 18 | else: 19 | start = start + 1 if start < n else start // 10 + 1 20 | while not start % 10: 21 | start //= 10 22 | return 23 | -------------------------------------------------------------------------------- /LeetCode/2019-08-03-387-First-Unique-Character-in-a-String.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-03 21:18:36 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-03 21:35:58 6 | 7 | from collections import Counter 8 | 9 | 10 | class Solution: 11 | def firstUniqChar(self, s: str) -> int: 12 | res = len(s) 13 | for char in 'abcdefghijklmnopqrstuvwxyz': 14 | left, right = s.find(char), s.rfind(char) 15 | if left != -1 and left == right: 16 | res = min(res, left) 17 | 18 | return -1 if res == len(s) else res 19 | -------------------------------------------------------------------------------- /LeetCode/2019-08-04-388-Longest-Absolute-File-Path.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-04 22:45:02 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-04 23:08:14 6 | 7 | 8 | class Solution(object): 9 | def lengthLongestPath(self, input): 10 | 11 | max_length = 0 12 | dot, blank = '.', '' 13 | stack = [(-1, 0)] # -1 表示目录深度,0 表示当前所有字符串的长度 14 | 15 | for name in input.split("\n"): 16 | level = name.count('\t') 17 | name = name.replace('\t', blank) 18 | # 去当前的目录深度 19 | while stack and level <= stack[-1][0]: # 如果一样深,或者当前目录的层级更浅 20 | stack.pop() 21 | if dot not in name: # 如果是目录 22 | stack.append((level, len(name) + stack[-1][1] + 1)) 23 | else: # 如果是文件 24 | max_length = max(max_length, len(name) + stack[-1][1]) 25 | 26 | return max_length 27 | -------------------------------------------------------------------------------- /LeetCode/2019-08-04-389-Find-the-Difference.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-04 23:09:19 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-04 23:09:30 6 | 7 | import operator 8 | from functools import reduce 9 | 10 | 11 | class Solution: 12 | def findTheDifference(self, s: str, t: str) -> str: 13 | return chr(reduce(operator.xor, map(ord, s + t), 0)) 14 | 15 | 16 | class Solution2: 17 | def findTheDifference(self, s: str, t: str) -> str: 18 | return chr(sum(map(ord, t)) - sum(map(ord, s))) 19 | -------------------------------------------------------------------------------- /LeetCode/2019-08-10-390-Elimination-Game.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-10 08:12:23 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-10 08:31:09 6 | 7 | 8 | class Solution: 9 | def lastRemaining(self, n: int) -> int: 10 | return self.leftright(n) 11 | 12 | def leftright(self, n): 13 | if n <= 2: 14 | return n 15 | if n & 1 == 1: # 奇数 16 | return 2 * self.rightleft((n - 1) >> 1) 17 | else: 18 | return 2 * self.rightleft(n >> 1) 19 | 20 | def rightleft(self, n): 21 | if n <= 2: 22 | return 1 23 | if n & 1 == 1: 24 | return 2 * self.leftright((n - 1) >> 1) 25 | else: 26 | return 2 * self.leftright(n >> 1) - 1 27 | -------------------------------------------------------------------------------- /LeetCode/2019-08-10-391-Perfect-Rectangle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-10 12:09:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-10 12:09:46 6 | 7 | from typing import List 8 | from collections import defaultdict 9 | 10 | 11 | class Solution: 12 | def isRectangleCover(self, rectangles: List[List[int]]) -> bool: 13 | point_table = defaultdict(int) 14 | 15 | area = 0 16 | for line in rectangles: 17 | leftx, lefty, rightx, righty = line 18 | point_table[(leftx, lefty)] += 1 19 | point_table[(rightx, righty)] += 1 20 | point_table[(leftx, righty)] += 1 21 | point_table[(rightx, lefty)] += 1 22 | area += (rightx - leftx) * (righty - lefty) 23 | 24 | vertex = [x for x in point_table if point_table[x] & 1] 25 | if len(vertex) != 4: 26 | return False 27 | 28 | min_, max_ = min(vertex), max(vertex) 29 | (minx, miny), (maxx, maxy) = min_, max_ 30 | 31 | return (maxx - minx) * (maxy - miny) == area 32 | -------------------------------------------------------------------------------- /LeetCode/2019-08-11-41-First-Missing-Positive.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-11 08:21:24 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-11 09:52:45 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def firstMissingPositive(self, nums: List[int]) -> int: 12 | length = len(nums) 13 | 14 | if not nums: 15 | return 1 16 | for i in range(length): 17 | while 0 < nums[i] <= length and nums[nums[i] - 1] != nums[i]: 18 | n = nums[i] - 1 19 | nums[i], nums[n] = nums[n], nums[i] 20 | 21 | for i, n in enumerate(nums, 1): 22 | if i != n: 23 | return i 24 | else: 25 | return n + 1 26 | 27 | return 28 | -------------------------------------------------------------------------------- /LeetCode/2019-08-17-392-Is-Subsequence.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-17 13:53:03 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-17 14:34:16 6 | 7 | import bisect 8 | from collections import defaultdict 9 | 10 | 11 | class Solution: 12 | def __init__(self): 13 | self.__isinit = False 14 | self.__dict = defaultdict(list) 15 | 16 | def __build(self, t): 17 | for index, char in enumerate(t): 18 | self.__dict[char].append(index) 19 | self.__isinit = True 20 | 21 | def isSubsequence(self, s: str, t: str) -> bool: 22 | if not self.__isinit: 23 | self.__build(t) 24 | 25 | next_ = -1 26 | for char in s: 27 | next_ = self.__check(char, next_) 28 | if next_ == -1: 29 | return False 30 | 31 | return True 32 | 33 | def __check(self, char, index): 34 | if char not in self.__dict: 35 | return -1 36 | next_ = bisect.bisect_right(self.__dict[char], index) 37 | return self.__dict[char][next_] if next_ < len(self.__dict[char]) else -1 38 | -------------------------------------------------------------------------------- /LeetCode/2019-08-18-38-Count-and-Say.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-18 09:49:01 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-18 09:51:29 6 | 7 | from itertools import groupby 8 | 9 | 10 | class Solution: 11 | def countAndSay(self, n: int) -> str: 12 | result = '1' 13 | for _ in range(n - 1): 14 | result = ''.join([str(len(list(g))) + key for key, g in groupby(result)]) 15 | 16 | return result 17 | -------------------------------------------------------------------------------- /LeetCode/2019-08-24-393-UTF-8-Validation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-24 10:55:33 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-24 11:59:50 6 | 7 | 8 | import re 9 | from typing import List 10 | 11 | 12 | class Solution: 13 | def validUtf8(self, data: List[int]) -> bool: 14 | 15 | next_ = 0 16 | pattern = re.compile("0b(.*?)0.*") 17 | while next_ != -1 and next_ < len(data): 18 | next_ = self.__check(next_, data, pattern) 19 | 20 | return False if next_ == -1 else True 21 | 22 | def __check(self, start, data, pattern): 23 | 24 | num = data[start] 25 | if not num & 0b10000000: 26 | return start + 1 27 | elif num & 0b11000000 == 0b10000000: 28 | return -1 29 | else: 30 | match = pattern.match(str(bin(num))) 31 | if not match: 32 | return -1 33 | length = match.span(1)[1] - match.span(1)[0] 34 | end = start + length 35 | if length > 4 or end > len(data): 36 | return -1 37 | if all(map(lambda i: data[i] & 0b11000000 == 0b10000000, range(start + 1, end))): 38 | return start + length 39 | return -1 40 | -------------------------------------------------------------------------------- /LeetCode/2019-08-25-394-Decode-String.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-25 09:19:03 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-25 10:17:59 6 | 7 | 8 | class Solution: 9 | def decodeString(self, s: str) -> str: 10 | num, chr_stack, num_stack = 0, [], [] 11 | for char in s: 12 | if char.isdigit(): 13 | num = num * 10 + int(char) 14 | elif char == '[': 15 | num_stack.append(num) 16 | chr_stack.append("[") 17 | num = 0 18 | elif char == ']': 19 | tmp = [] 20 | while chr_stack and chr_stack[-1] != '[': 21 | tmp.append(chr_stack.pop()) 22 | chr_stack.pop() 23 | chr_stack.extend(reversed(tmp * num_stack.pop())) 24 | else: 25 | chr_stack.append(char) 26 | 27 | return "".join(chr_stack) 28 | 29 | -------------------------------------------------------------------------------- /LeetCode/2019-08-27-395-Longest-Substring-with-At-Least-K-Repeating-Characters.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-27 21:07:09 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-28 08:40:37 6 | 7 | from collections import Counter 8 | 9 | 10 | class Solution: 11 | def longestSubstring(self, s: str, k: int) -> int: 12 | 13 | for key, v in Counter(s).items(): 14 | if v < k: 15 | return max(self.longestSubstring(sub, k) for sub in s.split(key)) 16 | return len(s) 17 | -------------------------------------------------------------------------------- /LeetCode/2019-08-28-396-Rotate-Function.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-28 21:06:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-28 21:41:13 6 | 7 | 8 | from typing import List 9 | 10 | 11 | class Solution: 12 | def maxRotateFunction(self, A: List[int]) -> int: 13 | sum_, count = sum(A), len(A) 14 | product = sum(map(lambda x: x[0] * x[1], enumerate(A))) 15 | res = product 16 | 17 | for i in A[:-1]: 18 | product = product - sum_ + count * i 19 | res = max(res, product) 20 | 21 | return res 22 | -------------------------------------------------------------------------------- /LeetCode/2019-08-29-397-Integer-Replacement.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-29 21:06:55 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-29 21:41:26 6 | 7 | 8 | class Solution: 9 | def integerReplacement(self, n: int) -> int: 10 | count = 0 11 | while n > 1: 12 | count += 1 13 | if not n % 2: 14 | n >>= 1 15 | elif n & 0b11 == 0b11 and n != 0b11: 16 | n += 1 17 | else: 18 | n -= 1 19 | 20 | return count 21 | -------------------------------------------------------------------------------- /LeetCode/2019-08-30-398-Random-Pick-Index.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-08-30 19:55:46 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-08-30 20:17:06 6 | 7 | import heapq 8 | import random 9 | 10 | from typing import List 11 | 12 | 13 | class Solution: 14 | 15 | def __init__(self, nums: List[int]): 16 | self.arrays = nums 17 | 18 | def pick(self, target: int) -> int: 19 | hep = [] 20 | for i, v in enumerate(self.arrays): 21 | if v == target: 22 | heapq.heappush(hep, (random.random(), i)) 23 | _, index = heapq.heappop(hep) 24 | return index 25 | 26 | def pick2(self, target: int) -> int: 27 | 28 | n, res = 0, 0 29 | for x in filter(lambda x: x[1] == target, enumerate(self.arrays)): 30 | n += 1 31 | if random.randint(1, n) == n: 32 | res = x[0] 33 | 34 | return res 35 | -------------------------------------------------------------------------------- /LeetCode/2019-09-02-400-Nth-Digit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-09-02 07:41:16 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-09-02 07:55:03 6 | 7 | 8 | class Solution: 9 | def findNthDigit(self, n: int) -> int: 10 | 11 | a, b, start = self.__find_index(n) 12 | return str(start + a - 1)[-1] if not b else str(start + a)[b - 1] 13 | 14 | def __find_index(self, n: int) -> (int, int, int): 15 | 16 | cnt_digit, cnt_zone, start = 1, 9, 1 17 | while n > cnt_zone * cnt_digit: 18 | n -= cnt_zone * cnt_digit 19 | cnt_digit += 1 20 | cnt_zone *= 10 21 | start *= 10 22 | a, b = divmod(n, cnt_digit) 23 | 24 | return a, b, start 25 | -------------------------------------------------------------------------------- /LeetCode/2019-09-03-401-Binary-Watch.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-09-03 22:35:31 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-09-04 08:59:55 6 | 7 | from typing import List 8 | from itertools import combinations 9 | 10 | 11 | class Solution: 12 | def readBinaryWatch(self, num: int) -> List[str]: 13 | minutes = {i: 2**i for i in range(6)} 14 | hours = {i: 2**(i - 6) for i in range(6, 10)} 15 | times = map(lambda x: self.__transfer(x, minutes, hours), combinations(list(range(10)), num)) 16 | 17 | return filter(lambda x: x is not None, times) 18 | 19 | def __transfer(self, com, minutes, hours): 20 | minute = sum(map(lambda x: minutes.get(x, 0), com)) 21 | hour = sum(map(lambda x: hours.get(x, 0), com)) 22 | return "{}:{:02d}".format(hour, minute) if hour <= 11 and minute <= 59 else None 23 | -------------------------------------------------------------------------------- /LeetCode/2019-09-07-402-Remove-K-Digits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-09-07 07:59:40 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-09-07 09:10:06 6 | 7 | 8 | class Solution: 9 | def removeKdigits(self, num: str, k: int) -> str: 10 | 11 | cnt, stack = 0, [] 12 | for n in num: 13 | while cnt < k and stack and n < stack[-1]: 14 | cnt += 1 15 | stack.pop() 16 | if n == "0" and not stack: 17 | continue 18 | stack.append(n) 19 | 20 | return "".join(stack[0:len(stack) - (k - cnt)]) or "0" 21 | -------------------------------------------------------------------------------- /LeetCode/2019-09-08-403-Frog-Jump.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-09-08 08:01:56 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-09-08 09:07:52 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def canCross(self, stones: List[int]) -> bool: 12 | stages = {x: set() for x in stones} 13 | stages[0] = {0} 14 | end = stones[-1] 15 | 16 | for key in stones: 17 | steps = stages[key] 18 | if not steps: 19 | return False 20 | if any(map(lambda step: self.__jump(stages, step, key, end), steps)): 21 | return True 22 | 23 | return False 24 | 25 | def __jump(self, stages, step, start, end): 26 | 27 | steps = (step - 1, step, step + 1) 28 | for s in filter(lambda x: x > 0 and start + x in stages, steps): 29 | stages[start + s].add(s) 30 | if start + s == end: 31 | return True 32 | 33 | return False 34 | -------------------------------------------------------------------------------- /LeetCode/2019-09-14-404-Sum-of-Left-Leaves.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-09-14 08:23:43 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-09-14 08:33:06 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def sumOfLeftLeaves(self, root: TreeNode) -> int: 19 | self.res = 0 20 | self.__traversal(root) 21 | return self.res 22 | 23 | def __traversal(self, root): 24 | if not root: 25 | return 26 | if root.left and not root.left.left and not root.left.right: 27 | self.res += root.left.val 28 | self.__traversal(root.left) 29 | self.__traversal(root.right) 30 | -------------------------------------------------------------------------------- /LeetCode/2019-09-14-405-Convert-a-Number-to-Hexadecimal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-09-14 10:47:02 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-09-14 11:07:11 6 | 7 | 8 | class Solution: 9 | def toHex(self, num: int) -> str: 10 | if num < 0: 11 | num = 0xffffffff + 1 + num 12 | 13 | transfer = "0123456789abcdef" 14 | res = [] 15 | while num: 16 | res.append(transfer[num % 16]) 17 | num >>= 4 18 | 19 | return ''.join(reversed(res)) or '0' 20 | -------------------------------------------------------------------------------- /LeetCode/2019-10-03-409-Longest-Palindrome.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-10-03 14:41:25 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-10-03 14:56:07 6 | 7 | from collections import Counter 8 | 9 | 10 | class Solution: 11 | def longestPalindrome(self, s: str) -> int: 12 | cnt_dict = Counter(s) 13 | a = sum(cnt_dict.values()) 14 | b = sum(1 for x in cnt_dict.values() if x & 1) 15 | 16 | return a if b == 0 else a - b + 1 17 | -------------------------------------------------------------------------------- /LeetCode/2019-10-05-412-Fizz-Buzz.md: -------------------------------------------------------------------------------- 1 | # LeetCode 412. Fizz Buzz 2 | 3 | ## Description 4 | 5 | Write a program that outputs the string representation of numbers from 1 to n. 6 | 7 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 8 | 9 | Example: 10 | 11 | ```py 12 | n = 15, 13 | 14 | Return: 15 | [ 16 | "1", 17 | "2", 18 | "Fizz", 19 | "4", 20 | "Buzz", 21 | "Fizz", 22 | "7", 23 | "8", 24 | "Fizz", 25 | "Buzz", 26 | "11", 27 | "Fizz", 28 | "13", 29 | "14", 30 | "FizzBuzz" 31 | ] 32 | ``` 33 | 34 | ### 思路 35 | 36 | ```py 37 | # -*- coding: utf-8 -*- 38 | # @Author: 何睿 39 | # @Create Date: 2019-10-05 20:01:30 40 | # @Last Modified by: 何睿 41 | # @Last Modified time: 2019-10-05 20:02:43 42 | 43 | 44 | from typing import List 45 | 46 | 47 | class Solution: 48 | def fizzBuzz(self, n: int) -> List[str]: 49 | return ['FizzBuzz' if not i % 15 else 'Buzz' if not i % 5 else 'Fizz' if not i % 3 else str(i) for i in range(1, n + 1)] 50 | ``` 51 | 52 | ©本文首发于 何睿的博客 ,欢迎转载,转载需保留 [文章来源](https://ruicore.cn/leetcode-412-fizz-buzz/) ,作者信息和本声明. 53 | -------------------------------------------------------------------------------- /LeetCode/2019-10-05-412-Fizz-Buzz.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-10-05 20:01:30 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-10-05 20:02:43 6 | 7 | 8 | from typing import List 9 | 10 | 11 | class Solution: 12 | def fizzBuzz(self, n: int) -> List[str]: 13 | return ['FizzBuzz' if not i % 15 else 'Buzz' if not i % 5 else 'Fizz' if not i % 3 else str(i) for i in range(1, n + 1)] 14 | -------------------------------------------------------------------------------- /LeetCode/2019-10-13-413-Arithmetic-Slices.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-10-13 18:47:35 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-10-13 19:45:52 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def numberOfArithmeticSlices(self, A: List[int]) -> int: 12 | 13 | if len(A) < 3: 14 | return 0 15 | 16 | dp = [0 for _ in range(len(A))] 17 | d = A[1] - A[0] 18 | start = 2 19 | 20 | next_ = self._count(A, d, dp, start) 21 | while next_ < len(A): 22 | d = A[next_] - A[next_ - 1] 23 | start = next_ + 1 24 | next_ = self._count(A, d, dp, start) 25 | 26 | return sum(dp) 27 | 28 | def _count(self, A, d, dp, start): 29 | 30 | for i in range(start, len(A)): 31 | if A[i] - A[i - 1] == d: 32 | dp[i] = dp[i - 1] + 1 33 | else: 34 | return i 35 | 36 | return len(A) 37 | -------------------------------------------------------------------------------- /LeetCode/2019-10-13-414-Third-Maximum-Number.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-10-13 20:27:38 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-10-13 20:55:02 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def thirdMax(self, nums: List[int]) -> int: 12 | bucket = [float("-inf"), float("-inf"), float("-inf")] 13 | for num in nums: 14 | for i in range(3): 15 | if num > bucket[i]: 16 | self._update(i, num, bucket) 17 | break 18 | if num == bucket[i]: 19 | break 20 | 21 | return bucket[-1] if bucket[-1] != float("-inf") else bucket[0] 22 | 23 | def _update(self, i, num, bucket): 24 | if i == 0: 25 | bucket[1], bucket[2] = bucket[0], bucket[1] 26 | bucket[0] = num 27 | elif i == 1: 28 | bucket[2] = bucket[1] 29 | bucket[1] = num 30 | elif i == 2: 31 | bucket[2] = num 32 | -------------------------------------------------------------------------------- /LeetCode/2019-10-14-415-Add-Strings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-10-14 19:42:33 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-10-14 19:47:43 6 | 7 | 8 | class Solution: 9 | def addStrings(self, num1: str, num2: str) -> str: 10 | return str(self._int(num1) + self._int(num2)) 11 | 12 | def _int(self, num): 13 | res = 0 14 | cnt = 1 15 | for s in num[::-1]: 16 | res += cnt * (ord(s) - ord('0')) 17 | cnt *= 10 18 | return res 19 | -------------------------------------------------------------------------------- /LeetCode/2019-10-26-416-Partition-Equal-Subset-Sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-10-26 09:30:29 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-10-26 10:18:19 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def canPartition(self, nums: List[int]) -> bool: 12 | sum_nums = sum(nums) 13 | if sum_nums & 1 or max(nums) > (sum_nums >> 1): 14 | return 15 | 16 | half_sum = sum_nums >> 1 17 | nums.sort(reverse=True) 18 | dp = [[False] * (half_sum + 1) for _ in range(2)] 19 | dp[0][0] = True 20 | dp[0][nums[0]] = True 21 | 22 | for i in range(1, len(nums)): 23 | idx = i % 2 24 | for j in range(nums[i]): 25 | dp[idx][j] = dp[idx - 1][j] 26 | for j in range(nums[i], half_sum + 1): 27 | dp[idx][j] = dp[idx - 1][j] if dp[idx - 1][j] else dp[idx - 1][j - nums[i]] 28 | if dp[idx][-1]: 29 | return True 30 | 31 | return dp[-1][-1] 32 | -------------------------------------------------------------------------------- /LeetCode/2019-11-30-421-Maximum-XOR-of-Two-Numbers-in-an-Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-11-30 09:35:38 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-11-30 10:10:40 6 | 7 | from typing import List 8 | 9 | 10 | class Solution: 11 | def findMaximumXOR(self, nums: List[int]) -> int: 12 | res, mask = 0, 0 13 | for i in range(31, -1, -1): 14 | mask |= (1 << i) 15 | prefix = set(num & mask for num in nums) 16 | tmp = res | (1 << i) 17 | for s in prefix: 18 | if tmp ^ s in prefix: 19 | res = tmp 20 | break 21 | 22 | return res 23 | -------------------------------------------------------------------------------- /LeetCode/2019-11-30-423-Reconstruct-Original-Digits-from-English.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-11-30 13:15:30 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-11-30 13:28:08 6 | 7 | 8 | from collections import Counter 9 | 10 | 11 | class Solution: 12 | def originalDigits(self, s: str) -> str: 13 | res = {} 14 | count = Counter(s) 15 | for key, char in zip([0, 2, 4, 6, 8], ['z', 'w', 'u', 'x', 'g']): 16 | res[key] = count.get(char, 0) 17 | res[1] = count.get('o', 0) - res[0] - res[2] - res[4] 18 | res[3] = count.get('h', 0) - res[8] 19 | res[5] = count.get("f", 0) - res[4] 20 | res[7] = count.get('s', 0) - res[6] 21 | res[9] = count.get('i', 0) - res[6] - res[8] - res[5] 22 | 23 | return ''.join(str(num) * res[num] for num in range(0, 10)) 24 | -------------------------------------------------------------------------------- /LeetCode/2019-11-30-424-Longest-Repeating-Character-Replacement.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-11-30 16:32:47 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-11-30 16:44:05 6 | 7 | from collections import defaultdict 8 | 9 | 10 | class Solution: 11 | def characterReplacement(self, s: str, k: int) -> int: 12 | window_count = defaultdict(int) 13 | res, left, right, count_s = 0, 0, 0, len(s) 14 | 15 | max_repeat_count = 0 16 | while right < count_s: 17 | window_count[s[right]] += 1 18 | max_repeat_count = max(max_repeat_count, window_count[s[right]]) 19 | 20 | while right - left + 1 - max_repeat_count > k: 21 | window_count[s[left]] -= 1 22 | max_repeat_count = max(max_repeat_count, window_count[s[left]]) 23 | left += 1 24 | 25 | res = max(res, right - left + 1) 26 | right += 1 27 | 28 | return res 29 | 30 | -------------------------------------------------------------------------------- /LeetCode/2019-12-28-429-N-ary-Tree-Level-Order-Traversal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-12-28 21:23:06 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-12-28 21:34:42 6 | 7 | 8 | from typing import List 9 | from collections import deque 10 | 11 | 12 | class Solution: 13 | def levelOrder(self, root: 'Node') -> List[List[int]]: 14 | if not root: 15 | return [] 16 | result = [] 17 | queue = deque([root]) 18 | 19 | while queue: 20 | tmp = [] 21 | count = len(queue) 22 | for _ in range(count): 23 | node = queue.popleft() 24 | tmp.append(node.val) 25 | if node.children: 26 | queue.extend(node.children) 27 | result.append(tmp) 28 | 29 | return result 30 | -------------------------------------------------------------------------------- /LeetCode/2019-12-29-430-Flatten-a-Multilevel-Doubly-Linked-List.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-12-29 10:57:03 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-12-29 11:05:17 6 | 7 | 8 | class Node: 9 | def __init__(self, val, prev, next, child): 10 | self.val = val 11 | self.prev = prev 12 | self.next = next 13 | self.child = child 14 | 15 | 16 | class Solution: 17 | def flatten(self, head: 'Node') -> 'Node': 18 | current = head 19 | while current: 20 | if current.child: 21 | _next = current.next # 当前节点的后一个节点 22 | last = current.child # 当前节点的自节点 23 | while last.next: 24 | last = last.next # 如果有子节点,找到子节点的最后一个节点 25 | current.next = current.child 26 | current.next.prev = current # 将自节点向上提高一层 27 | current.child = None 28 | last.next = _next 29 | if _next: 30 | _next.prev = last 31 | current = current.next 32 | 33 | return head 34 | -------------------------------------------------------------------------------- /LeetCode/2020-01-30-433-Minimum-Genetic-Mutation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2020-01-30 11:43:15 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2020-01-30 12:11:17 6 | 7 | import collections 8 | from typing import List 9 | 10 | 11 | class Solution: 12 | def _valid_next(self, current: str, next_: str): 13 | return sum(1 for c, n in zip(current, next_) if c != n) == 1 14 | 15 | def minMutation(self, start: str, end: str, bank: List[str]) -> int: 16 | queue = collections.deque() 17 | queue.append([start, '', 0]) 18 | 19 | while queue: 20 | current, previous, steps = queue.popleft() 21 | if current == end: 22 | return steps 23 | for item in bank: 24 | if item != previous and self._valid_next(current, item): 25 | queue.append([item, current, steps + 1]) 26 | 27 | return -1 28 | -------------------------------------------------------------------------------- /LeetCode/2020-03-31-435-Non-overlapping-Intervals.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2020-03-31 19:18:41 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2020-04-01 15:23:00 6 | rom typing import List 7 | 8 | 9 | class Solution: 10 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 11 | intervals = sorted(intervals, key=lambda x: x[0]) 12 | count = 0 13 | last = 0 14 | for i in range(1, len(intervals)): 15 | if intervals[last][1] > intervals[i][0]: 16 | count += 1 17 | if intervals[last][1] >= intervals[i][1]: 18 | last = i 19 | else: 20 | last = i 21 | 22 | return count 23 | -------------------------------------------------------------------------------- /LeetCode/2020-05-01-437-Path-Sum-III.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2020-05-01 17:30:03 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2020-05-01 19:54:16 6 | 7 | # Definition for a binary tree node. 8 | 9 | 10 | class TreeNode: 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | 17 | class Solution: 18 | def pathSum(self, root: TreeNode, sum: int) -> int: 19 | if not root: 20 | return 0 21 | 22 | return self.sumRoot(root, 0, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) 23 | 24 | def sumRoot(self, root, pre, sum_): 25 | 26 | if not root: 27 | return 0 28 | pre += root.val 29 | 30 | left = self.sumRoot(root.left, pre, sum_) 31 | right = self.sumRoot(root.right, pre, sum_) 32 | 33 | return (pre == sum_) + left + right 34 | -------------------------------------------------------------------------------- /LeetCode/C/2017-11-21-Reverse Integer easy.c: -------------------------------------------------------------------------------- 1 | int reverse(int x) 2 | { 3 | bool negative = false; 4 | int num = 0, temp_num = 0, temp = 0; 5 | int i = 0; 6 | 7 | if (x < 0) 8 | { 9 | negative = true; 10 | x = -x; 11 | } 12 | while (x) 13 | { 14 | if (num > (INT_MAX - x % 10) / 10)//这句话用来判断是否一出,这句话不懂 15 | return 0; 16 | num = num * 10 + x % 10; 17 | x = x / 10; 18 | } 19 | 20 | if (negative) 21 | return -num; 22 | return num; 23 | } -------------------------------------------------------------------------------- /LeetCode/C/2017-11-21-ZigZag Conversion medium.c: -------------------------------------------------------------------------------- 1 | char* convert(char* s, int numRows) 2 | { 3 | int i = 0, difference = 0, position_result = 0, position_s = 0; 4 | int length = strlen(s); 5 | int differenc_change = 1; 6 | char * result = (char*)malloc(sizeof(char)*(length + 1)); 7 | 8 | if (numRows == 1) 9 | return s; 10 | 11 | position_s = 0; 12 | difference = 2 * numRows - 2; 13 | while (position_s < length) 14 | { 15 | result[position_result] = s[position_s]; 16 | position_s += difference; 17 | position_result++; 18 | } 19 | 20 | for (i = 1; i < numRows - 1; i++) 21 | { 22 | differenc_change = 1; 23 | difference = 2 * numRows - 2 * (i + 1); 24 | position_s = i; 25 | while (position_s < length) 26 | { 27 | result[position_result] = s[position_s]; 28 | differenc_change++; 29 | if (!(differenc_change % 2)) 30 | difference = 2 * numRows - 2 * (i + 1); 31 | else 32 | difference = i * 2; 33 | position_s += difference; 34 | position_result++; 35 | } 36 | } 37 | 38 | position_s = numRows - 1; 39 | difference = 2 * numRows - 2; 40 | while (position_s < length) 41 | { 42 | result[position_result] = s[position_s]; 43 | position_s += difference; 44 | position_result++; 45 | } 46 | result[length] = NULL; 47 | 48 | return result; 49 | } -------------------------------------------------------------------------------- /LeetCode/C/2017-11-23-Palindrome Number easy.c: -------------------------------------------------------------------------------- 1 | int Get_length(int x) 2 | { 3 | int count = 0; 4 | 5 | while (x) 6 | { 7 | x /= 10; 8 | count++; 9 | } 10 | 11 | return count; 12 | } 13 | bool isPalindrome(int x) 14 | { 15 | int length = 0; 16 | int max = 1,min=1; 17 | int i = 0, times = 0; 18 | int temp = x, left = 0, right = 0; 19 | 20 | 21 | if (x < 0) 22 | return false; 23 | if (x < 10) 24 | return true; 25 | length = Get_length(x); 26 | times = (length + 1) / 2; 27 | for (i = 0; i < length - 1; i++) 28 | max *= 10; 29 | 30 | left = temp / max; 31 | right = temp % 10; 32 | 33 | for (i = 0; i < times; i++) 34 | { 35 | if (left == right) 36 | { 37 | max /= 10; 38 | min *= 10; 39 | left = (temp / max) % 10; 40 | right = (temp / min) % 10; 41 | } 42 | else 43 | return false; 44 | } 45 | 46 | return true; 47 | } -------------------------------------------------------------------------------- /LeetCode/C/2017-11-24-Container With Most Water medium.c: -------------------------------------------------------------------------------- 1 | //11. Container With Most Water 2 | 3 | int maxArea(int* height, int heightSize) 4 | { 5 | int result_max = 0, temp_max = 0; 6 | int left = 0, right = heightSize - 1; 7 | 8 | while (left result_max) 21 | result_max = temp_max; 22 | 23 | } 24 | 25 | return result_max; 26 | } -------------------------------------------------------------------------------- /LeetCode/C/2017-11-25-Integer to Roman medium.c: -------------------------------------------------------------------------------- 1 | // 12. Integer to Roman 2 | char* intToRoman(int num) 3 | { 4 | char string[13][3] = { "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" }; 5 | int value[13] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 6 | char * result = malloc(sizeof(char) * 100); 7 | int i = 0,j=0, temp_num = num, position = 0; 8 | int length = 0; 9 | 10 | for (i = 0; temp_num; i++) 11 | { 12 | while (temp_num>=value[i]) 13 | { 14 | length = strlen(string[i]); 15 | j = 0; 16 | while (length) 17 | { 18 | result[position] = string[i][j]; 19 | j++; 20 | position++; 21 | length--; 22 | } 23 | temp_num -= value[i]; 24 | } 25 | } 26 | 27 | result[position] = NULL; 28 | 29 | return result; 30 | } -------------------------------------------------------------------------------- /LeetCode/C/2017-11-8-(3n+1).c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define range_max 1000 6 | #define times 3 7 | 8 | //运行环境 Visual studio 9 | 10 | int judge(int guess) 11 | { 12 | int count = 0; 13 | 14 | if (!(guess - 1)) 15 | { 16 | printf_s("%d", 1); 17 | return count; 18 | } 19 | 20 | do 21 | { 22 | if (guess % 2)//如果是基数 23 | { 24 | guess = (times*guess + 1) / 2; 25 | count++; 26 | } 27 | else 28 | { 29 | guess = guess / 2; 30 | count++; 31 | } 32 | } while (guess - 1); 33 | 34 | return count; 35 | } 36 | 37 | int main() 38 | { 39 | int seed = clock()*clock()*clock()*time(NULL); 40 | int test_times = 100; 41 | int rand_num_max = 1000, rand_num_min = 2, test_num = 0; 42 | int i = 0; 43 | srand(seed); 44 | 45 | for (i = 0; i < test_times; i++) 46 | { 47 | test_num = rand() % (rand_num_max - rand_num_min + 1) + rand_num_min; 48 | printf_s("%d===%d times\n", test_num, judge(test_num)); 49 | } 50 | 51 | system("pause"); 52 | } 53 | -------------------------------------------------------------------------------- /LeetCode/C/2017-11-8-Insert_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void Insert_sort(int *list,int list_num) 6 | { 7 | int count = 0; 8 | int temp = 0; 9 | int i = 0, j = 0; 10 | 11 | for(i=1;i0; j--) 13 | { 14 | if (list[j] > list[j - 1]) 15 | { 16 | temp = list[j]; 17 | list[j] = list[j - 1]; 18 | list[j - 1] = temp; 19 | continue; 20 | } 21 | count++; 22 | break; 23 | } 24 | 25 | printf_s("%d\n", count); 26 | } 27 | 28 | //主调函数调用 29 | // int main() 30 | // { 31 | // int length = 1000000, i = 0; 32 | // int range_max = 100, range_min = 10; 33 | // int seed = 0; 34 | // int t1 = 0, t2 = 0; 35 | // t1 = clock(); 36 | 37 | // int *sort_list = (int *)calloc(sizeof(int), length); 38 | // seed = clock()*clock()*clock()*clock()*clock()*time(NULL); 39 | // srand(seed); 40 | 41 | // for (int j = 0; j < 1; j++) 42 | // { 43 | // for (i = 0; i < length; i++) 44 | // sort_list[i] = rand() % (range_max - range_min + 1) + range_min; 45 | // Insert_sort(sort_list, length); 46 | // } 47 | // t2 = clock(); 48 | 49 | // printf_s("%d---------------",(t2-t1)/1000); 50 | 51 | // system("pause"); 52 | // } 53 | -------------------------------------------------------------------------------- /LeetCode/C/2018-1-14-FIFO_PageReplacement.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-1-14-FIFO_PageReplacement.c -------------------------------------------------------------------------------- /LeetCode/C/2018-1-18-13. Roman to Integer.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-1-18-13. Roman to Integer.c -------------------------------------------------------------------------------- /LeetCode/C/2018-1-18-28. Implement strStr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int Get_length(char *str) 6 | { 7 | int length = 0; 8 | 9 | while (str[length]) 10 | length++; 11 | 12 | return length; 13 | } 14 | 15 | int strStr(char* haystack, char* needle) 16 | { 17 | int haystack_length = 0, needle_lenth = 0; 18 | int i = 0, j = 0; 19 | 20 | haystack_length = Get_length(haystack); 21 | needle_lenth = Get_length(needle); 22 | if (haystack[0] == 0 && needle[0] == 0) 23 | return 0; 24 | if (haystack[0] == 0 && needle[0] != 0) 25 | return -1; 26 | if (haystack[0] != 0 && needle[0] == 0) 27 | return 0; 28 | if (haystack_length < needle_lenth) 29 | return -1; 30 | while (haystack[i] && needle[j]) 31 | { 32 | if (haystack[i] == needle[j]) 33 | { 34 | i++; 35 | j++; 36 | } 37 | else 38 | { 39 | i = i - j + 1; 40 | j = 0; 41 | } 42 | } 43 | 44 | if (j >= needle_lenth) 45 | return i - needle_lenth; 46 | else 47 | return -1; 48 | } 49 | 50 | int main() 51 | { 52 | 53 | system("pause"); 54 | } -------------------------------------------------------------------------------- /LeetCode/C/2018-1-18-8. String to Integer (atoi).c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | // this code is come from http://blog.csdn.net/runningtortoises/article/details/45557659 11 | 12 | int myAtoi(char* str) 13 | { 14 | int flag = 1, res = 0, dig = 0; 15 | 16 | while (*str == ' ') 17 | str++; 18 | 19 | if (*str == '-') 20 | { 21 | flag = -1; 22 | str++; 23 | } 24 | else if (*str == '+') 25 | { 26 | str++; 27 | } 28 | 29 | while (*str) 30 | { 31 | if (*str<'0' || *str>'9') 32 | { 33 | return flag * res; 34 | } 35 | dig = *str - '0'; 36 | if (flag == 1 && res*10.0 + dig > INT_MAX) 37 | { 38 | return INT_MAX; 39 | } 40 | else if (flag == -1 && -res * 10.0 - dig < INT_MIN) 41 | { 42 | return INT_MIN; 43 | } 44 | res = res * 10 + dig; 45 | str++; 46 | } 47 | 48 | return flag * res; 49 | } 50 | 51 | int main() 52 | { 53 | printf_s("%ld", divide(1010369383,-2147483648)); 54 | system("pause"); 55 | } -------------------------------------------------------------------------------- /LeetCode/C/2018-1-18-Longest Common Prefix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | char* longestCommonPrefix(char** strs, int strsSize) 11 | { 12 | char* str = strs[0]; 13 | int i, j; 14 | if (strsSize == 0)return ""; 15 | for (i = 1; i 2 | #include 3 | 4 | 5 | // Definition for singly - linked list. 6 | 7 | struct ListNode { 8 | int val; 9 | struct ListNode *next; 10 | 11 | }; 12 | 13 | struct ListNode* swapPairs(struct ListNode* head) 14 | { 15 | if (!head || !head->next) 16 | return head; 17 | 18 | struct ListNode *temp = head->next; 19 | head->next = swapPairs(temp->next); 20 | temp->next = head; 21 | 22 | return temp; 23 | } -------------------------------------------------------------------------------- /LeetCode/C/2018-1-2-26. Remove Duplicates from Sorted Array easy.c: -------------------------------------------------------------------------------- 1 | 2 | // Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. 3 | 4 | // Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | // Example: 7 | 8 | // Given nums = [1,1,2], 9 | 10 | // Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 11 | // It doesn't matter what you leave beyond the new length. 12 | 13 | int removeDuplicates(int* nums, int numsSize) 14 | { 15 | int index = 0, i = 0; 16 | if (!numsSize) 17 | return index; 18 | 19 | index = 1; 20 | for (i = 1; i < numsSize; i++) 21 | { 22 | if (nums[i] != nums[i - 1]) 23 | { 24 | nums[index] = nums[i]; 25 | index++; 26 | } 27 | } 28 | 29 | return index; 30 | } -------------------------------------------------------------------------------- /LeetCode/C/2018-1-2-27. Remove Element easy.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | //27. Remove Element 6 | // 7 | //Given an array and a value, remove all instances of that value in - place and return the new length. 8 | // 9 | //Do not allocate extra space for another array, you must do this by modifying the input array in - place with O(1) extra memory. 10 | // 11 | //The order of elements can be changed.It doesn't matter what you leave beyond the new length. 12 | // 13 | //Example: 14 | // 15 | //Given nums = [3, 2, 2, 3], val = 3, 16 | // 17 | //Your function should return length = 2, with the first two elements of nums being 2. 18 | 19 | int removeElement(int* nums, int numsSize, int val) 20 | { 21 | int left = 0, right = numsSize - 1; 22 | 23 | while (left <= right) 24 | { 25 | if (nums[left] == val) 26 | { 27 | if (nums[right] == val) 28 | right--; 29 | else 30 | { 31 | nums[left] = nums[right]; 32 | left++; 33 | right--; 34 | } 35 | } 36 | else 37 | { 38 | left++; 39 | } 40 | 41 | } 42 | 43 | return right + 1; 44 | } -------------------------------------------------------------------------------- /LeetCode/C/2018-1-20-10. Regular Expression Matching.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | bool isMatch(char* s, char* p) 9 | { 10 | if (*p == '\0') return *s == '\0'; 11 | 12 | if (*(p + 1) != '*') 13 | { 14 | if (*p == *s || *p == '.'&&*s != '\0') 15 | return isMatch(s + 1, p + 1); 16 | 17 | return false; 18 | } 19 | else 20 | { 21 | while (*p == *s || *p == '.'&&*s != '\0') 22 | { 23 | if (isMatch(s, p + 2)) 24 | return true; 25 | s++; 26 | } 27 | return isMatch(s, p + 2); 28 | } 29 | } 30 | 31 | 32 | int main() 33 | { 34 | 35 | system("pause"); 36 | } -------------------------------------------------------------------------------- /LeetCode/C/2018-1-24-LRU Page replacement.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-1-24-LRU Page replacement.c -------------------------------------------------------------------------------- /LeetCode/C/2018-2-5-30. Substring with Concatenation of All Words.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-2-5-30. Substring with Concatenation of All Words.c -------------------------------------------------------------------------------- /LeetCode/C/2018-2-5-31.Next Permutation.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-2-5-31.Next Permutation.c -------------------------------------------------------------------------------- /LeetCode/C/2018-2-5-32. Longest Valid Parentheses.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-2-5-32. Longest Valid Parentheses.c -------------------------------------------------------------------------------- /LeetCode/C/2018-2-6-33. Search in Rotated Sorted Array.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-2-6-33. Search in Rotated Sorted Array.c -------------------------------------------------------------------------------- /LeetCode/C/2018-2-6-34. Search for a Range.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-2-6-34. Search for a Range.c -------------------------------------------------------------------------------- /LeetCode/C/2018-2-6-35. Search Insert Position.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-2-6-35. Search Insert Position.c -------------------------------------------------------------------------------- /LeetCode/C/2018-3-1-36. Valid Sudoku.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-3-1-36. Valid Sudoku.c -------------------------------------------------------------------------------- /LeetCode/C/2018-3-19-CaesarsCipher.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/LeetCode/C/2018-3-19-CaesarsCipher.c -------------------------------------------------------------------------------- /MySql/01-基础架构.md: -------------------------------------------------------------------------------- 1 | 数据库引擎:InnoDB 2 | 3 | Server 层(核心服务,视图) 4 | 5 | - 连接器 6 | 维持链接,管理链接 7 | 链接之后认证身份,通过之后查你输入 User 的权限 8 | 尽量使用长连接,如果内存占用太大: 9 | 1、定期断开长连接 10 | 2、mysql 5.7 或更新,执行 mysql_reset_connection 命令 11 | - 查询缓存 12 | 1、以 key-value 的形式存储在查询缓存中 13 | 2、只要有一个更新的操作,所有的缓存都会被更新 14 | - 分析器(你要做什么) 15 | - 词法分析,分析你要做什么,每个字符串代表什么,你要做什么。 16 | - 语法分析,语法是否满足 mysql 的语法,提示第一个出现错误的位置。 17 | - 优化器(该怎么做) 18 | - 表有多个索引的时候,使用哪个索引 19 | - 在一个语句有多表关联(join)的时候,决定各个表的连接顺序 20 | - 执行器 21 | - 检查你的权限 22 | - 权限通过,进行查询 23 | 24 | 存储层(数据的存储和提取) 25 | - 插件式的结构 26 | -------------------------------------------------------------------------------- /MySql/02-日志系统.md: -------------------------------------------------------------------------------- 1 | 日志系统 2 | 3 | WAL:Write-Ahead Logging,先写日志,后写磁盘 4 | 5 | **redo log** 6 | - 有更新的时候,将更新写到 redo log(需要写到硬盘),并更新内存 7 | - InnoDB 引擎在适当的时候,将这个操作记录更新到磁盘里面 8 | - 固定磁盘大小 9 | - 有 crash safe 的能力 10 | 11 | 12 | **big log** 13 | - 用于归档 14 | - 最开始的时候 mysql 并没有 InnoDB 引擎 15 | 16 | 区别: 17 | - redo log 为 InnoDB 特有,big log 是 Mysql Server 层实现的,任何数据引擎都可以使用 18 | - redo log 循环写,bin log 追加写 19 | 20 | 21 | 两阶段提交 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /MySql/03-事务隔离.md: -------------------------------------------------------------------------------- 1 | 锁级别 2 | 3 | 隔离的越严实,效率越低 4 | 5 | - 读未提交 :一个事务还未提交时,它的变更就可以被别的事务看到 6 | - 直接读数据库中的值 7 | 8 | 9 | - 读提交:一个事务提交之后,他的变更才可以被别的事务看到 10 | - 在每一个 sql 执行的时候创建视图 11 | 12 | 13 | - 可重复读:一个事务执行过程总看到的数据,总是跟这个事务在启动时看到的数据是一致的。 14 | - 在事务开始的时候创建视图 15 | 16 | 17 | - 串行化: 对于同一行记录,写会加写锁,读会加读锁, 18 | - 通过加锁来实现 19 | 20 | 不建议使用长连接,会导致内存占用过大 21 | 22 | ```sql 23 | select * from information_schema.innodb_trx where TIME_TO_SEC(timediff(now(),trx_started))>60 24 | ``` -------------------------------------------------------------------------------- /MySql/04-索引.md: -------------------------------------------------------------------------------- 1 | 2 | InnoDB 使用 B+ 树 3 | 4 | 1、提高查询效率 5 | 2、哈希表不适合范围查询,适合等值查询 6 | 3、有序数组查询快,更新慢 7 | 4、二叉树搜索效率高,但是访问节点的个数多,在机械硬盘时代,寻址时间过长 8 | 4、B+ 树能够很好的配合磁盘的读写特性,减少单次查询磁盘的访问次数; 9 | 10 | 11 | 回到主键索引搜索的过程称为回表 12 | 13 | 索引树已经覆盖了查询请求的情况,称为覆盖索引。 14 | 15 | Mysql 5.6 以后有了索引下推优化 16 | 17 | 普通索引 和 唯一索引 18 | 19 | change buffer 只能用普通索引 20 | 21 | change buffer 对于写了之后立即读的操作用处不大;change buffer 最适合的场景的是写多读少的场景; 22 | 23 | 提高性能的关键:减少随机读写 24 | 25 | >对于唯一索引来说,所有的更新操作都要先判断这个操作是否违反唯一性约束。比如,要插入 (4,400) 这个记录,就要先判断现在表中是否已经存在 k=4 的记录,而这必须要将数据页读入内存才能判断。如果都已经读入到内存了,那直接更新内存会更快,就没必要使用 change buffer 了 26 | 27 | ### 选错索引 28 | 索引的区分度 = 不重复的索引值/数据表的总记录,。区分度越高,索引查询时会让mysql在查询时过滤掉更多的行,值越接近1,区分度越高。 -------------------------------------------------------------------------------- /MySql/05-锁.md: -------------------------------------------------------------------------------- 1 | 全局锁 2 | 3 | 表锁 4 | 5 | 行级锁 6 | 7 | - 行锁在需要的时候添加,在事物提交时释放 8 | - 当并发系统中不同线程出现循环资源依赖,涉及的线程都在等待别的线程释放资源时,就会导致这几个线程都进入无限等待的状态,称为死锁 9 | - 进入等待,直到超时,超时时间可以通过参数参数设置 10 | - 主动死锁检测,发现死锁后,主动混滚一个事务(CPU 消耗高) 11 | - 12 | -------------------------------------------------------------------------------- /Others/2019-07-12-LD-买切糕.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Author: 何睿 3 | # @Create Date: 2019-07-12 21:52:42 4 | # @Last Modified by: 何睿 5 | # @Last Modified time: 2019-07-12 23:29:11 6 | 7 | from typing import List 8 | 9 | 10 | def get_change(costs: List, money: int) -> int: 11 | 12 | # 为了简短,对 costs 和 money 各自乘以 2 并转换为 int 的操作没有写出 13 | dp = [[0] * (money + 1) for _ in range(len(costs))] 14 | for i in range(1, money // costs[0] + 1): 15 | dp[0][i * costs[0]] = 1 16 | 17 | for i in range(1, len(costs)): 18 | for j in range(1, money + 1): 19 | dp[i][j] = sum(dp[i - 1][j - x * costs[i]] for x in range(j // costs[i] + 1)) 20 | # 如果刚好 j 能够整除 costs[i],说明可以构成一种买法 21 | if j % costs[i] == 0: dp[i][j] += 1 22 | 23 | return sum(dp[-1]) 24 | -------------------------------------------------------------------------------- /receive.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/receive.jpeg -------------------------------------------------------------------------------- /wechat.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruicore/algorithm/d544867131923ec7a96d7b731ced58373ac1f328/wechat.jpeg --------------------------------------------------------------------------------