├── 2022 ├── hj_106.py ├── hj_22_easy_code.py ├── hj_23_del_least_char.py ├── hj_31_word_deced.py ├── hj_56_perfect_numer.py ├── hj_57_min_number_pair.py ├── hj_62_apples.py ├── hj_exam_2.py ├── magic_index.py ├── 合并表记录.py ├── 最长子序列 │ ├── lcs_count.py │ └── lcs_print.py ├── 背包问题.py └── 质数因子.py ├── .gitignore ├── Classify ├── Array │ ├── 11#Container With Most Water.py │ ├── 123#Best Time to Buy and Sell Stock III.py │ ├── 152#Maximum Product Subarray.py │ ├── 153#Find Minimum in Rotated Sorted Array.py │ ├── 18#4Sum.py │ ├── 216#Combination Sum III.py │ ├── 238#Product of Array Except Self .py │ ├── 287#Find the Duplicate Number.py │ ├── 289#Game of Life.py │ ├── 31#Next Permutation.py │ ├── 34#Find First and Last Position of Element in Sorted Array.py │ ├── 380#Insert Delete GetRandom O(1).py │ ├── 39#Combination Sum.py │ ├── 40#Combination Sum II.py │ ├── 41#First Missing Positive.py │ ├── 42#Trapping Rain Water.py │ ├── 442#Find All Duplicates in an Array.py │ ├── 45#Jump Game II.py │ ├── 48#Rotate Image.py │ ├── 495#Teemo Attacking.py │ ├── 509#Fibonacci Number.py │ ├── 54#Spiral Matrix.py │ ├── 55#Jump Game.py │ ├── 56#Merge Intervals.py │ ├── 565#Array Nesting.py │ ├── 57#Insert Interval.py │ ├── 581#Shortest Unsorted Continuous Subarray.py │ ├── 59#Spiral Matrix II.py │ ├── 611#Valid Triangle Number.py │ ├── 62#Unique Paths.py │ ├── 63#Unique Paths II.py │ ├── 64#Minimum Path Sum.py │ ├── 661#mage Smoother.py │ ├── 665#Non-decreasing Array.py │ ├── 667#Beautiful Arrangement II.py │ ├── 674#Longest Continuous Increasing Subsequence.py │ ├── 695#Max Area of Island.py │ ├── 697#Degree of an Array.py │ ├── 714#Best Time to Buy and Sell Stock with Transaction Fee.py │ ├── 717#1-bit and 2-bit Characters.py │ ├── 718#Maximum Length of Repeated Subarray.py │ ├── 719#Find K-th Smallest Pair Distance.py │ ├── 724#Find Pivot Index.py │ ├── 729#My Calendar I.py │ ├── 73#Set Matrix Zeroes.py │ ├── 731#My Calendar II.py │ ├── 74#Search a 2D Matrix.py │ ├── 747#Largest Number At Least Twice of Others.py │ ├── 75#Sort Colors.py │ ├── 766#Toeplitz Matrix.py │ ├── 769#Max Chunks To Make Sorted.py │ ├── 78#Subsets.py │ ├── 79#Word Search.py │ ├── 80#Remove Duplicates from Sorted Array II.py │ ├── 81#Search in Rotated Sorted Array II.py │ ├── 830#Positions of Large Groups.py │ ├── 832#Flipping an Image.py │ ├── 84#Largest Rectangle in Histogram.py │ ├── 840#Magic Squares In Grid.py │ ├── 849#Maximize Distance to Closest Person.py │ ├── 85#Maximal Rectangle.py │ ├── 867#Transpose Matrix.py │ ├── 888#Fair Candy Swap.py │ ├── 896#Monotonic Array.py │ ├── 90#Subsets II.py │ ├── 900#RLE Iterator.py │ ├── 905#Sort Array By Parity.py │ ├── 914#X of a Kind in a Deck of Cards.py │ ├── 918#Maximum Sum Circular Subarray.py │ ├── 922#Sort Array By Parity II.py │ ├── 926#Flip String to Monotone Increasing.py │ ├── 941#Valid Mountain Array.py │ ├── 950#Reveal Cards In Increasing Order.py │ └── 969#Pancake Sorting.py ├── BinarySearch │ └── Readme.md ├── HashTable │ ├── 138#Copy List with Random Pointer.py │ ├── 347#Top K Frequent Elements.py │ ├── 36#Valid Sudoku.py │ ├── 451#Sort Characters By Frequency.py │ ├── 454#4Sum II.py │ ├── 508#Most Frequent Subtree Sum.py │ ├── 525#Contiguous Array.py │ ├── 535#Encode and Decode TinyURL.py │ ├── 594#Longest Harmonious Subsequence.py │ ├── 648#Replace Words.py │ ├── 676#Implement Magic Dictionary.py │ ├── 690#Employee Importance.py │ ├── 705#Design HashSet.py │ ├── 706#Design HashMap.py │ ├── 720#Longest Word in Dictionary.py │ ├── 726#Number of Atoms.py │ ├── 739#Daily Temperatures.py │ ├── 748#Shortest Completing Word.py │ ├── 771#Jewels and Stones.py │ ├── 781#Rabbits in Forest.py │ ├── 811#Subdomain Visit Count.py │ ├── 884#Uncommon Words from Two Sentences.py │ ├── 939#Minimum Area Rectangle.py │ └── 953#Verifying an Alien Dictionary.py ├── Sort │ ├── Readme.md │ ├── bubble_sort.py │ ├── heap_sort.py │ ├── insertion_sort.py │ ├── quick_sort.py │ ├── select_sort.py │ ├── shell_sort.py │ ├── sort.py │ └── sort_analysis.py ├── String │ ├── 12#Integer to Roman.py │ ├── 151#Reverse Words in a String.py │ ├── 165#Compare Version Numbers.py │ ├── 17#Letter Combinations of a Phone Number.py │ ├── 385#Mini Parser.py │ ├── 43#Multiply Strings.py │ ├── 49#Group Anagrams.py │ ├── 521#Longest Uncommon Subsequence I.py │ ├── 537#Complex Number Multiplication.py │ ├── 539#Minimum Time Difference.py │ ├── 553#Optimal Division.py │ ├── 583#Delete Operation for Two Strings.py │ ├── 609#Find Duplicate File in System.py │ ├── 632#Smallest Range.py │ ├── 647#Palindromic Substrings.py │ ├── 657#Robot Return to Origin.py │ ├── 678#Valid Parenthesis String.py │ ├── 680#Valid Palindrome II.py │ ├── 686#Repeated String Match.py │ ├── 696#Count Binary Substrings.py │ ├── 709#To Lower Case.py │ ├── 761#Special Binary String.py │ ├── 767#Reorganize String.py │ ├── 788#Rotated Digits.py │ ├── 791#Custom Sort String.py │ ├── 804#Unique Morse Code Words.py │ ├── 809#Expressive Words.py │ ├── 816#Ambiguous Coordinates.py │ ├── 819#Most Common Word.py │ ├── 824#Goat Latin.py │ ├── 831#Masking Personal Information.py │ ├── 833#Find And Replace in String.py │ ├── 842#Split Array into Fibonacci Sequence.py │ ├── 848#Shifting Letters.py │ ├── 856#Score of Parentheses.py │ ├── 859#Buddy Strings.py │ ├── 890#Find and Replace Pattern.py │ ├── 893#Groups of Special-Equivalent Strings.py │ ├── 899#Orderly Queue.py │ ├── 91#Decode Ways.py │ ├── 916#Word Subsets.py │ ├── 917#Reverse Only Letters.py │ ├── 925#Long Pressed Name.py │ ├── 929#Unique Email Addresses.py │ ├── 937#Reorder Log Files.py │ ├── 944#Delete Columns to Make Sorted.py │ ├── 961#N-Repeated Element in Size 2N Array.py │ └── Readme.md ├── ceshi1.py └── ceshi2.py ├── LeetCodeWeekly ├── April │ ├── Week1 │ │ ├── best-time-to-buy-and-sell-stock.py │ │ ├── group-anagrams-solution.py │ │ ├── happy-number.py │ │ ├── maximum-subarray.py │ │ ├── move-zeroes.py │ │ └── single-number.py │ ├── Week2 │ │ ├── backspace-string-compare.py │ │ ├── contiguous-array.py │ │ ├── diameter-of-binary-tree.py │ │ ├── last-stone-weight.py │ │ ├── middle-of-the-linked-list.py │ │ └── min-stack.py │ └── Week3 │ │ └── product-of-array-except-self.py └── meta_class.py ├── Others ├── 6_zigzag_conversion.py └── README.md ├── README.md ├── SwordOffer ├── DataStruct.py ├── README.md ├── SwordOffer_03.py ├── SwordOffer_04.py ├── SwordOffer_05.py ├── SwordOffer_06.py ├── SwordOffer_07.py ├── SwordOffer_09.py ├── SwordOffer_10_1.py ├── SwordOffer_10_2.py ├── SwordOffer_11.py ├── SwordOffer_12.py ├── SwordOffer_13.py ├── SwordOffer_14.py ├── SwordOffer_14_2.py ├── SwordOffer_15.py ├── SwordOffer_16.py ├── SwordOffer_17.py ├── SwordOffer_18.py ├── SwordOffer_19.py ├── SwordOffer_20.py ├── SwordOffer_21.py ├── SwordOffer_22.py ├── SwordOffer_24.py ├── SwordOffer_25.py ├── SwordOffer_26.py ├── SwordOffer_27.py ├── SwordOffer_28.py ├── SwordOffer_29.py ├── SwordOffer_30.py ├── SwordOffer_31.py ├── SwordOffer_32.py ├── SwordOffer_32_2.py ├── SwordOffer_32_3.py ├── SwordOffer_33.py ├── SwordOffer_34.py ├── SwordOffer_35.py ├── SwordOffer_36.py ├── SwordOffer_37.py ├── SwordOffer_38.py ├── SwordOffer_39.py ├── SwordOffer_40.py ├── SwordOffer_42.py ├── SwordOffer_44.py ├── SwordOffer_45.py ├── SwordOffer_46.py ├── SwordOffer_55_1.py ├── SwordOffer_55_2.py ├── SwordOffer_56_1.py ├── SwordOffer_56_2.py ├── SwordOffer_57.py ├── SwordOffer_57_2.py ├── SwordOffer_58.py └── SwordOffer_65.py ├── code ├── 1#Two Sum.py ├── 10#Regular Expression Matching.py ├── 100#Same Tree.py ├── 101#Symmetric Tree.py ├── 102#Binary Tree Level Order Traversal.py ├── 103#Binary Tree Zigzag Level Order Traversal.py ├── 104#Maximum Depth of Binary Tree.py ├── 106#Construct Binary Tree from Inorder and Postorder Traversal.py ├── 107#Binary Tree Level Order Traversal II.py ├── 108#Convert Sorted Array to Binary Search Tree.py ├── 109#Convert Sorted List to Binary Search Tree.py ├── 11#Container With Most Water.py ├── 110#Balanced Binary Tree.py ├── 111#Minimum Depth of Binary Tree.py ├── 112#Path Sum.py ├── 113#Path Sum II.py ├── 114#Flatten Binary Tree to Linked List.py ├── 116#Populating Next Right Pointers in Each Node.py ├── 117#Populating Next Right Pointers in Each Node II.py ├── 118#Pascal's Triangle.py ├── 119#Pascal's Triangle II.py ├── 12#Integer to Roman.py ├── 120#Triangle.py ├── 121#Best Time to Buy and Sell Stock.py ├── 122#Best Time to Buy and Sell Stock II.py ├── 123#Best Time to Buy and Sell Stock III.py ├── 125#Valid Palindrome.py ├── 127#Word Ladder.py ├── 13#Roman to Integer.py ├── 134#Gas Station.py ├── 136#Single Number.py ├── 138#Copy List with Random Pointer.py ├── 139#Word Break.py ├── 14#Longest Common Prefix.py ├── 141#Linked List Cycle.py ├── 142#Linked List Cycle II.py ├── 147#Insertion Sort List.py ├── 148#Sort List.py ├── 1496#spath crossing.py ├── 151#Reverse Words in a String.py ├── 152#Maximum Product Subarray.py ├── 153#Find Minimum in Rotated Sorted Array.py ├── 155#Min Stack.py ├── 160#Intersection of Two Linked Lists.py ├── 165#Compare Version Numbers.py ├── 167#Two Sum II - Input array is sorted.py ├── 168#Excel Sheet Column Title.py ├── 169#Majority Element.py ├── 17#Letter Combinations of a Phone Number.py ├── 171#Excel Sheet Column Number.py ├── 172#Factorial Trailing Zeroes.py ├── 18#4Sum.py ├── 189#Rotate Array.py ├── 190#Reverse Bits.py ├── 191#Number of 1 Bits.py ├── 198#House Robber.py ├── 2#Add Two Nubers.py ├── 20#Valid Parentheses.py ├── 202#Happy Number.py ├── 203#Remove Linked List Elements.py ├── 204#Count Primes.py ├── 205#Isomorphic Strings.py ├── 206#Reverse Linked List.py ├── 207#Course Schedule.py ├── 21#Merge Two Sorted Lists.py ├── 215#Kth Largest Element in an Array.py ├── 216#Combination Sum III.py ├── 217#Contains Duplicate.py ├── 219#Contains Duplicate II.py ├── 223#Rectangle Area.py ├── 225#Implement Stack using Queues.py ├── 226#Invert Binary Tree.py ├── 23#Merge k Sorted Lists.py ├── 231#Power of Two.py ├── 232#Implement Queue using Stacks.py ├── 234#Palindrome Linked List.py ├── 235#Lowest Common Ancestor of a Binary Search Tree.py ├── 237#Delete Node in a Linked List.py ├── 238#Product of Array Except Self .py ├── 24#Swap Nodes in Pairs.py ├── 242#Valid Anagram.py ├── 25#Reverse Nodes in k-Group.py ├── 257#Binary Tree Paths.py ├── 258#Add Digits.py ├── 26#Remove Duplicates from Sorted Array.py ├── 263#Ugly Number.py ├── 268#Missing Number.py ├── 27#Remove Element.py ├── 278#First Bad Version.py ├── 28#Implement strStr().py ├── 283.#Move Zeroes.py ├── 287#Find the Duplicate Number.py ├── 289#Game of Life.py ├── 290#Word Pattern.py ├── 292#Nim Game.py ├── 3#Longest Substring Without Repeating Characters.py ├── 303#Range Sum Query - Immutable.py ├── 31#Next Permutation.py ├── 326#Power of Three.py ├── 338#Counting Bits.py ├── 34#Find First and Last Position of Element in Sorted Array.py ├── 342#Power of Four.py ├── 344#Reverse String.py ├── 345#Reverse Vowels of a String.py ├── 347#Top K Frequent Elements.py ├── 349#Intersection of Two Arrays.py ├── 35#Search Insert Position.py ├── 350#Intersection of Two Arrays II.py ├── 36#Valid Sudoku.py ├── 367#Valid Perfect Square.py ├── 371#Sum of Two Integers.py ├── 374#Guess Number Higher or Lower.py ├── 38#Count and Say.py ├── 380#Insert Delete GetRandom O(1).py ├── 383#Ransom Note.py ├── 385#Mini Parser.py ├── 387#First Unique Character in a String.py ├── 389#Find the Difference.py ├── 39#Combination Sum.py ├── 40#Combination Sum II.py ├── 400#Nth Digit.py ├── 401#Binary Watch.py ├── 404#Sum of Left Leaves.py ├── 405#Convert a Number to Hexadecimal.py ├── 409#Longest Palindrome.py ├── 41#First Missing Positive.py ├── 412#Fizz Buzz.py ├── 414#Third Maximum Number.py ├── 415#Add Strings.py ├── 42#Trapping Rain Water.py ├── 427#Construct Quad Tree.py ├── 429#N-ary Tree Level Order Traversal.py ├── 43#Multiply Strings.py ├── 434#Number of Segments in a String.py ├── 437#Path Sum III.py ├── 438#Find All Anagrams in a String.py ├── 441#Arranging Coins.py ├── 442#Find All Duplicates in an Array.py ├── 443#String Compression.py ├── 447#Number of Boomerangs.py ├── 448#EFind All Numbers Disappeared in an Array.py ├── 45#Jump Game II.py ├── 451#Sort Characters By Frequency.py ├── 454#4Sum II.py ├── 455#Assign Cookies.py ├── 458#Poor Pigs.py ├── 459#Repeated Substring Pattern.py ├── 46#Permutations.py ├── 461#Hamming Distance.py ├── 463#Island Perimeter.py ├── 47#Permutations II.py ├── 475#Heaters.py ├── 476#Number Complement.py ├── 479#Largest Palindrome Product.py ├── 48#Rotate Image.py ├── 482#License Key Formatting.py ├── 485#Max Consecutive Ones.py ├── 49#Group Anagrams.py ├── 492#Construct the Rectangle.py ├── 495#Teemo Attacking.py ├── 496#Next Greater Element I.py ├── 500#Keyboard Row.py ├── 501#Find Mode in Binary Search Tree.py ├── 504#Base 7.py ├── 506#Relative Ranks.py ├── 507#Perfect Number.py ├── 508#Most Frequent Subtree Sum.py ├── 509#Fibonacci Number.py ├── 520#Detect Capital.py ├── 521#Longest Uncommon Subsequence I.py ├── 525#Contiguous Array.py ├── 53#Maximum Subarray.py ├── 530#Minimum Absolute Difference in BST.py ├── 532#K-diff Pairs in an Array.py ├── 535#Encode and Decode TinyURL.py ├── 537#Complex Number Multiplication.py ├── 538#Convert BST to Greater Tree.py ├── 539#Minimum Time Difference.py ├── 54#Spiral Matrix.py ├── 541#Reverse String II.py ├── 543#Diameter of Binary Tree.py ├── 55#Jump Game.py ├── 551#Student Attendance Record I.py ├── 553#Optimal Division.py ├── 557#Reverse Words in a String III.py ├── 558#Quad Tree Intersection.py ├── 559#Maximum Depth of N-ary Tree.py ├── 56#Merge Intervals.py ├── 561#Array Partition I.py ├── 563#Binary Tree Tilt.py ├── 565#Array Nesting.py ├── 566#Reshape the Matrix.py ├── 57#Insert Interval.py ├── 572#Subtree of Another Tree.py ├── 575#Distribute Candies.py ├── 58#Length of Last Word.py ├── 581#Shortest Unsorted Continuous Subarray.py ├── 583#Delete Operation for Two Strings.py ├── 589#N-ary Tree Preorder Traversal.py ├── 59#Spiral Matrix II.py ├── 590#N-ary Tree Postorder Traversal.py ├── 594#Longest Harmonious Subsequence.py ├── 598#Range Addition II.py ├── 599#Minimum Index Sum of Two Lists.py ├── 60#Permutation Sequence.py ├── 605#Can Place Flowers.py ├── 606#Construct String from Binary Tree.py ├── 609#Find Duplicate File in System.py ├── 61#Rotate List.py ├── 611#Valid Triangle Number.py ├── 617#Merge Two Binary Trees.py ├── 62#Unique Paths.py ├── 628#Maximum Product of Three Numbers.py ├── 63#Unique Paths II.py ├── 632#Smallest Range.py ├── 633#Sum of Square Numbers.py ├── 637#Average of Levels in Binary Tree.py ├── 64#Minimum Path Sum.py ├── 643#Maximum Average Subarray I.py ├── 645#Set Mismatch.py ├── 647#Palindromic Substrings.py ├── 648#Replace Words.py ├── 653#Two Sum IV - Input is a BST.py ├── 654#Maximum Binary Tree.py ├── 655#Print Binary Tree.py ├── 657#Robot Return to Origin.py ├── 66#Plus One.py ├── 661#mage Smoother.py ├── 665#Non-decreasing Array.py ├── 667#Beautiful Arrangement II.py ├── 669#Trim a Binary Search Tree.py ├── 67#Add Binary.py ├── 671#Second Minimum Node In a Binary Tree .py ├── 674#Longest Continuous Increasing Subsequence.py ├── 676#Implement Magic Dictionary.py ├── 678#Valid Parenthesis String.py ├── 680#Valid Palindrome II.py ├── 682#Baseball Game.py ├── 686#Repeated String Match.py ├── 687#Longest Univalue Path.py ├── 69#Sqrt(x).py ├── 690#Employee Importance.py ├── 693#Binary Number with Alternating Bits.py ├── 695#Max Area of Island.py ├── 696#Count Binary Substrings.py ├── 697#Degree of an Array.py ├── 7#Reverse Integer.py ├── 70#Climbing Stairs.py ├── 700#Search in a Binary Search Tree.py ├── 701#Insert into a Binary Search Tree.py ├── 703#Kth Largest Element in a Stream.py ├── 705#Design HashSet.py ├── 706#Design HashMap.py ├── 707#Design Linked List.py ├── 709#To Lower Case.py ├── 71#Simplify Path.py ├── 714#Best Time to Buy and Sell Stock with Transaction Fee.py ├── 717#1-bit and 2-bit Characters.py ├── 718#Maximum Length of Repeated Subarray.py ├── 719#Find K-th Smallest Pair Distance.py ├── 720#Longest Word in Dictionary.py ├── 724#Find Pivot Index.py ├── 726#Number of Atoms.py ├── 729#My Calendar I.py ├── 73#Set Matrix Zeroes.py ├── 731#My Calendar II.py ├── 733#Flood Fill.py ├── 739#Daily Temperatures.py ├── 74#Search a 2D Matrix.py ├── 744#Find Smallest Letter Greater Than Target.py ├── 747#Largest Number At Least Twice of Others.py ├── 748#Shortest Completing Word.py ├── 75#Sort Colors.py ├── 754#Reach a Number.py ├── 761#Special Binary String.py ├── 762#Prime Number of Set Bits in Binary Representation.py ├── 766#Toeplitz Matrix.py ├── 767#Reorganize String.py ├── 769#Max Chunks To Make Sorted.py ├── 77#Combinations.py ├── 771#Jewels and Stones.py ├── 78#Subsets.py ├── 781#Rabbits in Forest.py ├── 783#Minimum Distance Between BST Nodes.py ├── 784#Letter Case Permutation .py ├── 788#Rotated Digits.py ├── 789#Escape The Ghosts.py ├── 79#Word Search.py ├── 791#Custom Sort String.py ├── 796#Rotate String.py ├── 80#Remove Duplicates from Sorted Array II.py ├── 804#Unique Morse Code Words.py ├── 806#Number of Lines To Write String .py ├── 807#Max Increase to Keep City Skyline.py ├── 809#Expressive Words.py ├── 81#Search in Rotated Sorted Array II.py ├── 811#Subdomain Visit Count.py ├── 812#Largest Triangle Area.py ├── 814#Binary Tree Pruning.py ├── 816#Ambiguous Coordinates.py ├── 819#Most Common Word.py ├── 82#Remove Duplicates from Sorted List II.py ├── 821#Shortest Distance to a Character.py ├── 824#Goat Latin.py ├── 83#Remove Duplicates from Sorted List.py ├── 830#Positions of Large Groups.py ├── 831#Masking Personal Information.py ├── 832#Flipping an Image.py ├── 833#Find And Replace in String.py ├── 836#Rectangle Overlap.py ├── 84#Largest Rectangle in Histogram.py ├── 840#Magic Squares In Grid.py ├── 842#Split Array into Fibonacci Sequence.py ├── 844#Backspace String Compare.py ├── 848#Shifting Letters.py ├── 849#Maximize Distance to Closest Person.py ├── 85#Maximal Rectangle.py ├── 852#Peak Index in a Mountain Array.py ├── 856#Score of Parentheses.py ├── 859#Buddy Strings.py ├── 86#Partition List.py ├── 860#Lemonade Change.py ├── 867#Transpose Matrix.py ├── 868#Binary Gap.py ├── 869#Reordered Power of 2.py ├── 872#Leaf-Similar Trees.py ├── 874#Walking Robot Simulation.py ├── 876#Middle of the Linked List.py ├── 88#Merge Sorted Array.py ├── 883#Projection Area of 3D Shapes.py ├── 884#Uncommon Words from Two Sentences.py ├── 888#Fair Candy Swap.py ├── 89#Gray Code.py ├── 890#Find and Replace Pattern.py ├── 892#Surface Area of 3D Shapes.py ├── 893#Groups of Special-Equivalent Strings.py ├── 896#Monotonic Array.py ├── 897#Increasing Order Search Tree.py ├── 899#Orderly Queue.py ├── 9#Palindrome Number.py ├── 90#Subsets II.py ├── 900#RLE Iterator.py ├── 905#Sort Array By Parity.py ├── 908#Smallest Range I.py ├── 91#Decode Ways.py ├── 914#X of a Kind in a Deck of Cards.py ├── 916#Word Subsets.py ├── 917#Reverse Only Letters.py ├── 918#Maximum Sum Circular Subarray.py ├── 92#Reverse Linked List II.py ├── 921#Minimum Add to Make Parentheses Valid.py ├── 922#Sort Array By Parity II.py ├── 925#Long Pressed Name.py ├── 926#Flip String to Monotone Increasing.py ├── 929#Unique Email Addresses.py ├── 93#Restore IP Addresses.py ├── 933#Number of Recent Calls.py ├── 937#Reorder Log Files.py ├── 938#Range Sum of BST.py ├── 939#Minimum Area Rectangle.py ├── 94#Binary Tree Inorder Traversal.py ├── 941#Valid Mountain Array.py ├── 942#DI String Match.py ├── 944#Delete Columns to Make Sorted.py ├── 949#Largest Time for Given Digits.py ├── 95#Unique Binary Search Trees II .py ├── 950#Reveal Cards In Increasing Order.py ├── 953#Verifying an Alien Dictionary.py ├── 96#Unique Binary Search Trees.py ├── 961#N-Repeated Element in Size 2N Array.py ├── 965#Univalued Binary Tree.py ├── 969#Pancake Sorting.py ├── 970#Powerful Integers.py ├── 973#K Closest Points to Origin.py ├── 976#Largest Perimeter Triangle.py ├── 977#Squares of a Sorted Array.py ├── 98#Validate Binary Search Tree.py ├── 984#String Without AAA or BBB.py ├── 985#Sum of Even Numbers After Queries.py ├── 988#smallest string starting from leaf.py ├── 989#Add to Array-Form of Integer.py ├── 993#Cousins in Binary Tree.py ├── 994#Rotting Oranges.py ├── 997#Find the Town Judge.py └── README.md ├── code_thinking ├── arrays │ ├── 209_minimum_size_subarray_sum.py │ ├── 27_remove_element.py │ ├── 59_spiral_matrix_ii.py │ ├── 704_binary_search.py │ └── 977_squares_of_a_sorted_array.py ├── data_struct.py ├── hash_table │ ├── 15_3sum.py │ ├── 18_4sum.py │ ├── 1_two_sum.py │ ├── 202_happy_number.py │ ├── 242_valid_anagram.py │ ├── 349_intersection_of_two_arrays.py │ ├── 383_ransom_note.py │ └── 454_4sum_ii.py ├── list_node │ ├── 142_linked_list_cycle_ii.py │ ├── 160_intersection_of_two_linked_lists_lcci.py │ ├── 19_remove_nth_node_from_end_of_list.py │ ├── 203.remove_linked_list_elements.py │ ├── 206_revers_linked_list.py │ ├── 24_swap_nodes_in_pairs.py │ └── 707_design_linked_list.py ├── string │ ├── 151_reverse_words_in_a_string.py │ ├── 28_find_the_index_of_the_first_occurrence_in_a_string.py │ ├── 344_reverse_string.py │ ├── 459_repeated_substring_pattern.py │ ├── 541_reverse_string_ii.py │ └── right_reverse_string.py └── tree │ ├── 144_binary_tree_preorder_traversal.py │ ├── 145_binary_tree_postorder_traversal.py │ └── 94_binary_tree_inorder_traversal.py └── log.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | 7 | # PyCharm 8 | .idea 9 | 10 | # Test 11 | Test 12 | tests/ 13 | # virtual environment 14 | venv 15 | 16 | # vscode 17 | .vscode 18 | 19 | 20 | -------------------------------------------------------------------------------- /2022/hj_23_del_least_char.py: -------------------------------------------------------------------------------- 1 | def del_least_char(s: str): 2 | # 先计算字符串中的个数 3 | str_count = dict() 4 | for i in s: 5 | if i in str_count: 6 | str_count[i] += 1 7 | else: 8 | str_count[i] = 1 9 | min_count = min(str_count.values()) 10 | ans = "" 11 | for c in s: 12 | if str_count[c] != min_count: 13 | ans += c 14 | return ans 15 | 16 | if __name__ == '__main__': 17 | print(del_least_char("aabcddd")) -------------------------------------------------------------------------------- /2022/hj_31_word_deced.py: -------------------------------------------------------------------------------- 1 | def descend(s: str): 2 | ans = [] 3 | current_word = [] 4 | for i in s: 5 | if i.isalpha(): 6 | current_word.append(i) 7 | else: 8 | if current_word: 9 | ans.insert(0, "".join(current_word)) 10 | current_word = [] 11 | if current_word: 12 | ans.insert(0, "".join(current_word)) 13 | return " ".join(ans) 14 | 15 | eval() -------------------------------------------------------------------------------- /2022/hj_56_perfect_numer.py: -------------------------------------------------------------------------------- 1 | # 描述 2 | # 完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。 3 | 4 | # 它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。 5 | 6 | # 例如:28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28。 7 | 8 | # 输入n,请输出n以内(含n)完全数的个数。 9 | 10 | # 数据范围: 1 \le n \le 5 \times 10^{5} \1≤n≤5×10 11 | # 5 12 | 13 | # 输入描述: 14 | # 输入一个数字n 15 | 16 | # 输出描述: 17 | # 输出不超过n的完全数的个数 18 | 19 | from json.tool import main 20 | 21 | 22 | def checkPerfectNumber(num): 23 | """ 24 | :type num: int 25 | :rtype: bool 26 | """ 27 | return num in (6,28,496,8128,33550336) 28 | # 2 常规法 29 | def checkPerfectNumber(num): 30 | if num <= 1: 31 | return False 32 | res = 1 33 | bound = int(num**0.5) 34 | i = 2 35 | while i <= bound: 36 | if num%i==0: 37 | res += i + num//i 38 | bound = min(bound,num//i) 39 | if res>num: 40 | return False 41 | i+=1 42 | if res==num: 43 | return True 44 | return False 45 | 46 | from collections import Count -------------------------------------------------------------------------------- /2022/hj_57_min_number_pair.py: -------------------------------------------------------------------------------- 1 | # 描述 2 | # 任意一个偶数(大于2)都可以由2个素数组成,组成偶数的2个素数有很多种情况,本题目要求输出组成指定偶数的两个素数差值最小的素数对。 3 | 4 | # 数据范围:输入的数据满足 4≤n≤1000 5 | # 输入描述: 6 | # 输入一个大于2的偶数 7 | 8 | # 输出描述: 9 | # 从小到大输出两个素数 10 | 11 | 12 | def cal_susu_pair(num: int): 13 | if num == 4: 14 | return [2, 2] 15 | half = num // 2 16 | for i in range(half, 3, -1): 17 | if is_susu(i) and is_susu(num-i): 18 | return [i, num-i] 19 | 20 | 21 | 22 | def is_susu(num): 23 | if num == 2 or num == 3: 24 | return True 25 | bound = int(num ** 0.5) 26 | for i in range(2, bound + 1): 27 | if num % i == 0: 28 | return False 29 | return True 30 | 31 | input_nums = [20, 30, 100, 1000] 32 | for i in input_nums: 33 | print(cal_susu_pair(i)) -------------------------------------------------------------------------------- /2022/hj_62_apples.py: -------------------------------------------------------------------------------- 1 | def cal(m, n): 2 | """ 3 | 求 Cn m+n 4 | """ 5 | return factorial(m+n) // (factorial(m) * factorial(n)) 6 | 7 | 8 | def factorial(n): 9 | """ 10 | 求阶乘 11 | """ 12 | ans = 1 13 | for i in range(1, n+1): 14 | ans *= i 15 | return ans 16 | 17 | -------------------------------------------------------------------------------- /2022/合并表记录.py: -------------------------------------------------------------------------------- 1 | while True: 2 | try: 3 | n = int(input()) 4 | ans = dict() 5 | for _ in range(n): 6 | k, v = map(int, input().split()) 7 | if k in ans: 8 | ans[k] += v 9 | else: 10 | ans[k] = v 11 | keys = ans.keys() 12 | keys.sort() 13 | for k in keys: 14 | print(k, ans[k]) 15 | except: 16 | break -------------------------------------------------------------------------------- /2022/质数因子.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def cal(num): 4 | ans = [] 5 | square = math.ceil(math.sqrt(num)) # 略大于或等于平方数的整数 6 | while num % 2 == 0: 7 | ans.append(2) 8 | num = num // 2 9 | for i in range(3, square, 2): 10 | while num % i == 0: 11 | ans.append(i) 12 | num = num // i 13 | if num > square: 14 | ans.append(num) 15 | return ans 16 | 17 | if __name__ == '__main__': 18 | print(cal(1111)) -------------------------------------------------------------------------------- /Classify/Array/11#Container With Most Water.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/container-with-most-water/description/ 2 | class Solution: 3 | # 1 4 | # 暴力法 5 | # Time Limit Exceeded 6 | def maxArea(self, height): 7 | ret = 0 8 | for i in range(len(height)-1): 9 | for j in range(i+1,len(height)): 10 | ret = max(ret,min(height[i],height[j])*(j-i)) 11 | return ret 12 | def maxArea(self, height): 13 | lpoint,rpoint=0,len(height)-1 14 | max_area = 0 15 | while lpointheight[lpoint]: 18 | lpoint+=1 19 | else: 20 | rpoint-=1 21 | return max_area 22 | 23 | -------------------------------------------------------------------------------- /Classify/Array/152#Maximum Product Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | B = nums[::-1] 8 | for i in range(1, len(nums)): 9 | nums[i] *= nums[i-1] or 1 10 | B[i] *= B[i-1] or 1 11 | return max(nums+B) 12 | 13 | def maxProduct(nums): 14 | maximum = big = small = nums[0] 15 | for n in nums[1:]: 16 | big, small = max(n, n * big, n * small), min(n, n * big, n * small) 17 | maximum = max(maximum, big) 18 | return maximum -------------------------------------------------------------------------------- /Classify/Array/289#Game of Life.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/game-of-life/ 2 | class Solution(object): 3 | def gameOfLife(self, board): 4 | """ 5 | :type board: List[List[int]] 6 | :rtype: void Do not return anything, modify board in-place instead. 7 | """ 8 | 9 | def count(x, y): 10 | res = 0 11 | for r in range(x - 1, x + 2): 12 | for c in range(y - 1, y + 2): 13 | if (r != x or c != y) and 0 <= r < len(board) and 0 <= c < len(board[0]) and board[r][c] > 0: 14 | res += 1 15 | return res 16 | 17 | for x in range(len(board)): 18 | for y in range(len(board[0])): 19 | board[x][y] = count(x, y) + 1 if board[x][y] == 1 else - count(x, y) 20 | 21 | for x in range(len(board)): 22 | for y in range(len(board[0])): 23 | board[x][y] = 1 if board[x][y] in {3, 4, -3} else 0 -------------------------------------------------------------------------------- /Classify/Array/31#Next Permutation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/next-permutation/description/ 2 | class Solution: 3 | def nextPermutation(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: void Do not return anything, modify nums in-place instead. 7 | """ 8 | 9 | i = len(nums) - 1 10 | while i - 1 >= 0 and nums[i - 1] >= nums[i]: 11 | i -= 1 12 | 13 | if i - 1 >= 0: 14 | j = i 15 | while j < len(nums) and nums[j] > nums[i - 1]: 16 | j += 1 17 | # swap the min-max number 18 | nums[i - 1], nums[j - 1] = nums[j - 1], nums[i - 1] 19 | m = i 20 | n = len(nums) - 1 21 | while m < n: 22 | nums[m], nums[n] = nums[n], nums[m] 23 | m += 1 24 | n -= 1 -------------------------------------------------------------------------------- /Classify/Array/39#Combination Sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/combination-sum/description/ 2 | class Solution: 3 | def combinationSum(self, candidates, target): 4 | """ 5 | :type candidates: List[int] 6 | :type target: int 7 | :rtype: List[List[int]] 8 | """ 9 | res = [] 10 | candidates.sort() 11 | 12 | def dfs(target, index, path): 13 | if target < 0: 14 | return # backtracking 15 | if target == 0: 16 | res.append(path) 17 | return 18 | for i in range(index, len(candidates)): 19 | dfs(target-candidates[i], i, path+[candidates[i]]) 20 | 21 | dfs(target, 0, []) 22 | return res -------------------------------------------------------------------------------- /Classify/Array/41#First Missing Positive.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/first-missing-positive/description/ 2 | class Solution: 3 | # 1 4 | # 先找出最大数m,构造一个1到m+1的集合M 5 | # 用集合M减去nums集合N生成的集合M-N 6 | # 消失的最小正数就是min(M-N) 7 | def firstMissingPositive(self, nums): 8 | if not nums: 9 | return 1 10 | max_num = max(nums) 11 | return min(set(range(1,max_num+2))-set(nums)) 12 | # 2 13 | # 使用循环,从1遍历到len(nums)+1 14 | def firstMissingPositive(self, nums): 15 | if len(nums)==0: 16 | return 1 17 | #nums.sort() 18 | # if nums[0]>1: 19 | # return 1 20 | for i in range(1,len(nums)+2): 21 | if i not in nums: 22 | return i -------------------------------------------------------------------------------- /Classify/Array/442#Find All Duplicates in an Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-all-duplicates-in-an-array/description/ 2 | class Solution: 3 | def findDuplicates(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: List[int] 7 | """ 8 | from collections import Counter 9 | mapping = Counter(nums) 10 | return [i for i,v in mapping.items() if v==2] 11 | def findDuplicates(self, nums): 12 | nums_unique = set (nums) 13 | nums_duplicate = [] 14 | for num in nums: 15 | if num not in nums_unique: 16 | nums_duplicate.append (num) 17 | else: nums_unique.remove (num) 18 | 19 | return nums_duplicate -------------------------------------------------------------------------------- /Classify/Array/509#Fibonacci Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, N): 3 | """ 4 | :type N: int 5 | :rtype: int 6 | """ 7 | m = 0 8 | n = 1 9 | if N == 0: 10 | return 0 11 | for i in range(N-1): 12 | temp = m + n 13 | m = n 14 | n = temp 15 | return n -------------------------------------------------------------------------------- /Classify/Array/581#Shortest Unsorted Continuous Subarray.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/ 2 | class Solution: 3 | # 1 4 | def findUnsortedSubarray(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | n = len(nums) 10 | cmax, cmin = -float('inf'), float('inf') 11 | l, r = 0, -1 12 | for i in range(n): 13 | cmax = max(cmax, nums[i]) 14 | cmin = min(cmin, nums[n - 1 - i]) 15 | if nums[i] != cmax: r = i 16 | if nums[n - 1 - i] != cmin: l = n - 1 - i 17 | return r - l + 1 18 | # 19 | # thank @lee215 20 | # 比较与排序好的数组,使用zip然比较 21 | def findUnsortedSubarray(self, nums): 22 | is_same = [a == b for a, b in zip(nums, sorted(nums))] 23 | return 0 if all(is_same) else len(nums) - is_same.index(False) - is_same[::-1].index(False) -------------------------------------------------------------------------------- /Classify/Array/63#Unique Paths II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/submissions/detail/193955775/ 2 | class Solution: 3 | def uniquePathsWithObstacles(self, obstacleGrid): 4 | """ 5 | :type obstacleGrid: List[List[int]] 6 | :rtype: int 7 | """ 8 | n = len(obstacleGrid) 9 | m = len(obstacleGrid[0]) 10 | dp = [[0]*m for i in range(n)] 11 | for i in range(n): 12 | if obstacleGrid[i][0] == 1: 13 | break 14 | dp[i][0] = 1 15 | for i in range(m): 16 | if obstacleGrid[0][i] == 1: 17 | break 18 | dp[0][i] = 1 19 | for i in range(1, n): 20 | for j in range(1, m): 21 | if obstacleGrid[i][j] == 0: 22 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 23 | else: 24 | pass 25 | return dp[n-1][m-1] -------------------------------------------------------------------------------- /Classify/Array/661#mage Smoother.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/image-smoother/description/ 2 | class Solution: 3 | def imageSmoother(self, M): 4 | """ 5 | :type M: List[List[int]] 6 | :rtype: List[List[int]] 7 | """ 8 | R, C = len(M), len(M[0]) 9 | ans = [[0] * C for _ in M] 10 | 11 | for r in range(R): 12 | for c in range(C): 13 | count = 0 14 | for nr in (r-1, r, r+1): 15 | for nc in (c-1, c, c+1): 16 | if 0 <= nr < R and 0 <= nc < C: 17 | ans[r][c] += M[nr][nc] 18 | count += 1 19 | ans[r][c] //= count 20 | return ans 21 | 22 | -------------------------------------------------------------------------------- /Classify/Array/665#Non-decreasing Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/non-decreasing-array/description/ 2 | class Solution: 3 | def checkPossibility(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: bool 7 | """ 8 | p = None 9 | for i in range(len(nums) - 1): 10 | if nums[i] > nums[i+1]: 11 | if p is not None: 12 | return False 13 | p = i 14 | return (p is None or p == 0 or p == len(nums)-2 or 15 | nums[p-1] <= nums[p+1] or nums[p] <= nums[p+2]) 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Classify/Array/674#Longest Continuous Increasing Subsequence.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/ 2 | class Solution: 3 | def findLengthOfLCIS(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | if len(nums) < 1: 9 | return 0 10 | temp = 1 11 | sum = 1 12 | for i in range(1, len(nums)): 13 | if nums[i] > nums[i-1]: 14 | sum += 1 15 | if sum > temp: 16 | temp = sum 17 | else: 18 | sum = 1 19 | return temp -------------------------------------------------------------------------------- /Classify/Array/695#Max Area of Island.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/max-area-of-island/description/ 2 | class Solution: 3 | def maxAreaOfIsland(self, grid): 4 | max_size = 0 5 | rows, cols = len(grid), len(grid[0]) 6 | def dfs(i, j, size): 7 | if not (0 <= i < rows and 0 <= j < cols) or grid[i][j] in (-1, 0): 8 | return 9 | size[0] += 1 10 | grid[i][j] = -1 11 | for direction in ((0, 1), (1, 0), (-1, 0), (0, -1)): 12 | dfs(i + direction[0], j + direction[1], size) 13 | for i in range(rows): 14 | for j in range(cols): 15 | size = [0] 16 | dfs(i, j, size) 17 | max_size = max(max_size, size[0]) 18 | return max_size -------------------------------------------------------------------------------- /Classify/Array/697#Degree of an Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/degree-of-an-array/description/ 2 | class Solution(object): 3 | 4 | def findShortestSubArray(self, nums): 5 | left, right, count = {}, {}, {} 6 | for i, x in enumerate(nums): 7 | if x not in left: 8 | left[x] = i 9 | right[x] = i 10 | count[x] = count.get(x, 0) + 1 11 | 12 | ans = len(nums) 13 | degree = max(count.values()) 14 | for x in count: 15 | if count[x] == degree: 16 | ans = min(ans, right[x] - left[x] + 1) 17 | return ans 18 | def findShortestSubArray(self, nums): 19 | c = Counter(nums) 20 | count = max(c.values()) 21 | if count == 1: 22 | return 1 23 | rnums = nums[-1::-1] 24 | 25 | return len(nums) - max([rnums.index(n) + nums.index(n) for (n, val) in c.items() if val == count]) 26 | -------------------------------------------------------------------------------- /Classify/Array/717#1-bit and 2-bit Characters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/1-bit-and-2-bit-characters/description/ 2 | class Solution: 3 | # 1 4 | # 只有0,10,1 5 | # 那么遇到1就移动两位,遇到0就移动一位 6 | # 如果最后能够遍历完,说明是true 7 | def isOneBitCharacter(self, bits): 8 | i = 0 9 | while i < len(bits) - 1: 10 | i += bits[i] + 1 11 | return i == len(bits) - 1 12 | # 2 13 | # 14 | def isOneBitCharacter(self, bits): 15 | parity = bits.pop() 16 | while bits and bits.pop(): 17 | parity ^= 1 18 | return parity == 0 19 | 20 | 21 | -------------------------------------------------------------------------------- /Classify/Array/719#Find K-th Smallest Pair Distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countPairsLTE(self, array, value): 3 | ans = 0 4 | for i in range(len(array)): 5 | ans += bisect.bisect_right(array, array[i] + value, lo = i) - i - 1 6 | return ans 7 | 8 | def smallestDistancePair(self, nums, k): 9 | """ 10 | :type nums: List[int] 11 | :type k: int 12 | :rtype: int 13 | """ 14 | nums.sort() 15 | low, high = min([abs(nums[i] - nums[i+1]) for i in range(len(nums) - 1)]), abs(nums[0] - nums[~0]) 16 | while low < high: 17 | mid = (low + high)//2 18 | if self.countPairsLTE(nums, mid) < k: 19 | low = mid + 1 20 | else: 21 | high = mid 22 | return low -------------------------------------------------------------------------------- /Classify/Array/724#Find Pivot Index.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-pivot-index/description/ 2 | class Solution: 3 | # 1 4 | # 需要注意,pivotindex可以是头部和尾部 5 | # 需要考虑[-1,-1,-1,0,1,1]这种情况pivotindex为0 6 | def pivotIndex(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | S = sum(nums) 12 | leftsum = 0 13 | for i, x in enumerate(nums): 14 | if leftsum == (S - leftsum - x): 15 | return i 16 | leftsum += x 17 | return -1 18 | -------------------------------------------------------------------------------- /Classify/Array/747#Largest Number At Least Twice of Others.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ 2 | class Solution: 3 | # 1 使用heapq 4 | def dominantIndex(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | import heapq 10 | if len(nums)<2: 11 | return 0 12 | max1,max2 = heapq.nlargest(2,nums) 13 | return -1 if max1/2= 2*second_num: 28 | return origin.index(max_num) 29 | else: 30 | return -1 -------------------------------------------------------------------------------- /Classify/Array/830#Positions of Large Groups.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/positions-of-large-groups/description/ 2 | class Solution: 3 | def largeGroupPositions(self, S): 4 | """ 5 | :type S: str 6 | :rtype: List[List[int]] 7 | """ 8 | ans = [] 9 | i = 0 # The start of each group 10 | for j in range(len(S)): 11 | if j == len(S) - 1 or S[j] != S[j+1]: 12 | if j-i+1 >= 3: 13 | ans.append([i, j]) 14 | i = j+1 15 | return ans 16 | 17 | def largeGroupPositions(self, S): 18 | """ 19 | :type S: str 20 | :rtype: List[List[int]] 21 | """ 22 | i, j, n, res = 0, 0, len(S), [] 23 | 24 | while j < n: 25 | while j < n and S[i] == S[j]: 26 | j += 1 27 | if j - i >= 3: 28 | res.append((i, j-1)) 29 | i = j 30 | return res -------------------------------------------------------------------------------- /Classify/Array/832#Flipping an Image.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/flipping-an-image/description/ 2 | class Solution: 3 | # in-place reverse 4 | def flipAndInvertImage(self, A): 5 | """ 6 | :type A: List[List[int]] 7 | :rtype: List[List[int]] 8 | """ 9 | for r in range(len(A)): 10 | for c in range(len(A[0])): 11 | # A[r][c] = 1-A[r][c] 12 | A[r][c] ^= 1 13 | for r in range(len(A)): 14 | A[r].reverse() 15 | return A 16 | # another space 17 | def flipAndInvertImage(self, A): 18 | """ 19 | :type A: List[List[int]] 20 | :rtype: List[List[int]] 21 | """ 22 | reverse = [] 23 | for i in A: 24 | temp = [] 25 | for j in reversed(i): 26 | if(j==0): 27 | temp.append(1) 28 | else: 29 | temp.append(0) 30 | reverse.append(temp) 31 | return (reverse) 32 | -------------------------------------------------------------------------------- /Classify/Array/84#Largest Rectangle in Histogram.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | class Solution: 3 | def largestRectangleArea(self, heights): 4 | """ 5 | :type heights: List[int] 6 | :rtype: int 7 | """ 8 | heights.append(0) 9 | stack = [-1] 10 | ans = 0 11 | for i in range(len(heights)): 12 | while heights[i] < heights[stack[-1]]: 13 | h = heights[stack.pop()] 14 | w = i - stack[-1] - 1 15 | ans = max(ans, h * w) 16 | stack.append(i) 17 | heights.pop() 18 | return ans -------------------------------------------------------------------------------- /Classify/Array/85#Maximal Rectangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximalRectangle(self, matrix): 3 | """ 4 | :type matrix: List[List[str]] 5 | :rtype: int 6 | """ 7 | if not matrix or not matrix[0]: 8 | return 0 9 | n = len(matrix[0]) 10 | height = [0] * (n + 1) 11 | ans = 0 12 | for row in matrix: 13 | for i in range(n): 14 | height[i] = height[i] + 1 if row[i] == '1' else 0 15 | stack = [-1] 16 | for i in range(n + 1): 17 | while height[i] < height[stack[-1]]: 18 | h = height[stack.pop()] 19 | w = i - 1 - stack[-1] 20 | ans = max(ans, h * w) 21 | stack.append(i) 22 | return ans -------------------------------------------------------------------------------- /Classify/Array/867#Transpose Matrix.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/transpose-matrix/description/ 2 | class Solution: 3 | # 1 4 | # 常规法 5 | # O(mn) 6 | def transpose(self, A): 7 | """ 8 | :type A: List[List[int]] 9 | :rtype: List[List[int]] 10 | """ 11 | trans = [] 12 | for c in range(len(A[0])): 13 | temp = [] 14 | for r in range(len(A)): 15 | temp.append(A[r][c]) 16 | trans.append(temp) 17 | return trans 18 | # 2 19 | # 提前构造矩阵,利用变化式 a[i][j] = b[j][i] 20 | def transpose(self, A): 21 | M,N = len(A),len(A[0]) 22 | trans = [[None for m in range(M)] for n in range(N)] 23 | for i in range(M): 24 | for j in range(N): 25 | trans[j][i] = trans[i][j] 26 | return trans -------------------------------------------------------------------------------- /Classify/Array/888#Fair Candy Swap.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/fair-candy-swap/description/ 2 | class Solution: 3 | # 1 TLE 没通过 4 | def fairCandySwap(self, A, B): 5 | """ 6 | :type A: List[int] 7 | :type B: List[int] 8 | :rtype: List[int] 9 | """ 10 | sum_A = sum(A) 11 | sum_B = sum(B) 12 | diff = sum_A-sum_B 13 | for i in set(A): 14 | if i-diff//2 in set(B): 15 | return [i,i-diff//2] 16 | # 2 用set 17 | def fairCandySwap(self, A, B): 18 | """ 19 | :type A: List[int] 20 | :type B: List[int] 21 | :rtype: List[int] 22 | """ 23 | sb = set(B) 24 | diff = (sum(B) - sum(A)) // 2 25 | for num in A: 26 | if num + diff in sb: 27 | return num, num + diff 28 | -------------------------------------------------------------------------------- /Classify/Array/896#Monotonic Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/monotonic-array/description/ 2 | class Solution: 3 | # 1 4 | def isMonotonic(self, A): 5 | is_reverse = False 6 | if A[0]>A[-1]: 7 | is_reverse=True 8 | B = sorted(A,reverse=is_reverse) 9 | return A==B 10 | # 2 11 | def isMonotonic(self, A): 12 | return A==sorted(B,reverse=True if A[0]>A[-1] else False) 13 | # 3 14 | def isMonotonic(self, A): 15 | if not A or len(A) < 2: 16 | return True 17 | if A[0] <= A[-1]: 18 | left = A[0] 19 | for x in A: 20 | if x >= left: 21 | left = x 22 | else: 23 | return False 24 | else: 25 | left = A[0] 26 | for x in A: 27 | if x <= left: 28 | left = x 29 | else: 30 | return False 31 | 32 | return True -------------------------------------------------------------------------------- /Classify/Array/905#Sort Array By Parity.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sort-array-by-parity/description/ 2 | class Solution: 3 | # 1 4 | def sortArrayByParity(self, A): 5 | """ 6 | :type A: List[int] 7 | :rtype: List[int] 8 | """ 9 | 让奇数在后,偶数在前 10 | 两点法 11 | p1,p2 = 0,len(A)-1 12 | while p1=2 17 | 18 | def hasGroupsSizeX(self, deck): 19 | return reduce(fractions.gcd, collections.Counter(deck).values()) > 1 20 | 21 | -------------------------------------------------------------------------------- /Classify/Array/922#Sort Array By Parity II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sort-array-by-parity-ii/description/ 2 | class Solution: 3 | def sortArrayByParityII(self, A): 4 | odd_list = [] 5 | even_list = [] 6 | 7 | for i in A: 8 | if i % 2 == 1: 9 | odd_list.append(i) 10 | else: 11 | even_list.append(i) 12 | 13 | result = [None]*(len(odd_list)+len(even_list)) 14 | result[::2] = even_list 15 | result[1::2] = odd_list 16 | return result 17 | 18 | def sortArrayByParityII(self, A): 19 | lastEvenPlace = 0 20 | lastOddPlace = 1 21 | result = A.copy() 22 | for i in A: 23 | if i%2 == 0: 24 | result[lastEvenPlace] = i 25 | lastEvenPlace += 2 26 | else: 27 | result[lastOddPlace] = i 28 | lastOddPlace += 2 29 | return result -------------------------------------------------------------------------------- /Classify/Array/941#Valid Mountain Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-mountain-array/description/ 2 | class Solution: 3 | def validMountainArray(self, A): 4 | """ 5 | :type A: List[int] 6 | :rtype: bool 7 | """ 8 | i, j, n = 0, len(A) - 1, len(A) 9 | while i + 1 < n and A[i] < A[i + 1]: i += 1 10 | while j > 0 and A[j - 1] > A[j]: j -= 1 11 | return 0 < i == j < n - 1 12 | 13 | def validMountainArray(self, A): 14 | """ 15 | :type A: List[int] 16 | :rtype: bool 17 | """ 18 | if len(A) < 3: return False 19 | if A[0] >= A[1]: return False 20 | climb = True 21 | for a,b in zip(A,A[1:]): 22 | if climb: 23 | if ab: climb = False; continue 25 | return False 26 | else: 27 | if a>b: continue 28 | return False 29 | return not climb -------------------------------------------------------------------------------- /Classify/HashTable/594#Longest Harmonious Subsequence.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-harmonious-subsequence/description/ 2 | """ 3 | We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. 4 | 5 | Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. 6 | 7 | Example 1: 8 | Input: [1,3,2,2,5,2,3,7] 9 | Output: 5 10 | Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 11 | Note: The length of the input array will not exceed 20,000. 12 | """ 13 | class Solution: 14 | def findLHS(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: int 18 | """ 19 | from collections import Counter 20 | res = 0 21 | mapping = Counter(nums) 22 | for k in mapping.keys(): 23 | if k+1 in mapping: 24 | res = max(res, mapping.get(k) + mapping.get(k+1)) 25 | return res 26 | 27 | 28 | -------------------------------------------------------------------------------- /Classify/HashTable/771#Jewels and Stones.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/jewels-and-stones/description/ 2 | """ 3 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. 4 | Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 5 | 6 | The letters in J are guaranteed distinct, and all characters in J and S are letters. 7 | Letters are case sensitive, so "a" is considered a different type of stone from "A". 8 | 9 | Example 1: 10 | Input: J = "aA", S = "aAAbbbb" 11 | Output: 3 12 | 13 | Example 2: 14 | Input: J = "z", S = "ZZ" 15 | Output: 0 16 | Note: 17 | 18 | S and J will consist of letters and have length at most 50. 19 | The characters in J are distinct. 20 | """ 21 | 22 | 23 | class Solution: 24 | # 1 25 | # 97.83% 26 | def numJewelsInStones(self, J, S): 27 | """ 28 | :type J: str 29 | :type S: str 30 | :rtype: int 31 | """ 32 | ret = 0 33 | for i in J: 34 | ret += S.count(i) 35 | return ret -------------------------------------------------------------------------------- /Classify/Sort/Readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EachenKuang/LeetCode/b3e4a551ea1dc7ac89c0ea031df021ece5a261f8/Classify/Sort/Readme.md -------------------------------------------------------------------------------- /Classify/Sort/bubble_sort.py: -------------------------------------------------------------------------------- 1 | class BubbleSort: 2 | def bubble_sort(self, nums): 3 | for i in range(len(nums)): 4 | is_sort = False 5 | for j in range(len(nums) - 1 - i): 6 | if nums[j] > nums[j+1]: 7 | # 交换,每次将最大的数放置在 len-i-1 8 | is_sort = True 9 | nums[j], nums[j+1] = nums[j+1], nums[j] 10 | if not is_sort: 11 | return nums 12 | return nums 13 | 14 | 15 | if __name__ == '__main__': 16 | nums = [1, 1, 3, 2, 3, 4, 10, 7, 9] 17 | solution = BubbleSort() 18 | print(solution.bubble_sort(nums)) -------------------------------------------------------------------------------- /Classify/Sort/insertion_sort.py: -------------------------------------------------------------------------------- 1 | class InsertionSort: 2 | def insertion_sort(self, nums): 3 | for i in range(1, len(nums)): 4 | current = i - 1 5 | insert_value = nums[i] 6 | while current >= 0 and insert_value < nums[current]: 7 | # 调整需要插入的值,找到需要插入的位置,其到 current ~ i 统一右移 8 | nums[current + 1] = nums[current] 9 | current -= 1 10 | nums[current + 1] = insert_value 11 | return nums 12 | 13 | 14 | if __name__ == '__main__': 15 | nums = [1, 1, 2, 3, 3, 4, 4, 7, 9] 16 | solution = InsertionSort() 17 | print(solution.insertion_sort(nums)) -------------------------------------------------------------------------------- /Classify/Sort/select_sort.py: -------------------------------------------------------------------------------- 1 | class SelectSort: 2 | def select_sort(self, nums): 3 | for i in range(len(nums)-1): 4 | min_index = i 5 | for j in range(i+1, len(nums)): 6 | # 寻找 i~n 中最小的数,然后放置到 i 7 | if nums[min_index] > nums[j]: 8 | min_index = j 9 | # 交换 10 | if min_index != i: 11 | nums[min_index], nums[i] = nums[i], nums[min_index] 12 | return nums 13 | 14 | 15 | if __name__ == '__main__': 16 | nums = [10, 13, 2, 33, 3, 4, 4, 7, 9] 17 | solution = SelectSort() 18 | print(solution.select_sort(nums)) 19 | -------------------------------------------------------------------------------- /Classify/Sort/shell_sort.py: -------------------------------------------------------------------------------- 1 | class ShellSort: 2 | def shell_sort(self, nums): 3 | n = len(nums) 4 | gap = n // 2 5 | while gap > 0: 6 | for i in range(gap, n): 7 | current = i - gap 8 | insert_value = nums[i] 9 | while current >= 0 and insert_value < nums[current]: 10 | # 调整需要插入的值,找到需要插入的位置,其到 current ~ i 统一右移 11 | nums[current + gap] = nums[current] 12 | current -= gap 13 | nums[current + gap] = insert_value 14 | gap //= 2 15 | return nums 16 | 17 | 18 | if __name__ == '__main__': 19 | nums = [10, 13, 2, 33, 3, 4, 4, 7, 9] 20 | solution = ShellSort() 21 | print(solution.shell_sort(nums)) -------------------------------------------------------------------------------- /Classify/String/12#Integer to Roman.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/integer-to-roman/description/ 2 | class Solution: 3 | # 1 4 | # 将1~3999的十进制位数全列出来 5 | # 然后利用进制计算 6 | def intToRoman(self, num): 7 | """ 8 | :type num: int 9 | :rtype: str 10 | """ 11 | M = ["", "M", "MM", "MMM"] 12 | C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] 13 | X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] 14 | I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] 15 | return M[num//1000] + C[(num%1000)//100] + X[(num%100)//10] + I[num%10] 16 | # 2 17 | # 相较1中的暴力方法,2中通过减法,得到结果 18 | def intToRoman1(self, num): 19 | values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] 20 | numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] 21 | res, i = "", 0 22 | while num: 23 | res += (num//values[i]) * numerals[i] 24 | num %= values[i] 25 | i += 1 26 | return res -------------------------------------------------------------------------------- /Classify/String/151#Reverse Words in a String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-words-in-a-string/description/ 2 | class Solution(object): 3 | def reverseWords(self, s): 4 | """ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | return " ".join(reversed(s.split())) -------------------------------------------------------------------------------- /Classify/String/49#Group Anagrams.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/group-anagrams/description/ 2 | class Solution: 3 | # 1 4 | # 用(2,0,1,1,..)的26位元组来表示映射 5 | # defaultdict()可以存储list 6 | def groupAnagrams(self, strs): 7 | """ 8 | :type strs: List[str] 9 | :rtype: List[List[str]] 10 | """ 11 | ans = collections.defaultdict() 12 | for s in strs: 13 | ans[tuple(sorted(s))].append(s) 14 | return ans.values() 15 | 16 | def groupAnagrams(strs): 17 | ans = collections.defaultdict(list) 18 | for s in strs: 19 | count = [0] * 26 20 | for c in s: 21 | count[ord(c) - ord('a')] += 1 22 | ans[tuple(count)].append(s) 23 | return ans.values() -------------------------------------------------------------------------------- /Classify/String/521#Longest Uncommon Subsequence I.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-uncommon-subsequence-i/description/ 2 | # 这题没什么意义 3 | # For strings A, B, when len(A) > len(B), 4 | # the longest possible subsequence of either A or B is A, 5 | # and no subsequence of B can be equal to A. Answer: len(A). 6 | 7 | When len(A) == len(B), the only subsequence of B equal to A is B; so as long as A != B, the answer remains len(A). 8 | 9 | When A == B, any subsequence of A can be found in B and vice versa, so the answer is -1. 10 | class Solution: 11 | def findLUSlength(self, a, b): 12 | """ 13 | :type a: str 14 | :type b: str 15 | :rtype: int 16 | """ 17 | if a == b: 18 | return -1 19 | return max(len(a),len(b)) -------------------------------------------------------------------------------- /Classify/String/537#Complex Number Multiplication.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/complex-number-multiplication/description/ 2 | class Solution: 3 | def complexNumberMultiply(self, a, b): 4 | """ 5 | :type a: str 6 | :type b: str 7 | :rtype: str 8 | """ 9 | # a_real = int(a[:a.find('+')]) 10 | # a_ima = int(a[a.find('+')+1:-1]) 11 | # b_real = int(b[:b.find('+')]) 12 | # b_ima = int(b[b.find('+')+1:-1]) 13 | res_real = a_real*b_real-a_ima*b_ima 14 | res_ima = a_real*b_ima+a_ima*b_real 15 | a_real, a_ima = list(map(int,a[:-1].split('+'))) 16 | b_real, b_ima = list(map(int,b[:-1].split('+'))) 17 | res_real = a_real*b_real-a_ima*b_ima 18 | res_ima = a_real*b_ima+a_ima*b_real 19 | 20 | return "{0}+{1}i".format(res_real, res_ima) -------------------------------------------------------------------------------- /Classify/String/539#Minimum Time Difference.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-time-difference/description/ 2 | #24*60 = 1440 种情况 3 | class Solution: 4 | def findMinDifference(self, timePoints): 5 | """ 6 | :type timePoints: List[str] 7 | :rtype: int 8 | """ 9 | def diff(tp1,tp2): 10 | return 60*(int(tp1[0:2])-int(tp2[0:2]))+int(tp1[3:])-int(tp2[3:]) 11 | 12 | if len(set(timePoints))=2) 19 | -------------------------------------------------------------------------------- /Classify/String/657#Robot Return to Origin.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/robot-return-to-origin/description/ 2 | class Solution: 3 | def judgeCircle(self, moves): 4 | """ 5 | :type moves: str 6 | :rtype: bool 7 | """ 8 | return moves.count('L')==moves.count('R') and moves.count('U')==moves.count('D') -------------------------------------------------------------------------------- /Classify/String/686#Repeated String Match.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/repeated-string-match/description/ 2 | class Solution: 3 | def __init__(self, arg): 4 | super(ClassName, self).__init__() 5 | self.arg = arg 6 | 7 | # beat 99.99% 8 | def repeatedStringMatch(self, A, B): 9 | if set(A) != set(B): 10 | if len(A) < len(B): 11 | return -1 12 | # 上面的三行用来过滤大量的-1 case 13 | q = (len(B) - 1) // len(A) + 1 14 | for i in range(2): 15 | if B in A * (q+i): return q+i 16 | return -1 -------------------------------------------------------------------------------- /Classify/String/696#Count Binary Substrings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-binary-substrings/description/ 2 | class Solution: 3 | def countBinarySubstrings(self, s): 4 | """ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | s = list(map(len, s.replace('01', '0 1').replace('10', '1 0').split())) 9 | return sum(min(a, b) for a, b in zip(s, s[1:])) 10 | -------------------------------------------------------------------------------- /Classify/String/709#To Lower Case.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/to-lower-case/description/ 2 | class Solution: 3 | # 1 使用内置函数lower() 4 | def toLowerCase(self, str): 5 | """ 6 | :type str: str 7 | :rtype: str 8 | """ 9 | return str.lower() 10 | # 2 对于A~Z的字符进行转换 Ascll码+32 11 | def toLowerCase2(self, str): 12 | result = "" 13 | for c in str: 14 | if c >="A" and c<="Z": 15 | result= result+chr(ord(c)+32) 16 | else: 17 | result =result+ c 18 | return result -------------------------------------------------------------------------------- /Classify/String/767#Reorganize String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reorganize-string/description/ 2 | class Solution: 3 | # 1 4 | # 先把字符串排成按照重复数量从大到小的顺序的 5 | # 例如:"abbbccdddde" => "ddddbbbccae" 6 | # 然后将字符串分成两节插空排 7 | def reorganizeString(self, S): 8 | a = sorted(sorted(S), key=S.count) 9 | h = len(a) / 2 10 | a[1::2], a[::2] = a[:h], a[h:] 11 | return ''.join(a) * (a[-1:] != a[-2:-1]) 12 | -------------------------------------------------------------------------------- /Classify/String/791#Custom Sort String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/custom-sort-string/description/ 2 | from collections import Counter 3 | class Solution: 4 | # 1 5 | # beat 100% 6 | # 1、使用collections.Counter() 将字符串返回成计数字典 7 | # 2、字典的keys()可以直接使用set操作 8 | # 3、最后结果由join连接所有小片段,减少内存使用 9 | # 4、生成器比List快 10 | def customSortString(self, S, T): 11 | """ 12 | :type S: str 13 | :type T: str 14 | :rtype: str 15 | """ 16 | c = Counter(T) 17 | lefted = c.keys()-set(S) 18 | return ''.join(letter*c[letter] for letter in ([s for s in S]+[l for l in lefted])) 19 | -------------------------------------------------------------------------------- /Classify/String/804#Unique Morse Code Words.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-morse-code-words/description/ 2 | class Solution: 3 | def uniqueMorseRepresentations(self, words): 4 | """ 5 | :type words: List[str] 6 | :rtype: int 7 | """ 8 | concatenation = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 9 | letter = "abcdefghijklmnopqrstuvwxyz" 10 | mapping = dict(zip(letter,concatenation)) 11 | return len(set("".join([mapping[c] for c in word]) for word in words)) -------------------------------------------------------------------------------- /Classify/String/809#Expressive Words.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/expressive-words/description/ 2 | class Solution: 3 | def expressiveWords(self, S, words): 4 | """ 5 | :type S: str 6 | :type words: List[str] 7 | :rtype: int 8 | """ 9 | return sum(self.check(S, W) for W in words) 10 | def check(self, S, W): 11 | i, j, i2, j2, n, m = 0, 0, 0, 0, len(S), len(W) 12 | while i < n and j < m: 13 | if S[i] != W[j]: return False 14 | while i2 < n and S[i2] == S[i]: i2 += 1 15 | while j2 < m and W[j2] == W[j]: j2 += 1 16 | if i2 - i != j2 - j and i2 - i < max(3, j2 - j): return False 17 | i, j = i2, j2 18 | return i == n and j == m -------------------------------------------------------------------------------- /Classify/String/819#Most Common Word.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/most-common-word/description/ 2 | from collections import Counter 3 | class Solution: 4 | def mostCommonWord(self, paragraph, banned): 5 | """ 6 | :type paragraph: str 7 | :type banned: List[str] 8 | :rtype: str 9 | """ 10 | count=collections.Counter(piece for piece in re.split('[ !?\',;.]',paragraph.lower()) if piece) 11 | banned=set(banned) 12 | return max((item for item in count.items() if item[0] not in banned),key=operator.itemgetter(1))[0] 13 | 14 | # re.split 15 | # 函数 re.split() 是非常实用的,因为它允许你为分隔符指定多个正则模式。 16 | # 比如,分隔符可以是逗号,分号或者是空格,并且后面紧跟着任意个的空格。 17 | # 只要这个模式被找到,那么匹配的分隔符两边的实体都会被当成是结果中的元素返回。 18 | # 返回结果为一个字段列表,这个跟 str.split() 返回值类型是一样的。 -------------------------------------------------------------------------------- /Classify/String/833#Find And Replace in String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-and-replace-in-string/description/ 2 | class Solution(object): 3 | # 1 4 | # 反序很关键,可以从右往左遍历使用index 5 | # 利用zip函数 6 | def findReplaceString(self, S, indexes, sources, targets): 7 | """ 8 | :type S: str 9 | :type indexes: List[int] 10 | :type sources: List[str] 11 | :type targets: List[str] 12 | :rtype: str 13 | """ 14 | listOfS = list(S) 15 | distance = 0 16 | for index,source,target in sorted(zip(indexes, sources, targets),reverse=True): 17 | if S[i:i + len(s)] == s: 18 | listOfS[index:index+len(source)]=target 19 | return "".join(listOfS) 20 | 21 | def findReplaceString2(self, S, indexes, sources, targets): 22 | for i, s, t in sorted(zip(indexes, sources, targets), reverse=True): 23 | S = S[:i] + t + S[i + len(s):] if S[i:i + len(s)] == s else S 24 | return S -------------------------------------------------------------------------------- /Classify/String/859#Buddy Strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/buddy-strings/description/ 2 | class Solution: 3 | # 1 4 | def buddyStrings(self, A, B): 5 | """ 6 | :type A: str 7 | :type B: str 8 | :rtype: bool 9 | """ 10 | if set(A)!=set(B): 11 | return False 12 | count = 0 13 | sum = 0 14 | for i,j in zip(A,B): 15 | if ord(i)-ord(j) != 0: 16 | sum += ord(i)-ord(j) 17 | count+=1 18 | if count>2: 19 | return False 20 | # if count==2: 21 | # return True 22 | # else: 23 | # if len(set(A)) nums[i-1]: 11 | # ans += nums[i] - nums[i-1] 12 | # return ans + minus_count 13 | ans = 0 14 | for i in range(1, len(a)): 15 | if a[i] >= a[i-1]: 16 | ans += a[i] - a[i-1] 17 | return ans 18 | 19 | 20 | print(tab([1,2,3,2,1])) 21 | print(tab([2,3,3,0,2,1])) 22 | print(tab([0, 1, 2, 0, 2, 4, 2, 1, 0])) 23 | print(tab([0, 0])) 24 | print(tab([1, 1, 1, 0, 11])) 25 | print(tab([8,8])) 26 | 27 | # 9 28 | # 0 1 2 0 2 4 2 1 0 29 | 30 | # while True: 31 | # try: 32 | # n = int(input()) 33 | # nums = map(int, input().split()) 34 | # print(tab(nums)) 35 | # except: 36 | # break -------------------------------------------------------------------------------- /LeetCodeWeekly/April/Week1/single-number.py: -------------------------------------------------------------------------------- 1 | # Given a non-empty array of integers, every element appears twice except for one. Find that single one. 2 | # 3 | # Note: 4 | # 5 | # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | # 7 | # Example 1: 8 | # 9 | # Input: [2,2,1] 10 | # Output: 1 11 | # 12 | # Example 2: 13 | # 14 | # Input: [4,1,2,1,2] 15 | # Output: 4 16 | from functools import reduce 17 | 18 | 19 | # 方法一: 20 | # 直接使用异或操作,因为两个相同的数异或的结果是0,0和任何数异或的结果为任何数 21 | # 4 ^ 4 = 0 and 0 ^ n = n 22 | # 所以,对所有数进行连续异或操作就可以得出单独的那个数 23 | class Solution: 24 | def notOr(self, a, b): 25 | return a ^ b 26 | 27 | def singleNumber(self, nums: [int]) -> int: 28 | return reduce(self.notOr, nums) 29 | 30 | # 方法二: 31 | # 放入字典中,作为计数器,得出最后数量为1的那个key即可 32 | # 这里可以引入Counter这个库 33 | # from collections import Counter 34 | 35 | 36 | if __name__ == '__main__': 37 | solution = Solution() 38 | assert solution.singleNumber([2, 2, 1]) == 1 39 | assert solution.singleNumber([4, 1, 2, 1, 2]) == 4 40 | -------------------------------------------------------------------------------- /LeetCodeWeekly/meta_class.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right -------------------------------------------------------------------------------- /Others/README.md: -------------------------------------------------------------------------------- 1 | # Something Else 2 | ### Contact 3 | [*Eachen Kuang's* **LeetCode**](https://leetcode.com/eachenkuang/) 4 | [*Eachen Kuang's* **Zhihu**](https://www.zhihu.com/people/po-xiao-chen/) 5 | [*Eachen Kuang's* **WebSite**(废弃)](https://www.eachen.online/) 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 2 | 3 | ### Introduction 4 | This website is used to record the process of solving problems in [**LeetCode**](https://leetcode.com/). 5 | On the one hand, I can develop a habit of solving problems, on the other hand, 6 | I can motivate myself to challenge difficulties one after another. 7 | If you are interested in it, please join us! 8 | 9 | ### Tree 10 | ```shell 11 | . 12 | ├── Classify 13 | │   ├── Array 14 | │   ├── BinarySearch 15 | │   ├── HashTable 16 | │   ├── Sort 17 | │   └── String 18 | ├── LeetCodeWeekly 19 | ├── Others 20 | ├── code 21 | └── SwordOffer 22 | ``` 23 | ### Link 24 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_07.py: -------------------------------------------------------------------------------- 1 | # https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof 2 | # 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 3 | # 4 | # 例如,给出 5 | # 6 | # 前序遍历 preorder = [3,9,20,15,7] 7 | # 中序遍历 inorder = [9,3,15,20,7] 8 | # 返回如下的二叉树: 9 | # 10 | # 3 11 | # / \ 12 | # 9 20 13 | # / \ 14 | # 15 7 15 | # 16 | # 限制: 17 | # 18 | # 0 <= 节点个数 <= 5000 19 | from typing import List 20 | 21 | from SwordOffer.DataStruct import TreeNode 22 | 23 | 24 | class Solution: 25 | def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 26 | """递归的方法""" 27 | if not preorder: 28 | return None 29 | root_val = preorder[0] 30 | root = TreeNode(root_val) 31 | index = inorder.index(root_val) 32 | root.left = self.buildTree(preorder[1:index+1], inorder[0:index]) 33 | root.right = self.buildTree(preorder[index+1:], inorder[index+1:]) 34 | return root 35 | 36 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_10_2.py: -------------------------------------------------------------------------------- 1 | # 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n级的台阶总共有多少种跳法。 2 | # 3 | # 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 4 | # 5 | # 示例 1: 6 | # 7 | # 输入:n = 2 8 | # 输出:2 9 | # 示例 2: 10 | # 11 | # 输入:n = 7 12 | # 输出:21 13 | # 示例 3: 14 | # 15 | # 输入:n = 0 16 | # 输出:1 17 | # 提示: 18 | # 19 | # 0 <= n <= 100 20 | # 21 | # 来源:力扣(LeetCode) 22 | # 链接:https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof 23 | 24 | """ 25 | f(n) 26 | f(0) = 1 27 | f(1) = 1 28 | f(2) = f(0) + f(1) 29 | f(n) = f(n-1) + f(n-2) 30 | 就是斐波那契 31 | """ 32 | class Solution: 33 | CONSTANT = 1000000007 34 | def numWays(self, n: int) -> int: 35 | if n == 0 or n == 1: 36 | return 1 37 | f1 = f2 = 1 38 | for _ in range(2, n + 1): 39 | temp = f1 + f2 40 | f1 = f2 % self.CONSTANT 41 | f2 = temp % self.CONSTANT 42 | return f2 % self.CONSTANT -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_14.py: -------------------------------------------------------------------------------- 1 | # 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m-1] 。请问 k[0]*k[1]*...*k[m-1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。 2 | # 3 | # 示例 1: 4 | # 5 | # 输入: 2 6 | # 输出: 1 7 | # 解释: 2 = 1 + 1, 1 × 1 = 1 8 | # 示例 2: 9 | # 10 | # 输入: 10 11 | # 输出: 36 12 | # 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36 13 | # 提示: 14 | # 15 | # 2 <= n <= 58 16 | # 17 | # 来源:力扣(LeetCode) 18 | # 链接:https://leetcode-cn.com/problems/jian-sheng-zi-lcof 19 | import math 20 | class Solution: 21 | def cuttingRope(self, n: int) -> int: 22 | dp = [0] * (n + 1) 23 | dp[2] = 1 24 | for i in range(3, n + 1): 25 | for j in range(2, i): 26 | dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j])) 27 | return dp[n] 28 | 29 | def cuttingRope_2(self, n: int) -> int: 30 | """ 31 | 尽量形成多个3,剩下4的时候分成2个2 32 | """ 33 | if n < 4: 34 | return n - 1 35 | res = 1 36 | while n > 4: 37 | res *=3 38 | n -= 3 39 | return res * n 40 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_14_2.py: -------------------------------------------------------------------------------- 1 | # 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m - 1] 。请问 k[0]*k[1]*...*k[m - 1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。 2 | # 3 | # 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 4 | # 5 | #   6 | # 7 | # 示例 1: 8 | # 9 | # 输入: 2 10 | # 输出: 1 11 | # 解释: 2 = 1 + 1, 1 × 1 = 1 12 | # 示例 2: 13 | # 14 | # 输入: 10 15 | # 输出: 36 16 | # 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36 17 | #   18 | # 19 | # 提示: 20 | # 21 | # 2 <= n <= 1000 22 | # 23 | # 来源:力扣(LeetCode) 24 | # 链接:https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof 25 | class Solution: 26 | def cuttingRope(self, n: int) -> int: 27 | if n < 4: 28 | return n - 1 29 | res = 1 30 | while n > 4: 31 | res *= 3 32 | n -= 3 33 | return res * n % 1000000007 34 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_17.py: -------------------------------------------------------------------------------- 1 | # 输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。 2 | # 3 | # 示例 1: 4 | # 5 | # 输入: n = 1 6 | # 输出: [1,2,3,4,5,6,7,8,9] 7 | #   8 | # 9 | # 说明: 10 | # 11 | # 用返回一个整数列表来代替打印 12 | # n 为正整数 13 | # 14 | # 15 | # 来源:力扣(LeetCode) 16 | # 链接:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof 17 | from typing import List 18 | 19 | 20 | class Solution: 21 | def printNumbers(self, n: int) -> List[int]: 22 | """ 23 | 简单来说,就是打印 1~10^n-1 24 | """ 25 | return [i for i in range(1, 10**n)] 26 | 27 | # 其实应该考虑是的大数的存储问题,不论是short,int, long 都是有其最大值的,所以需要考虑用字符串存储。 28 | # 实际上是一个全排列。 29 | def printNumbers(self, n: int) -> List[str]: 30 | pass 31 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_18.py: -------------------------------------------------------------------------------- 1 | # 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。 2 | # 3 | # 返回删除后的链表的头节点。 4 | # 5 | # 注意:此题对比原题有改动 6 | # 7 | # 示例 1: 8 | # 9 | # 输入: head = [4,5,1,9], val = 5 10 | # 输出: [4,1,9] 11 | # 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9. 12 | # 示例 2: 13 | # 14 | # 输入: head = [4,5,1,9], val = 1 15 | # 输出: [4,5,9] 16 | # 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9. 17 | # 18 | # 来源:力扣(LeetCode) 19 | # 链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof 20 | 21 | from SwordOffer.DataStruct import ListNode 22 | 23 | 24 | class Solution: 25 | # 双指针 26 | def deleteNode(self, head: ListNode, val: int) -> ListNode: 27 | if not head: 28 | # 判断节点为非空 29 | return head 30 | if head.val == val: 31 | # 如果是第一个节点 32 | return head.next 33 | pre, cur = head, head.next 34 | while cur and cur.val != val: 35 | pre, cur = cur, cur.next 36 | if cur: 37 | pre.next = cur.next 38 | return head 39 | # 单指针 -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_26.py: -------------------------------------------------------------------------------- 1 | # 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) 2 | # 3 | # B是A的子结构, 即 A中有出现和B相同的结构和节点值。 4 | # 5 | # 例如: 6 | # 给定的树 A: 7 | # 8 | # 3 9 | # / \ 10 | # 4 5 11 | # / \ 12 | # 1 2 13 | # 给定的树 B: 14 | # 15 | # 4 16 | # / 17 | # 1 18 | # 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。 19 | # 20 | # 来源:力扣(LeetCode) 21 | # 链接:https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof 22 | from SwordOffer.DataStruct import TreeNode 23 | 24 | 25 | class Solution: 26 | def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: 27 | """ 28 | 递归方法 29 | """ 30 | def recur(A, B): 31 | if not B: 32 | return True 33 | if not A or A.val != B.val: 34 | return False 35 | return recur(A.left, B.left) and recur(A.right, B.right) 36 | 37 | return bool(A and B) and (recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)) 38 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_32_2.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | from SwordOffer.DataStruct import TreeNode 4 | 5 | 6 | class Solution: 7 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 8 | from collections import deque 9 | if not root: 10 | return [] 11 | res, queue = [], deque() 12 | queue.append(root) 13 | while queue: 14 | tmp = [] 15 | for _ in range(len(queue)): 16 | node = queue.popleft() 17 | tmp.append(node.val) 18 | if node.left: 19 | queue.append(node.left) 20 | if node.right: 21 | queue.append(node.right) 22 | res.append(tmp) 23 | return res 24 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_33.py: -------------------------------------------------------------------------------- 1 | # 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 2 | # 3 | #   4 | # 5 | # 参考以下这颗二叉搜索树: 6 | # 7 | # 5 8 | # / \ 9 | # 2 6 10 | # / \ 11 | # 1 3 12 | # 示例 1: 13 | # 14 | # 输入: [1,6,3,2,5] 15 | # 输出: false 16 | # 示例 2: 17 | # 18 | # 输入: [1,3,2,6,5] 19 | # 输出: true 20 | #   21 | # 22 | # 提示: 23 | # 24 | # 数组长度 <= 1000 25 | # 26 | # 来源:力扣(LeetCode) 27 | # 链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof 28 | from typing import List 29 | 30 | 31 | class Solution: 32 | def verifyPostorder(self, postorder: List[int]) -> bool: 33 | def recur(i, j): 34 | if i >= j: 35 | return True 36 | p = i 37 | while postorder[p] < postorder[j]: 38 | p += 1 39 | m = p 40 | while postorder[p] > postorder[j]: 41 | p += 1 42 | return p == j and recur(i, m - 1) and recur(m, j - 1) 43 | 44 | return recur(0, len(postorder) - 1) 45 | 46 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_36.py: -------------------------------------------------------------------------------- 1 | from SwordOffer.DataStruct import Node 2 | 3 | 4 | class Solution: 5 | def treeToDoublyList(self, root: 'Node') -> 'Node': 6 | def dfs(cur): 7 | if not cur: 8 | return 9 | dfs(cur.left) # 递归左子树 10 | if self.pre: # 修改节点引用 11 | self.pre.right, cur.left = cur, self.pre 12 | else: # 记录头节点 13 | self.head = cur 14 | self.pre = cur # 保存 cur 15 | dfs(cur.right) # 递归右子树 16 | 17 | if not root: 18 | return 19 | self.pre = None 20 | dfs(root) 21 | self.head.left, self.pre.right = self.pre, self.head 22 | return self.head 23 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_42.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.cn/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/ 2 | # 输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 3 | 4 | # 要求时间复杂度为O(n)。 5 | 6 | # 示例1: 7 | 8 | # 输入: nums = [-2,1,-3,4,-1,2,1,-5,4] 9 | # 输出: 6 10 | # 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 11 | #   12 | 13 | # 提示: 14 | 15 | # 1 <= arr.length <= 10^5 16 | # -100 <= arr[i] <= 100 17 | # 注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/ 18 | 19 | from typing import List 20 | 21 | 22 | class Solution: 23 | def maxSubArray(self, nums: List[int]) -> int: 24 | 25 | pre = 0 26 | maxAns = nums[0] 27 | for x in nums: 28 | pre = max(pre + x, x) 29 | maxAns = max(maxAns, pre) 30 | 31 | return maxAns 32 | 33 | 34 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_46.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.cn/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/ 2 | # # 给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。 3 | # 示例 1: 4 | 5 | # 输入: 12258 6 | # 输出: 5 7 | # 解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi" 8 | #   9 | 10 | # 提示: 11 | 12 | # 0 <= num < 2^31 13 | 14 | 15 | class Solution: 16 | def translateNum(self, num: int) -> int: 17 | s = str(num) 18 | a = b = 1 19 | for i in range(len(s) - 2, -1, -1): 20 | a, b = (a + b if "10" <= s[i:i + 2] <= "25" else a), a 21 | return a 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_56_1.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/ 3 | # 求只出现1次的两个数 4 | class Solution: 5 | def singleNumbers(self, nums: List[int]) -> List[int]: 6 | 7 | 8 | # 利用异或的性质 9 | # 按位分组 10 | a_xor_b = 0 11 | for i in nums: 12 | a_xor_b ^= i 13 | 14 | # 找到最低位的一 15 | low_bit_one = a_xor_b & (-a_xor_b) 16 | 17 | res = 0 18 | for i in nums: 19 | if low_bit_one & i: 20 | res ^= i 21 | 22 | return [res, a_xor_b ^ res] -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_56_2.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/ 3 | # 在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。 4 | 5 | 6 | class Solution: 7 | def singleNumbers(self, nums: List[int]) -> int: 8 | 9 | counts = [0] * 32 10 | for num in nums: 11 | for j in range(32): 12 | counts[j] += num & 1 13 | num >>= 1 14 | res, m = 0, 3 15 | for i in range(32): 16 | res <<= 1 17 | res |= counts[31 - i] % m 18 | return res if counts[31] % m == 0 else ~(res ^ 0xffffffff) 19 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_57.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.cn/problems/he-wei-sde-liang-ge-shu-zi-lcof/ 3 | # 输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。 4 | 5 | class Solution: 6 | def singleNumbers(self, nums: List[int]) -> int: 7 | 8 | counts = [0] * 32 9 | for num in nums: 10 | for j in range(32): 11 | counts[j] += num & 1 12 | num >>= 1 13 | res, m = 0, 3 14 | for i in range(32): 15 | res <<= 1 16 | res |= counts[31 - i] % m 17 | return res if counts[31] % m == 0 else ~(res ^ 0xffffffff) 18 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_57_2.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.cn/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/ 3 | # 输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。 4 | 5 | class Solution: 6 | def findContinuousSequence(self, target: int) -> List[List[int]]: 7 | # 双指针法 8 | left = 1 9 | right = 2 10 | ans = [] 11 | while left < right and right < target: 12 | sum = (right - left + 1) * (right + left) //2 13 | if sum == target: 14 | ans.append([i for i in range(left, right + 1)]) 15 | left += 1 16 | elif sum > target: 17 | left += 1 18 | else: 19 | right += 1 20 | return ans 21 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_58.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/ 3 | # 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 4 | 5 | class Solution: 6 | def reverseLeftWords(self, s: str, n: int) -> str: 7 | # 切片法 8 | return s[n:] + s[:n] 9 | 10 | def reverseLeftWords(self, s: str, n: int) -> str: 11 | # 三次翻转 12 | # 先翻转0:n,然后翻转n:-1,最后整个数组翻转 13 | 14 | pass 15 | -------------------------------------------------------------------------------- /SwordOffer/SwordOffer_65.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.cn/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/ 3 | # 写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。 4 | 5 | class Solution: 6 | def add(self, a: int, b: int) -> int: 7 | # 这里是考察位运算 8 | x = 0xffffffff 9 | a, b = a & x, b & x 10 | while b != 0: 11 | a, b = (a ^ b), (a & b) << 1 & x 12 | return a if a <= 0x7fffffff else ~(a ^ x) 13 | 14 | # 注意Python的整型数的机制 15 | -------------------------------------------------------------------------------- /code/1#Two Sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum/description/ 2 | class Solution: 3 | def twoSum(self, nums, target): 4 | """ 5 | :type nums: List[int] 6 | :type target: int 7 | :rtype: List[int] 8 | """ 9 | pair = {} 10 | for i in range(len(nums)): 11 | if nums[i] in pair.keys(): 12 | return [pair.get(nums[i]),i] 13 | else: 14 | pair[target-nums[i]] = i 15 | return [] 16 | -------------------------------------------------------------------------------- /code/101#Symmetric Tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/symmetric-tree/description/ 2 | # Definition for a binary tree node. 3 | # class TreeNode(object): 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.left = None 7 | # self.right = None 8 | 9 | class Solution(object): 10 | def isSymmetric(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: bool 14 | """ 15 | # 方法一:分层读取,使用队列 16 | # 方法二:递归 17 | return self.isMirror(root,root) 18 | def isMirror(self,node1,node2): 19 | if not node1 and not node2: 20 | return True 21 | elif not node1 or not node2: 22 | return False 23 | else: 24 | if node1.val == node2.val: 25 | return self.isMirror(node1.left,node2.right) and self.isMirror(node1.right,node2.left) 26 | else: 27 | return False 28 | -------------------------------------------------------------------------------- /code/104#Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.left = None 7 | # self.right = None 8 | 9 | class Solution: 10 | # 1 递归方法 11 | def maxDepth(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: int 15 | """ 16 | if not root: 17 | return 0 18 | return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 19 | # 2 使用非递归 20 | def maxDepth(self, root): 21 | stack = [(root, 1)] 22 | total = 0 23 | while stack: 24 | node, depth = stack.pop() 25 | if node: 26 | total = max(total, depth) 27 | stack.extend([(node.left, depth + 1), (node.right, depth + 1)]) 28 | return total -------------------------------------------------------------------------------- /code/107#Binary Tree Level Order Traversal II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.left = None 7 | # self.right = None 8 | 9 | class Solution: 10 | def levelOrderBottom(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: List[List[int]] 14 | """ 15 | if not root: 16 | return [] 17 | res = [] 18 | lis = [root] 19 | while lis: 20 | lis2 = [] 21 | level = [] 22 | for each in lis: 23 | if each.left: 24 | lis2.append(each.left) 25 | if each.right: 26 | lis2.append(each.right) 27 | level.append(each.val) 28 | res.append(level) 29 | lis = lis2 30 | return res[::-1] -------------------------------------------------------------------------------- /code/108#Convert Sorted Array to Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ 2 | class Solution: 3 | def sortedArrayToBST(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: TreeNode 7 | """ 8 | def helper(nums,start,end): 9 | if start>=end: 10 | return None 11 | mid = start+(end-start)//2 12 | parent = TreeNode(nums[mid]) 13 | parent.left = helper(nums,start,mid) 14 | parent.right = helper(nums,mid+1,end) 15 | return parent 16 | return helper(nums,0,len(nums)) -------------------------------------------------------------------------------- /code/11#Container With Most Water.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/container-with-most-water/description/ 2 | class Solution: 3 | # 1 4 | # 暴力法 5 | # Time Limit Exceeded 6 | def maxArea(self, height): 7 | ret = 0 8 | for i in range(len(height)-1): 9 | for j in range(i+1,len(height)): 10 | ret = max(ret,min(height[i],height[j])*(j-i)) 11 | return ret 12 | def maxArea(self, height): 13 | lpoint,rpoint=0,len(height)-1 14 | max_area = 0 15 | while lpointheight[lpoint]: 18 | lpoint+=1 19 | else: 20 | rpoint-=1 21 | return max_area 22 | 23 | -------------------------------------------------------------------------------- /code/117#Populating Next Right Pointers in Each Node II.py: -------------------------------------------------------------------------------- 1 | # 与116相同 2 | class Solution2: 3 | def connect(self, root: 'Node') -> 'Node': 4 | if not root: 5 | return None 6 | 7 | queue = [root] 8 | while queue: 9 | for i in range(len(queue)-1): 10 | queue[i].next = queue[i+1] 11 | queue[-1].next = None 12 | tmp = [] 13 | for node in queue: 14 | tmp.extend([node.left, node.right]) 15 | 16 | queue = [n for n in tmp if n] 17 | return root -------------------------------------------------------------------------------- /code/119#Pascal's Triangle II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/pascals-triangle-ii/description/ 2 | class Solution: 3 | def getRow(self, rowIndex): 4 | """ 5 | :type rowIndex: int 6 | :rtype: List[int] 7 | """ 8 | if rowIndex==0: 9 | return [1] 10 | c=Solution.getRow(self,rowIndex-1) 11 | newrow=[] 12 | gauche=[0]+c 13 | droite=c+[0] 14 | for i in range(len(gauche)): 15 | newrow.append(gauche[i]+droite[i]) 16 | return newrow -------------------------------------------------------------------------------- /code/12#Integer to Roman.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/integer-to-roman/description/ 2 | class Solution: 3 | # 1 4 | # 将1~3999的十进制位数全列出来 5 | # 然后利用进制计算 6 | def intToRoman(self, num): 7 | """ 8 | :type num: int 9 | :rtype: str 10 | """ 11 | M = ["", "M", "MM", "MMM"] 12 | C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] 13 | X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] 14 | I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] 15 | return M[num//1000] + C[(num%1000)//100] + X[(num%100)//10] + I[num%10] 16 | # 2 17 | # 相较1中的暴力方法,2中通过减法,得到结果 18 | def intToRoman1(self, num): 19 | values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] 20 | numerals = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] 21 | res, i = "", 0 22 | while num: 23 | res += (num//values[i]) * numerals[i] 24 | num %= values[i] 25 | i += 1 26 | return res -------------------------------------------------------------------------------- /code/121#Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 2 | import sys 3 | class Solution: 4 | def maxProfit(self, prices): 5 | """ 6 | :type prices: List[int] 7 | :rtype: int 8 | """ 9 | # 只做一次交易,需要保证找出最小值与最大值,且最小值在最大值之前。 10 | minPrice = sys.maxsize 11 | maxProfit = 0 12 | for p in prices: 13 | if p < minPrice: 14 | minPrice = p 15 | elif p-minPrice>maxProfit: 16 | maxProfit = p-minPrice 17 | return maxProfit -------------------------------------------------------------------------------- /code/125#Valid Palindrome.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-palindrome/description/ 2 | class Solution: 3 | def isPalindrome(self, s): 4 | """ 5 | :type s: str 6 | :rtype: bool 7 | """ 8 | # 实际上是判断一个一个字符串的英文字母字串是否是回文 9 | processedString = [] 10 | for c in s: 11 | if c.isalnum(): 12 | processedString.append(c.lower()) 13 | 14 | l = len(processedString) 15 | for i in range(0, l//2): 16 | if processedString[i] != processedString[l-1-i]: 17 | return False 18 | 19 | return True 20 | 21 | def isPalindrome2(self, s): 22 | """ 23 | :type s: str 24 | :rtype: bool 25 | """ 26 | import re 27 | s = s.lower() 28 | s1 = re.findall(r'[a-z0-9]', s) 29 | s2 = "".join(s1) 30 | # 使用字符串切片反转 31 | return s2[::-1] == s2 32 | -------------------------------------------------------------------------------- /code/13#Roman to Integer.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/roman-to-integer/description/ 2 | class Solution(object): 3 | def romanToInt(self, s): 4 | """ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | ans = 0 9 | dic_str = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1} 10 | pre = 0 11 | for i in range(len(s)-1, -1, -1): 12 | tmp = dic_str[s[i]] 13 | if tmp < pre: 14 | ans -= tmp 15 | else: 16 | ans += tmp 17 | pre = tmp 18 | return ans -------------------------------------------------------------------------------- /code/136#Single Number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def singleNumber(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | # 1 使用异或 8 | # 只有一个数出现1次,其他都是两次,可以使用异或运算 9 | # a^a = 0 10 | # a^0 = a 11 | a = 0 12 | for i in nums: 13 | a ^= i 14 | return a 15 | # 2 使用加和 16 | # 先求出和,然后求出set,加和后乘2减去SUM 17 | def singleNumber(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | return(sum(set(nums))*2 - sum(nums)) -------------------------------------------------------------------------------- /code/139#Word Break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 | ok = [True] 4 | for i in range(1, len(s)+1): 5 | ok += any(ok[j] and s[j:i] in wordDict for j in range(i)), 6 | return ok[-1] -------------------------------------------------------------------------------- /code/14#Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestCommonPrefix(self, strs): 3 | """ 4 | :type strs: List[str] 5 | :rtype: str 6 | """ 7 | if not strs: 8 | return "" 9 | if len(strs)==1: 10 | return strs[0] 11 | strs.sort() 12 | length = min(len(strs[0]),len(strs[-1])) 13 | ch = "" 14 | for i in range(0,length): 15 | if strs[0][i] == strs[-1][i]: 16 | ch +=strs[0][i] 17 | else: 18 | break 19 | return ch -------------------------------------------------------------------------------- /code/141#Linked List Cycle.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/linked-list-cycle/description/ 2 | # Definition for singly-linked list. 3 | # class ListNode(object): 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | 8 | class Solution(object): 9 | def hasCycle(self, head): 10 | """ 11 | :type head: ListNode 12 | :rtype: bool 13 | """ 14 | # 使用两个指针(快慢)进行 15 | if not head or not head.next: 16 | return False 17 | q1 = head 18 | q2 = head.next 19 | while q1!= q2: 20 | if not q2 or not q2.next: 21 | return False 22 | q1 = q1.next 23 | q2 = q2.next.next 24 | return True -------------------------------------------------------------------------------- /code/142#Linked List Cycle II.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def detectCycle(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | # 使用两个指针(快慢)进行 14 | if not head or not head.next: 15 | return None 16 | q1 = head 17 | q2 = head.next 18 | while q1 != q2: 19 | if not q2 or not q2.next: 20 | return None 21 | q1 = q1.next 22 | q2 = q2.next.next 23 | # 确定有环,从头指针与q1 q2相遇的地方分别遍历 24 | res = head 25 | q1 = q1.next 26 | while res !=q1: 27 | res = res.next 28 | q1 = q1.next 29 | return res 30 | -------------------------------------------------------------------------------- /code/1496#spath crossing.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.cn/problems/path-crossing/ 2 | # 给你一个字符串 path,其中 path[i] 的值可以是 'N'、'S'、'E' 或者 'W',分别表示向北、向南、向东、向西移动一个单位。 3 | 4 | # 你从二维平面上的原点 (0, 0) 处开始出发,按 path 所指示的路径行走。 5 | 6 | # 如果路径在任何位置上与自身相交,也就是走到之前已经走过的位置,请返回 true ;否则,返回 false 。 7 | 8 | 9 | 10 | 11 | 12 | class Solution: 13 | def isPathCrossing(self, path: str) -> bool: 14 | start_x = 0 15 | start_y = 0 16 | roads = {(0,0)} 17 | for i in path: 18 | if i == "N": 19 | start_y += 1 20 | elif i == "S": 21 | start_y -= 1 22 | elif i == "E": 23 | start_x += 1 24 | elif i == "W": 25 | start_x -= 1 26 | temp = (start_x, start_y) 27 | if temp in roads: 28 | return True 29 | else: 30 | roads.add(temp) 31 | return False 32 | 33 | def main(): 34 | solution = Solution() 35 | print(solution.isPathCrossing("NESWW")) 36 | 37 | main() 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /code/151#Reverse Words in a String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-words-in-a-string/description/ 2 | class Solution(object): 3 | def reverseWords(self, s): 4 | """ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | return " ".join(reversed(s.split())) -------------------------------------------------------------------------------- /code/152#Maximum Product Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | B = nums[::-1] 8 | for i in range(1, len(nums)): 9 | nums[i] *= nums[i-1] or 1 10 | B[i] *= B[i-1] or 1 11 | return max(nums+B) 12 | 13 | def maxProduct(nums): 14 | maximum = big = small = nums[0] 15 | for n in nums[1:]: 16 | big, small = max(n, n * big, n * small), min(n, n * big, n * small) 17 | maximum = max(maximum, big) 18 | return maximum -------------------------------------------------------------------------------- /code/167#Two Sum II - Input array is sorted.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/ 2 | # 与twoSum一致,只是将角标加一。 3 | class Solution: 4 | def twoSum(self, numbers, target): 5 | """ 6 | :type numbers: List[int] 7 | :type target: int 8 | :rtype: List[int] 9 | """ 10 | pair = {} 11 | for i in range(len(numbers)): 12 | if numbers[i] in pair.keys(): 13 | return [pair.get(numbers[i]),i+1] 14 | else: 15 | pair[target-numbers[i]] = i+1 16 | return [] -------------------------------------------------------------------------------- /code/168#Excel Sheet Column Title.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/excel-sheet-column-title/description/ 2 | class Solution: 3 | # 1 直接使用字母表 4 | def convertToTitle(self, n): 5 | """ 6 | :type n: int 7 | :rtype: str 8 | """ 9 | alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 10 | res = "" 11 | while n > 0: 12 | word = (n-1) % 26 13 | n = (n-1) // 26 14 | tempString = alpha[word] 15 | res = ''.join((tempString, res)) 16 | return res 17 | # 2 利用chr与ord函数 18 | # chr(65)='A';ord('A')=65 19 | def convertToTitle(self, n): 20 | """ 21 | :type n: int 22 | :rtype: str 23 | """ 24 | res = '' 25 | dist = ord('A') 26 | 27 | while n > 0: 28 | word = (n-1) % 26 29 | n = (n-1) // 26 30 | tempString = chr(word+dist) 31 | res = ''.join((tempString, res)) 32 | return res -------------------------------------------------------------------------------- /code/169#Majority Element.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/majority-element/description/ 2 | class Solution: 3 | # 1 如果某个数大于n/2,那么排序后的数列中,该数一定位于中位数 4 | def majorityElement(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | return sorted(nums)[len(nums)//2] 10 | # 2 数数法 不推荐 11 | def majorityElement(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: int 15 | """ 16 | l = len(nums) 17 | num = set(nums) 18 | for val in num: 19 | a = nums.count(val) 20 | if a >= l*0.5: 21 | return val 22 | -------------------------------------------------------------------------------- /code/171#Excel Sheet Column Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/excel-sheet-column-number/description/ 2 | class Solution: 3 | # 1 常规法 4 | def titleToNumber(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 10 | res = 0 11 | base = 1 12 | for i in s[::-1]: 13 | res += (alpha.index(i)+1) * base 14 | base *= 26 15 | return res 16 | # 2 一行Python法 17 | # 利用reduce函数与lambda 18 | def titleToNumber(self, s): 19 | """ 20 | :type s: str 21 | :rtype: int 22 | """ 23 | return reduce(lambda x, y: x*26 + y, [ord(c) - ord('A') + 1 for c in s]) -------------------------------------------------------------------------------- /code/172#Factorial Trailing Zeroes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/factorial-trailing-zeroes/description/ 2 | class Solution(object): 3 | def trailingZeroes(self, n): 4 | """ 5 | :type n: int 6 | :rtype: int 7 | """ 8 | # 实际上是找1~n中有几个5的质因数 9 | # 分析 10 | # 1~10 2 11 | # 11~20 2 12 | # 21~30 25,30 3 13 | # 31~40 2 14 | # 41~50 45,50 3 15 | base = 5 16 | ans = 0 17 | while base <= n: 18 | ans += n//base 19 | base *=5 20 | return ans -------------------------------------------------------------------------------- /code/189#Rotate Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/rotate-array/description/ 2 | class Solution: 3 | def rotate(self, nums, k): 4 | """ 5 | :type nums: List[int] 6 | :type k: int 7 | :rtype: void Do not return anything, modify nums in-place instead. 8 | """ 9 | # 显然不能直接一步步移动 10 | # 先对K进行模运算 11 | if not nums: 12 | return 13 | n = len(nums) 14 | k = k%n 15 | nums[:] = nums[n-k:]+nums[:n-k] -------------------------------------------------------------------------------- /code/190#Reverse Bits.py: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/reverse-bits/description/ 2 | class Solution: 3 | # @param n, an integer 4 | # @return an integer 5 | # 1 6 | # 需要考虑32位这个点,有可能转化过来的二进制数零 7 | # 的位数不够32,需要补齐 8 | # int(str,base) bin(num)函数的使用 9 | def reverseBits(self, n): 10 | s = bin(n)[2:] 11 | if len(s)<=32: 12 | s2 = '0b'+s[::-1]+(32-len(s))*'0' 13 | return int(s2,2) 14 | # 2 15 | # 通过移位循环32次,使用n&1返回满足的最低位 16 | # 法二挺巧妙的 17 | def reverseBits(self, n): 18 | res = 0 19 | for _ in xrange(32): 20 | res = (res<<1) + (n&1) 21 | n>>=1 22 | return res -------------------------------------------------------------------------------- /code/191#Number of 1 Bits.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-1-bits/description/ 2 | class Solution(object): 3 | # 1 编程之美上的题目 4 | # n&n-1每次都能够把最左边的1消去 5 | # 循环操作的步数为1的个数 6 | def hammingWeight(self, n): 7 | """ 8 | :type n: int 9 | :rtype: int 10 | """ 11 | count = 0 12 | while n>0: 13 | n&=n-1 14 | count+=1 15 | return count 16 | 17 | # 2 直接使用bin()函数然后使用str的count方法 18 | # 这样做直接使用了Python封装好的库,没有get到考察的点 19 | # 不推荐,单纯是炫技的one line Python code 20 | def hammingWeight(self, n): 21 | """ 22 | :type n: int 23 | :rtype: int 24 | """ 25 | return str(bin(n)).count('1') 26 | 27 | # 3 利用移位操作来计算1的个数,每一位与1做且操作,如果为1则加1 28 | # 常规操作 29 | def hammingWeight(self, n): 30 | onesCount = 0 31 | 32 | while n > 0: 33 | if n & 0x1: 34 | onesCount += 1 35 | n = n >> 1 36 | 37 | return onesCount -------------------------------------------------------------------------------- /code/198#House Robber.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/house-robber/description/ 2 | class Solution: 3 | # 1 使用一个数组保存,动态规划 4 | def rob(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | if not nums: 10 | return 0 11 | memo = [0 for _ in range(len(nums)+1)] 12 | memo[1] = nums[0] 13 | for i in range(1,len(nums)): 14 | memo[i+1] = max(memo[i],memo[i-1]+nums[i]) 15 | return memo[len(nums)] 16 | 17 | # 2 将方法1中的数组简化为两个变量保存 18 | def rob(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | # rob(i) = Math.max( rob(i - 2) + currentHouseValue, rob(i - 1) ) 24 | if not nums: 25 | return 0 26 | pre1 = 0 27 | pre2 = 0 28 | i = 0 29 | for num in nums: 30 | temp = pre1 31 | pre1 = max(pre2+num,pre1) 32 | pre2 = temp 33 | return pre1 -------------------------------------------------------------------------------- /code/2#Add Two Nubers.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/add-two-numbers/description/ 2 | # Definition for singly-linked list. 3 | # class ListNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | 8 | class Solution: 9 | def addTwoNumbers(self, l1, l2): 10 | """ 11 | :type l1: ListNode 12 | :type l2: ListNode 13 | :rtype: ListNode 14 | """ 15 | carry = 0 16 | res = l1 # 使用l1作为链表,不用创建新的链表 17 | while l1 or l2: 18 | l1.val += l2.val + carry if l2 else carry 19 | carry = l1.val//10 # 使用标准除法,如果大于等于10则carry置1 20 | l1.val %= 10 21 | if l2: 22 | l2=l2.next 23 | if l1.next: 24 | l1=l1.next 25 | elif carry or l2: 26 | l1.next=ListNode(0) #如果l1没有则补0 27 | l1=l1.next 28 | else: 29 | break 30 | return res 31 | -------------------------------------------------------------------------------- /code/20#Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | stack = [] 8 | for i in s: 9 | if i == "}" or i == "]" or i == ")": 10 | if not stack: 11 | return False 12 | if i=="}" and stack[-1] == "{" or i=="]" and stack[-1] == "[" or i==")" and stack[-1] == "(": 13 | stack.pop() 14 | else: 15 | return False 16 | else: 17 | stack.append(i) 18 | return not stack 19 | 20 | -------------------------------------------------------------------------------- /code/203#Remove Linked List Elements.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-linked-list-elements/description/ 2 | # Definition for singly-linked list. 3 | # class ListNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | 8 | class Solution: 9 | def removeElements(self, head, val): 10 | """ 11 | :type head: ListNode 12 | :type val: int 13 | :rtype: ListNode 14 | """ 15 | ret = res = ListNode(0) 16 | res.next = head 17 | while res.next: 18 | if res.next.val==val: 19 | res.next = res.next.next 20 | else: 21 | res = res.next 22 | return ret.next -------------------------------------------------------------------------------- /code/204#Count Primes.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-primes/description/ 2 | class Solution: 3 | # 1 常规方法,数字较大会memory溢出 4 | def countPrimes(self, n): 5 | """ 6 | :type n: int 7 | :rtype: int 8 | """ 9 | def isPrime(num): 10 | for i in range(2,int(num**0.5)+1): 11 | if num%i==0: 12 | return False 13 | return True 14 | if n<3: 15 | return 0 16 | count = 1 17 | for i in range(3,n,2): 18 | if isPrime(i): 19 | count+=1 20 | return count 21 | # 2 22 | # 使用0,1的数组来表示是否是质数。 23 | # 24 | def countPrimes(self, n): 25 | """ 26 | :type n: int 27 | :rtype: int 28 | """ 29 | if n < 2: 30 | return 0 31 | s = [1] * n 32 | s[0] = s[1] = 0 33 | for i in range(2, int(n ** 0.5) + 1): 34 | if s[i] == 1: 35 | s[i * i:n:i] = [0] * len(s[i * i:n:i]) 36 | return sum(s) -------------------------------------------------------------------------------- /code/21#Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | class Solution: 8 | def mergeTwoLists(self, l1, l2): 9 | """ 10 | :type l1: ListNode 11 | :type l2: ListNode 12 | :rtype: ListNode 13 | """ 14 | dummy_head = tail = ListNode(0) 15 | 16 | while l1 and l2: 17 | if l1.val < l2.val: 18 | tail.next, l1 = l1, l1.next 19 | else: 20 | tail.next, l2 = l2, l2.next 21 | tail = tail.next 22 | 23 | tail.next = l1 or l2 24 | return dummy_head.next -------------------------------------------------------------------------------- /code/215#Kth Largest Element in an Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/kth-largest-element-in-an-array/ 2 | """ 3 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 4 | 5 | Example 1: 6 | 7 | Input: [3,2,1,5,6,4] and k = 2 8 | Output: 5 9 | Example 2: 10 | 11 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 12 | Output: 4 13 | Note: 14 | You may assume k is always valid, 1 ≤ k ≤ array's length. 15 | """ 16 | class Solution: 17 | def findKthLargest(self, nums, k): 18 | """ 19 | :type nums: List[int] 20 | :type k: int 21 | :rtype: int 22 | """ 23 | import heapq 24 | return heapq.nlargest(k,nums) -------------------------------------------------------------------------------- /code/219#Contains Duplicate II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/contains-duplicate/description/ 2 | class Solution(object): 3 | # 1 常规方法 使用字典记录,利用字典查找O(1) 4 | def containsDuplicate(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: bool 8 | """ 9 | mapping = dict() 10 | for i in nums: 11 | if i in mapping: 12 | return True 13 | else: 14 | mapping[i]=1 15 | return False 16 | # 2 巧妙地方法 利用set方法 17 | def containsDuplicate(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: bool 21 | """ 22 | if(len(set(nums)) == len(nums)): 23 | return False 24 | return True 25 | # 3 先sort,然后比较相邻是否相同,不推荐 26 | def containsDuplicate(self, nums): 27 | """ 28 | :type nums: List[int] 29 | :rtype: bool 30 | """ 31 | nums.sort() 32 | for i in range(1, len(nums)): 33 | if nums[i] == nums[i - 1]: 34 | return True 35 | return False -------------------------------------------------------------------------------- /code/226#Invert Binary Tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | # 1 递归方法 10 | def invertTree(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: TreeNode 14 | """ 15 | # 递归 16 | if not root: 17 | return root 18 | root.left,root.right = root.right, root.left 19 | self.invertTree(root.left) 20 | self.invertTree(root.right) 21 | return root -------------------------------------------------------------------------------- /code/23#Merge k Sorted Lists.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/merge-k-sorted-lists/ 2 | """ 3 | Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 4 | 5 | Example: 6 | 7 | Input: 8 | [ 9 | 1->4->5, 10 | 1->3->4, 11 | 2->6 12 | ] 13 | Output: 1->1->2->3->4->4->5->6 14 | """ 15 | # Definition for singly-linked list. 16 | class ListNode: 17 | def __init__(self, x): 18 | self.val = x 19 | self.next = None 20 | # 思路一: 21 | # 先使用一个池子(长度为k)来保存当前的每个链表的第一个值,将池子中的最小值 22 | class Solution: 23 | def mergeKLists(self, lists: list[ListNode]) -> ListNode: 24 | import heapq 25 | def gen(node): 26 | while node: 27 | yield node.val, node 28 | node = node.next 29 | dummy = last = ListNode(None) 30 | for _, last.next in heapq.merge(*map(gen, lists)): 31 | last = last.next 32 | return dummy.next 33 | 34 | -------------------------------------------------------------------------------- /code/231#Power of Two.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPowerOfTwo(self, n): 3 | """ 4 | :type n: int 5 | :rtype: bool 6 | """ 7 | if n<=0: 8 | return False 9 | if n==1: 10 | return True 11 | while n>1: 12 | if n%2: 13 | return False 14 | else: 15 | n = n//2 16 | return True -------------------------------------------------------------------------------- /code/237#Delete Node in a Linked List.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 2 | # Definition for singly-linked list. 3 | # class ListNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | 8 | class Solution: 9 | def deleteNode(self, node): 10 | """ 11 | :type node: ListNode 12 | :rtype: void Do not return anything, modify node in-place instead. 13 | """ 14 | # 这题有问题啊!要删除的点也没有,肯定是错了 15 | node.val = node.next.val 16 | node.next = node.next.next 17 | # 上面的代码可以通过,且beat100% 18 | 19 | # 实际上我认为题目应该是这样 20 | def deleteNode(self, head,node): 21 | """ 22 | :type head: ListNode 23 | :type node: int 24 | :rtype: void Do not return anything, modify node in-place instead. 25 | """ 26 | while head and head.next: 27 | if head.val==node: 28 | head = head.next 29 | return 30 | -------------------------------------------------------------------------------- /code/24#Swap Nodes in Pairs.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/swap-nodes-in-pairs/ 2 | """ 3 | Given a linked list, swap every two adjacent nodes and return its head. 4 | 5 | You may not modify the values in the list's nodes, only nodes itself may be changed. 6 | 7 | 8 | 9 | Example: 10 | 11 | Given 1->2->3->4, you should return the list as 2->1->4->3. 12 | """ 13 | 14 | # Definition for singly-linked list. 15 | class ListNode: 16 | def __init__(self, x): 17 | self.val = x 18 | self.next = None 19 | 20 | class Solution: 21 | def swapPairs(self, head: ListNode) -> ListNode: 22 | pre, pre.next = self, head 23 | while pre.next and pre.next.next: 24 | a = pre.next 25 | b = a.next 26 | pre.next, b.next, a.next = b, a, b.next 27 | pre = a 28 | return self.next 29 | -------------------------------------------------------------------------------- /code/26#Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 2 | class Solution(object): 3 | def removeDuplicates(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | nums[:] = list(set(nums)) 9 | nums.sort() 10 | return len(nums) -------------------------------------------------------------------------------- /code/263#Ugly Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/ugly-number/description/ 2 | class Solution: 3 | def isUgly(self, num): 4 | """ 5 | :type num: int 6 | :rtype: bool 7 | """ 8 | if num<=0: 9 | return False 10 | while num%5==0: 11 | num//=5 12 | while num%3==0: 13 | num//=3 14 | while num%2==0: 15 | num//=2 16 | return True if num==1 else False 17 | -------------------------------------------------------------------------------- /code/268#Missing Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/missing-number/description/ 2 | class Solution: 3 | # 1 常规:O(n2) time out 失败 4 | def missingNumber(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | for i in range(len(nums)+1): 10 | if i not in nums: 11 | return i 12 | 13 | # 2 14 | # 1中变式,使用set判断是否包含O(n) 15 | # 83.90% 16 | def missingNumber(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: int 20 | """ 21 | s = set(nums) 22 | for i in range(len(nums)+1): 23 | if i not in s: 24 | return i 25 | # 3 26 | # O(n) 99.58% 27 | # 使用和的方法求出缺少的数 28 | def missingNumber(self, nums): 29 | """ 30 | :type nums: List[int] 31 | :rtype: int 32 | """ 33 | n = len(nums) 34 | return n*(n+1)//2-sum(nums) -------------------------------------------------------------------------------- /code/27#Remove Element.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-element/description/ 2 | class Solution: 3 | def removeElement(self, nums, val): 4 | """ 5 | :type nums: List[int] 6 | :type val: int 7 | :rtype: int 8 | """ 9 | times = nums.count(val) 10 | while times>0: 11 | nums.remove(val) 12 | times-=1 13 | return len(nums) -------------------------------------------------------------------------------- /code/278#First Bad Version.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/first-bad-version/description/ 2 | # The isBadVersion API is already defined for you. 3 | # @param version, an integer 4 | # @return a bool 5 | # def isBadVersion(version): 6 | 7 | # 实际上,这是一个特殊的二分查询 8 | # 一个数的状态只有0,1两种情况,他们按照0,0,0,...,1,1,1,...的顺序排列 9 | # 我们要找到最第一个1。 10 | class Solution: 11 | def firstBadVersion(self, n): 12 | """ 13 | :type n: int 14 | :rtype: int 15 | """ 16 | # 二分法 17 | low = 1 18 | high = n 19 | while low 0: 14 | res += 1 15 | return res 16 | 17 | for x in range(len(board)): 18 | for y in range(len(board[0])): 19 | board[x][y] = count(x, y) + 1 if board[x][y] == 1 else - count(x, y) 20 | 21 | for x in range(len(board)): 22 | for y in range(len(board[0])): 23 | board[x][y] = 1 if board[x][y] in {3, 4, -3} else 0 -------------------------------------------------------------------------------- /code/290#Word Pattern.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/word-pattern/description/ 2 | class Solution: 3 | # 1 4 | def wordPattern(self, pattern, str): 5 | """ 6 | :type pattern: str 7 | :type str: str 8 | :rtype: bool 9 | """ 10 | s = pattern 11 | t = str.split() 12 | return list(map(s.find, s)) == list(map(t.index, t)) 13 | # 2 14 | def wordPattern(self, pattern, str): 15 | s = pattern 16 | t = str.split() 17 | return len(set(zip(s, t))) == len(set(s)) == len(set(t)) and len(s) == len(t) -------------------------------------------------------------------------------- /code/292#Nim Game.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/nim-game/description/ 2 | # 题目很简单 3 | # 对于先手,需要在第一次拿之后剩下是4的倍数就能赢。 4 | # 先手拿完之后,不管后手怎么拿都能组成4的倍数,从而胜利。 5 | class Solution: 6 | def canWinNim(self, n): 7 | """ 8 | :type n: int 9 | :rtype: bool 10 | """ 11 | return True if n%4 else False 12 | -------------------------------------------------------------------------------- /code/31#Next Permutation.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/next-permutation/description/ 2 | class Solution: 3 | def nextPermutation(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: void Do not return anything, modify nums in-place instead. 7 | """ 8 | 9 | i = len(nums) - 1 10 | while i - 1 >= 0 and nums[i - 1] >= nums[i]: 11 | i -= 1 12 | 13 | if i - 1 >= 0: 14 | j = i 15 | while j < len(nums) and nums[j] > nums[i - 1]: 16 | j += 1 17 | # swap the min-max number 18 | nums[i - 1], nums[j - 1] = nums[j - 1], nums[i - 1] 19 | m = i 20 | n = len(nums) - 1 21 | while m < n: 22 | nums[m], nums[n] = nums[n], nums[m] 23 | m += 1 24 | n -= 1 -------------------------------------------------------------------------------- /code/326#Power of Three.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/power-of-three/description/ 2 | class Solution: 3 | # 1 常规方法 4 | # n小于等于0 FALSE 5 | # n等于1 TRUE 6 | # n大于1 需要判断 7 | def isPowerOfThree(self, n): 8 | """ 9 | :type n: int 10 | :rtype: bool 11 | """ 12 | if n<=0: 13 | return False 14 | while n>1: 15 | if n%3==0: 16 | n//=3 17 | else: 18 | return False 19 | return True 20 | # 2 技巧 21 | # M=1162261467=3^19 '0b1000101010001101011001111011011' 31位 22 | # 在int以内的数,只要是3的m次方,一定会被M整除 23 | def isPowerOfThree(self, n): 24 | """ 25 | :type n: int 26 | :rtype: bool 27 | """ 28 | return n > 0 and 1162261467 % n == 0 29 | # 3 递归 常规方法变式 30 | def isPowerOfThree(self, n): 31 | """ 32 | :type n: int 33 | :rtype: bool 34 | """ 35 | return n>0 and (n==1 or (n%3==0 and self.isPowerOfThree(n/3))) -------------------------------------------------------------------------------- /code/342#Power of Four.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/power-of-four/description/ 2 | class Solution: 3 | # 1 常规方法 4 | # n小于等于0 FALSE 5 | # n等于1 TRUE 6 | # n大于1 需要判断 7 | def isPowerOfFour(self, num): 8 | """ 9 | :type n: int 10 | :rtype: bool 11 | """ 12 | if num<=0: 13 | return False 14 | while num>1: 15 | if num%4==0: 16 | num//=4 17 | else: 18 | return False 19 | return True 20 | # 2 技巧 21 | # 4的倍数 二进制位 0100 与 0011 且操作 为0, 22 | def isPowerOfFour(self, num): 23 | """ 24 | :type n: int 25 | :rtype: bool 26 | """ 27 | return (num > 0) and (num & (num-1) == 0) and (num & 0xAAAAAAAA) == 0 28 | # 3 递归 常规方法变式 29 | def isPowerOfFour(self, num): 30 | """ 31 | :type n: int 32 | :rtype: bool 33 | """ 34 | return num>0 and (num==1 or (num%4==0 and self.isPowerOfFour(num/4))) -------------------------------------------------------------------------------- /code/344#Reverse String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-string/description/ 2 | class Solution: 3 | def reverseString(self, s): 4 | """ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | return s[::-1] -------------------------------------------------------------------------------- /code/345#Reverse Vowels of a String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reverse-vowels-of-a-string/description/ 2 | class Solution: 3 | def reverseVowels(self, s): 4 | """ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | vowels = set(list("aeiouAEIOU")) 9 | s = list(s) 10 | ptr_1, ptr_2 = 0, len(s) - 1 11 | while ptr_1 < ptr_2: 12 | if s[ptr_1] in vowels and s[ptr_2] in vowels: 13 | s[ptr_1], s[ptr_2] = s[ptr_2], s[ptr_1] 14 | ptr_1 += 1 15 | ptr_2 -= 1 16 | if s[ptr_1] not in vowels: 17 | ptr_1 += 1 18 | if s[ptr_2] not in vowels: 19 | ptr_2 -= 1 20 | return ''.join(s) -------------------------------------------------------------------------------- /code/349#Intersection of Two Arrays.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/intersection-of-two-arrays/description/ 2 | class Solution: 3 | # 1 使用set集合以及函数intersection 4 | def intersection(self, nums1, nums2): 5 | """ 6 | :type nums1: List[int] 7 | :type nums2: List[int] 8 | :rtype: List[int] 9 | """ 10 | return list(set(nums1).intersection(set(nums2))) 11 | # list(set(nums1)&set(nums2)) 同样可以 12 | # 2 常规方法 13 | # 先排序,然后遍历 14 | def intersection(self, nums1, nums2): 15 | """ 16 | :type nums1: List[int] 17 | :type nums2: List[int] 18 | :rtype: List[int] 19 | """ 20 | nums1.sort() 21 | nums2.sort() 22 | ret = set() 23 | i, j = 0, 0 24 | while i < len(nums1) and j < len(nums2): 25 | if nums1[i] < nums2[j]: 26 | i += 1 27 | elif nums1[i] > nums2[j]: 28 | j += 1 29 | else: 30 | ret.add(nums1[i]) 31 | i += 1 32 | j += 1 33 | return list(ret) -------------------------------------------------------------------------------- /code/35#Search Insert Position.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/search-insert-position/description/ 2 | class Solution: 3 | def searchInsert(self, nums, target): 4 | """ 5 | :type nums: List[int] 6 | :type target: int 7 | :rtype: int 8 | """ 9 | if not nums: 10 | return 0 11 | if targetnums[-1]: 14 | return len(nums) 15 | 16 | low = 0 17 | high = len(nums)-1 18 | while low<=high: 19 | mid = low + (high-low)//target 20 | if target == nums[mid]: 21 | return mid 22 | elif target > nums[mid]: 23 | low = mid+1 24 | else: 25 | high =mid-1 26 | return low -------------------------------------------------------------------------------- /code/367#Valid Perfect Square.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-perfect-square/description/ 2 | class Solution: 3 | # 1 常规方法 二分法 4 | def isPerfectSquare(self, num): 5 | """ 6 | :type num: int 7 | :rtype: bool 8 | """ 9 | low = 1 10 | high = num 11 | while low<=high: 12 | mid = low+(high-low)//2 13 | if mid*mid==num: 14 | return True 15 | elif mid*mid 0: 24 | num -= i 25 | i += 2 26 | return num==0 -------------------------------------------------------------------------------- /code/371#Sum of Two Integers.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sum-of-two-integers/description/ 2 | class Solution: 3 | # 1 trick 4 | def getSum(self, a, b): 5 | """ 6 | :type a: int 7 | :type b: int 8 | :rtype: int 9 | """ 10 | tmp = [a, b] 11 | return sum(tmp) 12 | # 2 13 | def getSum(self, a, b): 14 | MOD = 0xFFFFFFFF 15 | MAX_INT = 0x7FFFFFFF 16 | while b != 0: 17 | a, b = (a ^ b) & MOD, ((a & b) << 1) & MOD 18 | return a if a <= MAX_INT else ~(a & MAX_INT) ^ MAX_INT 19 | 20 | # https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary:-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently -------------------------------------------------------------------------------- /code/374#Guess Number Higher or Lower.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/guess-number-higher-or-lower/description/ 2 | 3 | # The guess API is already defined for you. 4 | # @param num, your guess 5 | # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 6 | # def guess(num): 7 | 8 | class Solution(object): 9 | # 实际上就是考察二分法,送分题,不过首先需要看懂题目 10 | def guessNumber(self, n): 11 | """ 12 | :type n: int 13 | :rtype: int 14 | """ 15 | low = 1 16 | high = n 17 | while low <= high: 18 | mid = (low + high)//2 19 | res = guess(mid) 20 | if res == 0 : 21 | return mid 22 | elif res == -1: 23 | high = mid - 1 24 | else: 25 | low = mid + 1 -------------------------------------------------------------------------------- /code/38#Count and Say.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/count-and-say/description/ 2 | class Solution(object): 3 | def countAndSay(self, n): 4 | """ 5 | :type n: int 6 | :rtype: str 7 | """ 8 | if n == 1: return "1" 9 | if n == 2: return "11" 10 | prev = "11" 11 | for i in range(3, n+1): 12 | res = "" 13 | ct = 1 14 | for j in range(1, len(prev)): 15 | if prev[j] != prev[j-1]: 16 | res = res + str(ct) + prev[j-1] 17 | ct = 1 18 | else: 19 | ct += 1 20 | res = res + str(ct) + prev[j] 21 | prev = res 22 | return res -------------------------------------------------------------------------------- /code/383#Ransom Note.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/ransom-note/description/ 2 | class Solution: 3 | # 1 利用内部函数 4 | def canConstruct(self, ransomNote, magazine): 5 | """ 6 | :type ransomNote: str 7 | :type magazine: str 8 | :rtype: bool 9 | """ 10 | return not collections.Counter(ransomNote) - collections.Counter(magazine) 11 | # 2 使用set()与count() 12 | def canConstruct(self, ransomNote, magazine): 13 | """ 14 | :type ransomNote: str 15 | :type magazine: str 16 | :rtype: bool 17 | """ 18 | for i in set(ransomNote): 19 | if ransomNote.count(i) > magazine.count(i): 20 | return False 21 | return True 22 | -------------------------------------------------------------------------------- /code/39#Combination Sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/combination-sum/description/ 2 | class Solution: 3 | def combinationSum(self, candidates, target): 4 | """ 5 | :type candidates: List[int] 6 | :type target: int 7 | :rtype: List[List[int]] 8 | """ 9 | res = [] 10 | candidates.sort() 11 | 12 | def dfs(target, index, path): 13 | if target < 0: 14 | return # backtracking 15 | if target == 0: 16 | res.append(path) 17 | return 18 | for i in range(index, len(candidates)): 19 | dfs(target-candidates[i], i, path+[candidates[i]]) 20 | 21 | dfs(target, 0, []) 22 | return res -------------------------------------------------------------------------------- /code/400#Nth Digit.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/nth-digit/description/ 2 | """ 3 | 1位数 9*1 4 | 2位数 90*2 5 | 3位数 900*3 6 | 4位数 9000*4 7 | bit = 1 =>+1 8 | base = 9 =>*10 9 | """ 10 | class Solution: 11 | def findNthDigit(self, n): 12 | """ 13 | :type n: int 14 | :rtype: int 15 | """ 16 | bit = 1 17 | base = 9 18 | while n>bit*base: 19 | n -= bit*base 20 | bit += 1 21 | base *= 10 22 | order = n//bit+1 23 | num_bit = n%bit 24 | start = 10**(bit-1) 25 | which = start + order -1 26 | ret = str(which)[num_bit-1] if num_bit>0 else str(which-1)[-1] 27 | return int(ret) 28 | -------------------------------------------------------------------------------- /code/404#Sum of Left Leaves.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sum-of-left-leaves/description/ 2 | class Solution(object): 3 | # 1 递归 4 | def sumOfLeftLeaves(self, root): 5 | if not root: return 0 6 | if root.left and not root.left.left and not root.left.right: 7 | return root.left.val + self.sumOfLeftLeaves(root.right) 8 | return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) 9 | # 2 递归 10 | def sumOfLeftLeaves(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: int 14 | """ 15 | 16 | sum = 0 17 | 18 | if root != None: 19 | if root.left != None: 20 | if root.left.left == None and root.left.right == None: 21 | sum += root.left.val 22 | else: 23 | sum += self.sumOfLeftLeaves(root.left) 24 | if root.right != None: 25 | sum += self.sumOfLeftLeaves(root.right) 26 | 27 | return sum -------------------------------------------------------------------------------- /code/41#First Missing Positive.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/first-missing-positive/description/ 2 | class Solution: 3 | # 1 4 | # 先找出最大数m,构造一个1到m+1的集合M 5 | # 用集合M减去nums集合N生成的集合M-N 6 | # 消失的最小正数就是min(M-N) 7 | def firstMissingPositive(self, nums): 8 | if not nums: 9 | return 1 10 | max_num = max(nums) 11 | return min(set(range(1,max_num+2))-set(nums)) 12 | # 2 13 | # 使用循环,从1遍历到len(nums)+1 14 | def firstMissingPositive(self, nums): 15 | if len(nums)==0: 16 | return 1 17 | #nums.sort() 18 | # if nums[0]>1: 19 | # return 1 20 | for i in range(1,len(nums)+2): 21 | if i not in nums: 22 | return i -------------------------------------------------------------------------------- /code/412#Fizz Buzz.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/fizz-buzz/description/ 2 | class Solution: 3 | def fizzBuzz(self, n): 4 | """ 5 | :type n: int 6 | :rtype: List[str] 7 | """ 8 | res = list(range(1,n+1)) 9 | for i in range(len(res)): 10 | if res[i]%15==0: 11 | res[i]="FizzBuzz" 12 | elif res[i]%3==0: 13 | res[i]="Fizz" 14 | elif res[i]%5==0: 15 | res[i]="Buzz" 16 | else: 17 | res[i]=str(res[i]) 18 | return res -------------------------------------------------------------------------------- /code/414#Third Maximum Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/third-maximum-number/description/ 2 | class Solution(object): 3 | # 1 4 | # 先转化为set 5 | # 转化为list排序 6 | def thirdMax(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | a = set(nums) 12 | return sorted(list(a))[-3 if len(a)>=3 else -1] 13 | # 2 14 | def thirdMax(self, nums): 15 | if len(nums) < 3: 16 | return max(nums) 17 | else: 18 | newNums = set(nums) 19 | if len(newNums) <3: 20 | return max(newNums) 21 | else: 22 | newNums = sorted(newNums) 23 | return newNums[len(newNums)-3] -------------------------------------------------------------------------------- /code/415#Add Strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/add-strings/description/ 2 | class Solution: 3 | def addStrings(self, num1, num2): 4 | """ 5 | :type num1: str 6 | :type num2: str 7 | :rtype: str 8 | """ 9 | num1, num2 = list(num1), list(num2) 10 | carry, res = 0, [] 11 | while len(num2) > 0 or len(num1) > 0: 12 | n1 = ord(num1.pop())-ord('0') if len(num1) > 0 else 0 13 | n2 = ord(num2.pop())-ord('0') if len(num2) > 0 else 0 14 | 15 | temp = n1 + n2 + carry 16 | res.append(temp % 10) 17 | carry = temp // 10 18 | if carry: res.append(carry) 19 | return ''.join([str(i) for i in res])[::-1] 20 | 21 | -------------------------------------------------------------------------------- /code/429#N-ary Tree Level Order Traversal.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/ 2 | """ 3 | # Definition for a Node. 4 | class Node(object): 5 | def __init__(self, val, children): 6 | self.val = val 7 | self.children = children 8 | """ 9 | class Solution(object): 10 | def levelOrder(self, root): 11 | """ 12 | :type root: Node 13 | :rtype: List[List[int]] 14 | """ 15 | q, ret = [root], [] 16 | while any(q): 17 | ret.append([node.val for node in q]) 18 | q = [child for node in q for child in node.children if child] 19 | return ret -------------------------------------------------------------------------------- /code/434#Number of Segments in a String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-segments-in-a-string/description/ 2 | class Solution(object): 3 | def countSegments(self, s): 4 | """ 5 | :type s: str 6 | :rtype: int 7 | """ 8 | return len(s.split()) -------------------------------------------------------------------------------- /code/438#Find All Anagrams in a String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ 2 | from collections import Counter 3 | 4 | class Solution(object): 5 | def findAnagrams(self, s, p): 6 | """ 7 | :type s: str 8 | :type p: str 9 | :rtype: List[int] 10 | """ 11 | res = [] 12 | pCounter = Counter(p) 13 | sCounter = Counter(s[:len(p)-1]) 14 | for i in range(len(p)-1,len(s)): 15 | sCounter[s[i]] += 1 # include a new char in the window 16 | if sCounter == pCounter: # This step is O(1), since there are at most 26 English letters 17 | res.append(i-len(p)+1) # append the starting index 18 | sCounter[s[i-len(p)+1]] -= 1 # decrease the count of oldest char in the window 19 | if sCounter[s[i-len(p)+1]] == 0: 20 | del sCounter[s[i-len(p)+1]] # remove the count if it is 0 21 | return res 22 | -------------------------------------------------------------------------------- /code/441#Arranging Coins.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/arranging-coins/description/ 2 | class Solution(object): 3 | # 1 公式法 4 | # h*(h+1)/2 h^2+h-2n<0 5 | # h ≤ (sqrt(8n + 1) -1)/2 6 | def arrangeCoins(self, n): 7 | """ 8 | :type n: int 9 | :rtype: int 10 | """ 11 | return int((math.sqrt(8 * n + 1)-1)/2) 12 | # 2 二分法 13 | def arrangeCoins2(self, n) 14 | target=2*n 15 | low,high=1,n 16 | 17 | while low<=high: 18 | mid=(low+high)/2 19 | ans=mid*(mid+1) 20 | if anstarget: 23 | high=mid-1 24 | if ans==target: 25 | return mid 26 | return high -------------------------------------------------------------------------------- /code/442#Find All Duplicates in an Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-all-duplicates-in-an-array/description/ 2 | class Solution: 3 | def findDuplicates(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: List[int] 7 | """ 8 | from collections import Counter 9 | mapping = Counter(nums) 10 | return [i for i,v in mapping.items() if v==2] 11 | def findDuplicates(self, nums): 12 | nums_unique = set (nums) 13 | nums_duplicate = [] 14 | for num in nums: 15 | if num not in nums_unique: 16 | nums_duplicate.append (num) 17 | else: nums_unique.remove (num) 18 | 19 | return nums_duplicate -------------------------------------------------------------------------------- /code/443#String Compression.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/submissions/detail/185625748/ 2 | class Solution: 3 | # 1 4 | # 使用left保存当前长度 5 | def compress(self, chars): 6 | """ 7 | :type chars: List[str] 8 | :rtype: int 9 | """ 10 | left = i = 0 11 | while i < len(chars): 12 | char, length = chars[i], 1 13 | while (i + 1) < len(chars) and char == chars[i + 1]: 14 | length, i = length + 1, i + 1 15 | chars[left] = char 16 | if length > 1: 17 | len_str = str(length) 18 | chars[left + 1:left + 1 + len(len_str)] = len_str 19 | left += len(len_str) 20 | left, i = left + 1, i + 1 21 | return left 22 | -------------------------------------------------------------------------------- /code/447#Number of Boomerangs.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/number-of-boomerangs/description/ 2 | class Solution(object): 3 | def numberOfBoomerangs(self, points): 4 | """ 5 | :type points: List[List[int]] 6 | :rtype: int 7 | """ 8 | res = 0 9 | for p in points: 10 | cmap = {} 11 | for q in points: 12 | f = p[0]-q[0] 13 | s = p[1]-q[1] 14 | cmap[f*f + s*s] = 1 + cmap.get(f*f + s*s, 0) 15 | for k in cmap: 16 | res += cmap[k] * (cmap[k] -1) 17 | return res 18 | -------------------------------------------------------------------------------- /code/448#EFind All Numbers Disappeared in an Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/ 2 | class Solution: 3 | # 1 4 | # 先使用set,然后遍历1-n,将不在set中的取出 5 | def findDisappearedNumbers(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: List[int] 9 | """ 10 | length = len(nums) 11 | num_set = set(nums) 12 | res = [] 13 | for i in range(1,length+1): 14 | if i not in num_set: 15 | res.append(i) 16 | return res 17 | # 2 使用两个set相减,耗时长 18 | def findDisappearedNumbers2(self,nums): 19 | all_nums = [i for i in range(1, len(nums)+1)] 20 | return list(set(all_nums) - set(nums)) -------------------------------------------------------------------------------- /code/455#Assign Cookies.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/assign-cookies/description/ 2 | class Solution: 3 | def findContentChildren(self, g, s): 4 | """ 5 | :type g: List[int] 6 | :type s: List[int] 7 | :rtype: int 8 | """ 9 | g.sort() 10 | s.sort() 11 | i = j = 0 12 | res = 0 13 | while i0: 17 | sum&=sum-1 18 | count+=1 19 | return count -------------------------------------------------------------------------------- /code/47#Permutations II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/permutations-ii/ 2 | """ 3 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 4 | 5 | Example: 6 | 7 | Input: [1,1,2] 8 | Output: 9 | [ 10 | [1,1,2], 11 | [1,2,1], 12 | [2,1,1] 13 | ] 14 | """ 15 | 16 | class Solution1: 17 | def permuteUnique(nums): 18 | permutations = [[]] 19 | 20 | for head in nums: 21 | permutations = [rest[:i] + [head] + rest[i:] for rest in permutations for i in 22 | range((rest + [head]).index(head) + 1)] 23 | 24 | return permutations 25 | 26 | 27 | class Solution2: 28 | def permuteUnique(self, nums): 29 | ans = [[]] 30 | for n in nums: 31 | new_ans = [] 32 | for l in ans: 33 | for i in range(len(l) + 1): 34 | new_ans.append(l[:i] + [n] + l[i:]) 35 | if i < len(l) and l[i] == n: 36 | break # handles duplication 37 | ans = new_ans 38 | return ans 39 | -------------------------------------------------------------------------------- /code/476#Number Complement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findComplement(self, num): 3 | """ 4 | :type num: int 5 | :rtype: int 6 | """ 7 | # 1 8 | # 先计算出位数l 9 | # 取反的数与原数相加为1后面l个0 10 | # 5:101 2:010 5+2=7:111 11 | s = bin(num)[2:] 12 | l = len(s) 13 | return 2**l-1-num -------------------------------------------------------------------------------- /code/479#Largest Palindrome Product.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-palindrome-product/description/ 2 | class Solution: 3 | # 答案导向的解答。没有参考性 4 | # 这道题点赞62,被踩1060 5 | # 建议别做这题 6 | def largestPalindrome(self, n): 7 | """ 8 | :type n: int 9 | :rtype: int 10 | """ 11 | if n == 1: return 9 12 | if n == 2: return 987 13 | if n == 3: return 123 # 913 993 14 | if n == 4: return 597 # 9901 9999 15 | if n == 5: return 677 # 99681 99979 16 | if n == 6: return 1218 # 999001 999999 17 | if n == 7: return 877 # 9997647 9998017 18 | if n == 8: return 475 # 99990001 99999999 -------------------------------------------------------------------------------- /code/482#License Key Formatting.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/license-key-formatting/description/ 2 | class Solution: 3 | # 理解题目意思很重要 4 | 5 | def licenseKeyFormatting(self, S, K): 6 | S=S.upper() 7 | listS = S.split("-") 8 | full = "".join(listS) 9 | full = full[::-1] 10 | if K!= 0: 11 | newsplit = [full[K*i:K*(i+1)] for i in range(1+len(full)//K)] 12 | if newsplit[-1] == "": 13 | newsplit.pop(-1) 14 | return "-".join(newsplit)[::-1] 15 | 16 | else: 17 | return full[::-1] -------------------------------------------------------------------------------- /code/49#Group Anagrams.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/group-anagrams/description/ 2 | class Solution: 3 | # 1 4 | # 用(2,0,1,1,..)的26位元组来表示映射 5 | # defaultdict()可以存储list 6 | def groupAnagrams(self, strs): 7 | """ 8 | :type strs: List[str] 9 | :rtype: List[List[str]] 10 | """ 11 | ans = collections.defaultdict() 12 | for s in strs: 13 | ans[tuple(sorted(s))].append(s) 14 | return ans.values() 15 | 16 | def groupAnagrams(strs): 17 | ans = collections.defaultdict(list) 18 | for s in strs: 19 | count = [0] * 26 20 | for c in s: 21 | count[ord(c) - ord('a')] += 1 22 | ans[tuple(count)].append(s) 23 | return ans.values() -------------------------------------------------------------------------------- /code/492#Construct the Rectangle.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/construct-the-rectangle/description/ 2 | class Solution(object): 3 | def constructRectangle(self, area): 4 | """ 5 | :type area: int 6 | :rtype: List[int] 7 | """ 8 | # 9 | bondary = int(area**0.5) 10 | for i in range(bondary,0,-1): 11 | if area%i == 0: 12 | return [area//i,i] -------------------------------------------------------------------------------- /code/500#Keyboard Row.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/keyboard-row/description/ 2 | class Solution: 3 | # 1 4 | # 利用集合方法issubset() 5 | def findWords(self, words): 6 | """ 7 | :type words: List[str] 8 | :rtype: List[str] 9 | """ 10 | line1 = "qwertyuiopQWERTYUIOP" 11 | line2 = "asdfghjklASDFGHJKL" 12 | line3 = "zxcvbnmZXCVBNM" 13 | res = [] 14 | for word in words: 15 | s = set(word) 16 | if s.issubset(line1) or s.issubset(line2) or s.issubset(line3): 17 | res.append(word) 18 | return res -------------------------------------------------------------------------------- /code/504#Base 7.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/base-7/description/ 2 | class Solution: 3 | # 1 常规方法 4 | # 需要区分正负数与零 5 | def convertToBase7(self, num): 6 | """ 7 | :type num: int 8 | :rtype: str 9 | """ 10 | flag = 0 11 | if num == 0: 12 | return "0" 13 | elif num < 0: 14 | flag = 1 15 | num = 0-num 16 | res = [] 17 | while num: 18 | bit = num%7 19 | num = num//7 20 | res.insert(0,str(bit)) 21 | return ''.join(res) if flag==0 else "-"+''.join(res) -------------------------------------------------------------------------------- /code/506#Relative Ranks.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/relative-ranks/description/ 2 | class Solution: 3 | def findRelativeRanks(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: List[str] 7 | """ 8 | N = len(nums) 9 | p = [(n, i) for i, n in enumerate(nums)] 10 | p = sorted(p, key=lambda x: x[0], reverse=True) 11 | ans = [0] * N 12 | for rank in range(N): 13 | idx = p[rank][1] 14 | if rank == 0: 15 | ans[idx] = "Gold Medal" 16 | elif rank == 1: 17 | ans[idx] = "Silver Medal" 18 | elif rank == 2: 19 | ans[idx] = "Bronze Medal" 20 | else: 21 | ans[idx] = str(rank+1) 22 | return ans -------------------------------------------------------------------------------- /code/507#Perfect Number.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/perfect-number/description/ 2 | class Solution: 3 | # 1 暴力破解 4 | def checkPerfectNumber(self, num): 5 | """ 6 | :type num: int 7 | :rtype: bool 8 | """ 9 | return num in (6,28,496,8128,33550336) 10 | # 2 常规法 11 | def checkPerfectNumber(self, num): 12 | if num <= 1: 13 | return False 14 | res = 1 15 | bound = int(num**0.5) 16 | i = 2 17 | while i <= bound: 18 | if num%i==0: 19 | res += i + num//i 20 | bound = min(bound,num//i) 21 | if res>num: 22 | return False 23 | i+=1 24 | if res==num: 25 | return True 26 | return False 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /code/509#Fibonacci Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, N): 3 | """ 4 | :type N: int 5 | :rtype: int 6 | """ 7 | m = 0 8 | n = 1 9 | if N == 0: 10 | return 0 11 | for i in range(N-1): 12 | temp = m + n 13 | m = n 14 | n = temp 15 | return n -------------------------------------------------------------------------------- /code/520#Detect Capital.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/detect-capital/description/ 2 | class Solution: 3 | def detectCapitalUse(self, word): 4 | """ 5 | :type word: str 6 | :rtype: bool 7 | """ 8 | if len(word) == 1: 9 | return True 10 | if word.islower() or word.isupper(): 11 | return True 12 | elif word[0].isupper() and word[1:].islower(): 13 | return True 14 | return False 15 | -------------------------------------------------------------------------------- /code/521#Longest Uncommon Subsequence I.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-uncommon-subsequence-i/description/ 2 | # 这题没什么意义 3 | # For strings A, B, when len(A) > len(B), 4 | # the longest possible subsequence of either A or B is A, 5 | # and no subsequence of B can be equal to A. Answer: len(A). 6 | 7 | When len(A) == len(B), the only subsequence of B equal to A is B; so as long as A != B, the answer remains len(A). 8 | 9 | When A == B, any subsequence of A can be found in B and vice versa, so the answer is -1. 10 | class Solution: 11 | def findLUSlength(self, a, b): 12 | """ 13 | :type a: str 14 | :type b: str 15 | :rtype: int 16 | """ 17 | if a == b: 18 | return -1 19 | return max(len(a),len(b)) -------------------------------------------------------------------------------- /code/53#Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-subarray/description/ 2 | class Solution: 3 | def maxSubArray(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | 策略:遍历所有数,如果当前和小于0,则从下一个数开始重新算 8 | 用res保存当前最大,current_sum保存遍历数组的和大小 9 | """ 10 | res = nums[0] 11 | current_sum = nums[0] 12 | for i in range(1,len(nums)): 13 | current_sum = max(current_sum + nums[i], nums[i]) 14 | res = max(res, current_sum) 15 | return res -------------------------------------------------------------------------------- /code/532#K-diff Pairs in an Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/k-diff-pairs-in-an-array/description/ 2 | import collections 3 | class Solution(object): 4 | def findPairs(self, nums, k): 5 | """ 6 | :type nums: List[int] 7 | :type k: int 8 | :rtype: int 9 | """ 10 | if k>0: 11 | return len(set(nums)&set(n+k for n in nums)) 12 | elif k==0: 13 | return sum(v>1 for v in collections.Counter(nums).values()) 14 | else: 15 | return 0 -------------------------------------------------------------------------------- /code/537#Complex Number Multiplication.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/complex-number-multiplication/description/ 2 | class Solution: 3 | def complexNumberMultiply(self, a, b): 4 | """ 5 | :type a: str 6 | :type b: str 7 | :rtype: str 8 | """ 9 | # a_real = int(a[:a.find('+')]) 10 | # a_ima = int(a[a.find('+')+1:-1]) 11 | # b_real = int(b[:b.find('+')]) 12 | # b_ima = int(b[b.find('+')+1:-1]) 13 | res_real = a_real*b_real-a_ima*b_ima 14 | res_ima = a_real*b_ima+a_ima*b_real 15 | a_real, a_ima = list(map(int,a[:-1].split('+'))) 16 | b_real, b_ima = list(map(int,b[:-1].split('+'))) 17 | res_real = a_real*b_real-a_ima*b_ima 18 | res_ima = a_real*b_ima+a_ima*b_real 19 | 20 | return "{0}+{1}i".format(res_real, res_ima) -------------------------------------------------------------------------------- /code/539#Minimum Time Difference.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-time-difference/description/ 2 | #24*60 = 1440 种情况 3 | class Solution: 4 | def findMinDifference(self, timePoints): 5 | """ 6 | :type timePoints: List[str] 7 | :rtype: int 8 | """ 9 | def diff(tp1,tp2): 10 | return 60*(int(tp1[0:2])-int(tp2[0:2]))+int(tp1[3:])-int(tp2[3:]) 11 | 12 | if len(set(timePoints))1 or count_L>2: 21 | return False 22 | return True 23 | # 2 使用正则 24 | def checkRecord(self, s): 25 | return False if bool(re.search(r"(L){3,}",s)) or bool(re.search(r"(A).*\1",s)) else True 26 | -------------------------------------------------------------------------------- /code/553#Optimal Division.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/optimal-division/description/ 2 | class Solution: 3 | # 1 4 | # 对于a/b/c/d/e 5 | # 最大应该是 a*c*d*e/b 等价于 a/(b/c/d/e) 6 | # 策略: 7 | # 1)只有一个数,本身 8 | # 2)只有两个数,a/b 9 | # 3)两个以上的数需要添加括号: a/(b/c) 10 | def optimalDivision(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: str 14 | """ 15 | if len(nums)==1: 16 | return str(nums[0]) 17 | elif len(nums)==2: 18 | return str(nums[0])+'/'+str(nums[1]) 19 | else: 20 | return "{0}/({1})".format(nums[0],'/'.join(map(str,nums[1:]))) -------------------------------------------------------------------------------- /code/557#Reverse Words in a String III.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/submissions/detail/187303513/ 2 | class Solution: 3 | # 1 4 | # one line 5 | def reverseWords(self, s): 6 | """ 7 | :type s: str 8 | :rtype: str 9 | """ 10 | return ' '.join(word[::-1] for word in s.split()) -------------------------------------------------------------------------------- /code/559#Maximum Depth of N-ary Tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/ 2 | """ 3 | # Definition for a Node. 4 | class Node(object): 5 | def __init__(self, val, children): 6 | self.val = val 7 | self.children = children 8 | """ 9 | class Solution(object): 10 | # 1 BFS 11 | def maxDepth(self, root): 12 | """ 13 | :type root: Node 14 | :rtype: int 15 | """ 16 | q, level = root and [root], 0 17 | while q: 18 | q, level = [child for node in q for child in node.children if child], level + 1 19 | return level 20 | # 2 DFS 21 | def maxDepth(self, root, level = 1): 22 | return max(root and [self.maxDepth(child, level + 1) for child in root.children] + [level] or [0]) -------------------------------------------------------------------------------- /code/561#Array Partition I.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/array-partition-i/description/ 2 | class Solution(object): 3 | # 事实上只要知道这个最大的逻辑 4 | # 对于(1,2,3,4),(1,2)(3,4)组合最大 5 | # 所以思路是:先按照顺序排序,然后两两组合。 6 | def arrayPairSum(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | return sum(sorted(nums[::2])) -------------------------------------------------------------------------------- /code/563#Binary Tree Tilt.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-tree-tilt/description/ 2 | # Definition for a binary tree node. 3 | # class TreeNode(object): 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.left = None 7 | # self.right = None 8 | 9 | class Solution(object): 10 | def findTilt(self, root): 11 | self.ans = 0 12 | def _sum(node): 13 | if not node: return 0 14 | left, right = _sum(node.left), _sum(node.right) 15 | self.ans += abs(left - right) 16 | return node.val + left + right 17 | _sum(root) 18 | return self.ans 19 | -------------------------------------------------------------------------------- /code/566#Reshape the Matrix.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reshape-the-matrix/description/ 2 | class Solution(object): 3 | # 1 常规 4 | def matrixReshape(self, nums, r, c): 5 | """ 6 | :type nums: List[List[int]] 7 | :type r: int 8 | :type c: int 9 | :rtype: List[List[int]] 10 | """ 11 | if r * c != len(nums) * len(nums[0]): 12 | return nums 13 | else: 14 | items = [y for x in nums for y in x] 15 | return [items[x*c : ((x+1)*c)] for x in range(r)] 16 | # 2 17 | # 巧妙运用各种函数 18 | def matrixReshape(self, nums, r, c): 19 | flat = sum(nums, []) 20 | if len(flat) != r * c: 21 | return nums 22 | tuples = zip(*([iter(flat)] * c)) 23 | return map(list, tuples) 24 | 25 | 26 | -------------------------------------------------------------------------------- /code/575#Distribute Candies.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/distribute-candies/description/ 2 | class Solution: 3 | def distributeCandies(self, candies): 4 | """ 5 | :type candies: List[int] 6 | :rtype: int 7 | """ 8 | return min(len(set(candies)),len(candies)//2) -------------------------------------------------------------------------------- /code/58#Length of Last Word.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/length-of-last-word/description/ 2 | class Solution: 3 | # 1 one line 4 | def lengthOfLastWord(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | return 0 if not s.split() else len(s.split()[-1]) 10 | # 2 11 | 12 | -------------------------------------------------------------------------------- /code/581#Shortest Unsorted Continuous Subarray.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/ 2 | class Solution: 3 | # 1 4 | def findUnsortedSubarray(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | n = len(nums) 10 | cmax, cmin = -float('inf'), float('inf') 11 | l, r = 0, -1 12 | for i in range(n): 13 | cmax = max(cmax, nums[i]) 14 | cmin = min(cmin, nums[n - 1 - i]) 15 | if nums[i] != cmax: r = i 16 | if nums[n - 1 - i] != cmin: l = n - 1 - i 17 | return r - l + 1 18 | # 19 | # thank @lee215 20 | # 比较与排序好的数组,使用zip然比较 21 | def findUnsortedSubarray(self, nums): 22 | is_same = [a == b for a, b in zip(nums, sorted(nums))] 23 | return 0 if all(is_same) else len(nums) - is_same.index(False) - is_same[::-1].index(False) -------------------------------------------------------------------------------- /code/594#Longest Harmonious Subsequence.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-harmonious-subsequence/description/ 2 | """ 3 | We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. 4 | 5 | Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. 6 | 7 | Example 1: 8 | Input: [1,3,2,2,5,2,3,7] 9 | Output: 5 10 | Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 11 | Note: The length of the input array will not exceed 20,000. 12 | """ 13 | class Solution: 14 | def findLHS(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: int 18 | """ 19 | from collections import Counter 20 | res = 0 21 | mapping = Counter(nums) 22 | for k in mapping.keys(): 23 | if k+1 in mapping: 24 | res = max(res, mapping.get(k) + mapping.get(k+1)) 25 | return res 26 | 27 | 28 | -------------------------------------------------------------------------------- /code/598#Range Addition II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/range-addition-ii/description/ 2 | class Solution: 3 | # 1 4 | def maxCount1(self, m, n, ops): 5 | """ 6 | :type m: int 7 | :type n: int 8 | :type ops: List[List[int]] 9 | :rtype: int 10 | """ 11 | a,b=m,n 12 | for i in ops: 13 | a = min(i[0],a) 14 | b = min(i[1],b) 15 | return a*b 16 | # 2 17 | def maxCount2(self, m, n, ops): 18 | if not ops: 19 | return m*n 20 | return min(op[0] for op in ops)*min(op[1] for op in ops) -------------------------------------------------------------------------------- /code/606#Construct String from Binary Tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/construct-string-from-binary-tree/description/ 2 | class Solution: 3 | def tree2str(self, t): 4 | """ 5 | :type t: TreeNode 6 | :rtype: str 7 | """ 8 | if not t: return '' 9 | left = '({})'.format(self.tree2str(t.left)) if (t.left or t.right) else '' 10 | right = '({})'.format(self.tree2str(t.right)) if t.right else '' 11 | return '{}{}{}'.format(t.val, left, right) 12 | 13 | def tree2str(self, t): 14 | if not t: return "" 15 | subleft = "(%s)" % (self.tree2str(t.left) if t.left or t.right else "") 16 | subright = "(%s)" % (self.tree2str(t.right) if t.right else "") 17 | return ("%s%s%s" % (str(t.val), subleft, subright)).replace("()","") 18 | -------------------------------------------------------------------------------- /code/609#Find Duplicate File in System.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-duplicate-file-in-system/description/ 2 | class Solution: 3 | # 1 4 | # defaultdict 可以将一个key对应多个value 5 | def findDuplicate(self, paths): 6 | """ 7 | :type paths: List[str] 8 | :rtype: List[List[str]] 9 | """ 10 | from collections import defaultdict 11 | d = defaultdict(list) 12 | for p in paths: 13 | path, *files = p.split() 14 | for file in files: 15 | content = file[file.index('(')+1:-1] 16 | name = file[:file.index('(')] 17 | d[content].append('/'.join([path,name])) 18 | return list(v for v in d.values() if len(v)>=2) 19 | -------------------------------------------------------------------------------- /code/617#Merge Two Binary Trees.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/merge-two-binary-trees/description/ 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.left = None 7 | # self.right = None 8 | 9 | class Solution: 10 | # 1 递归 构造新的树 11 | def mergeTrees(self, t1, t2): 12 | """ 13 | :type t1: TreeNode 14 | :type t2: TreeNode 15 | :rtype: TreeNode 16 | """ 17 | if not t1 and not t2: 18 | return None 19 | ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)) 20 | ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left) 21 | ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right) 22 | return ans 23 | # 2 递归 在原树的基础上构造 24 | def mergeTrees(self, t1, t2): 25 | if t1 and t2: 26 | t1.val += t2.val 27 | t1.left = self.mergeTrees(t1.left,t2.left) 28 | t2.right = self.mergeTrees(t1.right,t2.right) 29 | return t1 30 | else: 31 | return t1 or t2 32 | # 3 使用栈非递归 33 | # 按顺序存入栈 34 | 35 | -------------------------------------------------------------------------------- /code/63#Unique Paths II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/submissions/detail/193955775/ 2 | class Solution: 3 | def uniquePathsWithObstacles(self, obstacleGrid): 4 | """ 5 | :type obstacleGrid: List[List[int]] 6 | :rtype: int 7 | """ 8 | n = len(obstacleGrid) 9 | m = len(obstacleGrid[0]) 10 | dp = [[0]*m for i in range(n)] 11 | for i in range(n): 12 | if obstacleGrid[i][0] == 1: 13 | break 14 | dp[i][0] = 1 15 | for i in range(m): 16 | if obstacleGrid[0][i] == 1: 17 | break 18 | dp[0][i] = 1 19 | for i in range(1, n): 20 | for j in range(1, m): 21 | if obstacleGrid[i][j] == 0: 22 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 23 | else: 24 | pass 25 | return dp[n-1][m-1] -------------------------------------------------------------------------------- /code/637#Average of Levels in Binary Tree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/average-of-levels-in-binary-tree/description/ 2 | # Definition for a binary tree node. 3 | # class TreeNode: 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.left = None 7 | # self.right = None 8 | 9 | class Solution: 10 | def averageOfLevels(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: List[float] 14 | """ 15 | if not root: 16 | return [] 17 | res = [] 18 | lis = [root] 19 | while lis: 20 | lis2 = [] 21 | level_sum = 0 22 | for each in lis: 23 | level_sum += each.val 24 | if each.left: 25 | lis2.append(each.left) 26 | if each.right: 27 | lis2.append(each.right) 28 | 29 | res.append(level_sum / len(lis)) 30 | lis = lis2 31 | return res 32 | -------------------------------------------------------------------------------- /code/643#Maximum Average Subarray I.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-average-subarray-i/description/ 2 | class Solution: 3 | def findMaxAverage1(self, nums, k): 4 | """ 5 | :type nums: List[int] 6 | :type k: int 7 | :rtype: float 8 | """ 9 | dp = [0] 10 | for x in nums: 11 | dp.append(dp[-1] + x) 12 | ma = max(dp[i+k] - dp[i] for i in range(len(nums) - k + 1)) 13 | return ma / k 14 | def findMaxAverage2(self, nums, k): 15 | s= sum(nums[:k]) 16 | max_sum= s 17 | for i in range(len(nums)-k): 18 | temp= s-nums[i]+nums[i+k] 19 | if temp>max_sum: 20 | max_sum= temp 21 | s=temp 22 | return max_sum/k -------------------------------------------------------------------------------- /code/645#Set Mismatch.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/set-mismatch/description/ 2 | class Solution: 3 | def findErrorNums(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: List[int] 7 | """ 8 | once = set(nums) 9 | sum_whole = sum(range(len(nums)+1)) # sum of 1~n 10 | sum_once = sum(once) # sum of nums minus dupicated num 11 | sum_all = sum(nums) # sum of nums 12 | 13 | dupicated = sum_all-sum_once 14 | left = sum_whole -sum_once 15 | return [dupicated,left] 16 | 17 | -------------------------------------------------------------------------------- /code/657#Robot Return to Origin.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/robot-return-to-origin/description/ 2 | class Solution: 3 | def judgeCircle(self, moves): 4 | """ 5 | :type moves: str 6 | :rtype: bool 7 | """ 8 | return moves.count('L')==moves.count('R') and moves.count('U')==moves.count('D') -------------------------------------------------------------------------------- /code/66#Plus One.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/plus-one/description/ 2 | class Solution: 3 | # 1 4 | def plusOne(self, digits): 5 | """ 6 | :type digits: List[int] 7 | :rtype: List[int] 8 | """ 9 | return list(map(int,str(int("".join(map(str,digits)))+1))) 10 | # 2 11 | def plusOne(self, digits): 12 | for i in range(len(digits)-1,-1,-1): 13 | if digits[i]<9: 14 | digits[i]+=1 15 | return digits 16 | else: 17 | digits[i] =0 18 | digits.insert(0,1) 19 | return digits -------------------------------------------------------------------------------- /code/661#mage Smoother.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/image-smoother/description/ 2 | class Solution: 3 | def imageSmoother(self, M): 4 | """ 5 | :type M: List[List[int]] 6 | :rtype: List[List[int]] 7 | """ 8 | R, C = len(M), len(M[0]) 9 | ans = [[0] * C for _ in M] 10 | 11 | for r in range(R): 12 | for c in range(C): 13 | count = 0 14 | for nr in (r-1, r, r+1): 15 | for nc in (c-1, c, c+1): 16 | if 0 <= nr < R and 0 <= nc < C: 17 | ans[r][c] += M[nr][nc] 18 | count += 1 19 | ans[r][c] //= count 20 | return ans 21 | 22 | -------------------------------------------------------------------------------- /code/665#Non-decreasing Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/non-decreasing-array/description/ 2 | class Solution: 3 | def checkPossibility(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: bool 7 | """ 8 | p = None 9 | for i in range(len(nums) - 1): 10 | if nums[i] > nums[i+1]: 11 | if p is not None: 12 | return False 13 | p = i 14 | return (p is None or p == 0 or p == len(nums)-2 or 15 | nums[p-1] <= nums[p+1] or nums[p] <= nums[p+2]) 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /code/67#Add Binary.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/add-binary/description/ 2 | class Solution(object): 3 | def addBinary(self, a, b): 4 | """ 5 | :type a: str 6 | :type b: str 7 | :rtype: str 8 | """ 9 | sum = int(a,2)+int(b,2) 10 | return(bin(sum)[2:]) -------------------------------------------------------------------------------- /code/674#Longest Continuous Increasing Subsequence.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/ 2 | class Solution: 3 | def findLengthOfLCIS(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | if len(nums) < 1: 9 | return 0 10 | temp = 1 11 | sum = 1 12 | for i in range(1, len(nums)): 13 | if nums[i] > nums[i-1]: 14 | sum += 1 15 | if sum > temp: 16 | temp = sum 17 | else: 18 | sum = 1 19 | return temp -------------------------------------------------------------------------------- /code/686#Repeated String Match.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/repeated-string-match/description/ 2 | class Solution: 3 | def __init__(self, arg): 4 | super(ClassName, self).__init__() 5 | self.arg = arg 6 | 7 | # beat 99.99% 8 | def repeatedStringMatch(self, A, B): 9 | if set(A) != set(B): 10 | if len(A) < len(B): 11 | return -1 12 | # 上面的三行用来过滤大量的-1 case 13 | q = (len(B) - 1) // len(A) + 1 14 | for i in range(2): 15 | if B in A * (q+i): return q+i 16 | return -1 -------------------------------------------------------------------------------- /code/69#Sqrt(x).py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sqrtx/description/ 2 | class Solution: 3 | # 1 标准版 4 | def mySqrt(self, x): 5 | """ 6 | :type x: int 7 | :rtype: int 8 | """ 9 | low = 0 10 | high = x 11 | while low<=high: 12 | mid = low+(high-low)//2 13 | if x==mid**2: 14 | return mid 15 | elif x= 0 and int(str_x[::-1]) <= (2**31-1): 11 | return int(str_x[::-1]) 12 | elif x < 0 and -int(str_x[:0:-1]) >= (-2**31): 13 | return -int(str_x[:0:-1]) 14 | else: 15 | return 0 16 | -------------------------------------------------------------------------------- /code/70#Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/climbing-stairs/description/ 2 | class Solution: 3 | # 1 4 | def climbStairs(self, n): 5 | """ 6 | :type n: int 7 | :rtype: int 8 | """ 9 | if n==0: 10 | return 0 11 | if n==1: 12 | return 1 13 | if n==2: 14 | return 2 15 | a,b=1,2 16 | for i in range(3,n+1): 17 | temp=a+b 18 | a,b=b,temp 19 | return temp 20 | # 2 使用递归,可能会溢出 -------------------------------------------------------------------------------- /code/709#To Lower Case.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/to-lower-case/description/ 2 | class Solution: 3 | # 1 使用内置函数lower() 4 | def toLowerCase(self, str): 5 | """ 6 | :type str: str 7 | :rtype: str 8 | """ 9 | return str.lower() 10 | # 2 对于A~Z的字符进行转换 Ascll码+32 11 | def toLowerCase2(self, str): 12 | result = "" 13 | for c in str: 14 | if c >="A" and c<="Z": 15 | result= result+chr(ord(c)+32) 16 | else: 17 | result =result+ c 18 | return result -------------------------------------------------------------------------------- /code/717#1-bit and 2-bit Characters.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/1-bit-and-2-bit-characters/description/ 2 | class Solution: 3 | # 1 4 | # 只有0,10,1 5 | # 那么遇到1就移动两位,遇到0就移动一位 6 | # 如果最后能够遍历完,说明是true 7 | def isOneBitCharacter(self, bits): 8 | i = 0 9 | while i < len(bits) - 1: 10 | i += bits[i] + 1 11 | return i == len(bits) - 1 12 | # 2 13 | # 14 | def isOneBitCharacter(self, bits): 15 | parity = bits.pop() 16 | while bits and bits.pop(): 17 | parity ^= 1 18 | return parity == 0 19 | 20 | 21 | -------------------------------------------------------------------------------- /code/719#Find K-th Smallest Pair Distance.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countPairsLTE(self, array, value): 3 | ans = 0 4 | for i in range(len(array)): 5 | ans += bisect.bisect_right(array, array[i] + value, lo = i) - i - 1 6 | return ans 7 | 8 | def smallestDistancePair(self, nums, k): 9 | """ 10 | :type nums: List[int] 11 | :type k: int 12 | :rtype: int 13 | """ 14 | nums.sort() 15 | low, high = min([abs(nums[i] - nums[i+1]) for i in range(len(nums) - 1)]), abs(nums[0] - nums[~0]) 16 | while low < high: 17 | mid = (low + high)//2 18 | if self.countPairsLTE(nums, mid) < k: 19 | low = mid + 1 20 | else: 21 | high = mid 22 | return low -------------------------------------------------------------------------------- /code/724#Find Pivot Index.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-pivot-index/description/ 2 | class Solution: 3 | # 1 4 | # 需要注意,pivotindex可以是头部和尾部 5 | # 需要考虑[-1,-1,-1,0,1,1]这种情况pivotindex为0 6 | def pivotIndex(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: int 10 | """ 11 | S = sum(nums) 12 | leftsum = 0 13 | for i, x in enumerate(nums): 14 | if leftsum == (S - leftsum - x): 15 | return i 16 | leftsum += x 17 | return -1 18 | -------------------------------------------------------------------------------- /code/747#Largest Number At Least Twice of Others.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-number-at-least-twice-of-others/description/ 2 | class Solution: 3 | # 1 使用heapq 4 | def dominantIndex(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | import heapq 10 | if len(nums)<2: 11 | return 0 12 | max1,max2 = heapq.nlargest(2,nums) 13 | return -1 if max1/2= 2*second_num: 28 | return origin.index(max_num) 29 | else: 30 | return -1 -------------------------------------------------------------------------------- /code/767#Reorganize String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reorganize-string/description/ 2 | class Solution: 3 | # 1 4 | # 先把字符串排成按照重复数量从大到小的顺序的 5 | # 例如:"abbbccdddde" => "ddddbbbccae" 6 | # 然后将字符串分成两节插空排 7 | def reorganizeString(self, S): 8 | a = sorted(sorted(S), key=S.count) 9 | h = len(a) / 2 10 | a[1::2], a[::2] = a[:h], a[h:] 11 | return ''.join(a) * (a[-1:] != a[-2:-1]) 12 | -------------------------------------------------------------------------------- /code/771#Jewels and Stones.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/jewels-and-stones/description/ 2 | """ 3 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. 4 | Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 5 | 6 | The letters in J are guaranteed distinct, and all characters in J and S are letters. 7 | Letters are case sensitive, so "a" is considered a different type of stone from "A". 8 | 9 | Example 1: 10 | Input: J = "aA", S = "aAAbbbb" 11 | Output: 3 12 | 13 | Example 2: 14 | Input: J = "z", S = "ZZ" 15 | Output: 0 16 | Note: 17 | 18 | S and J will consist of letters and have length at most 50. 19 | The characters in J are distinct. 20 | """ 21 | 22 | 23 | class Solution: 24 | # 1 25 | # 97.83% 26 | def numJewelsInStones(self, J, S): 27 | """ 28 | :type J: str 29 | :type S: str 30 | :rtype: int 31 | """ 32 | ret = 0 33 | for i in J: 34 | ret += S.count(i) 35 | return ret -------------------------------------------------------------------------------- /code/783#Minimum Distance Between BST Nodes.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | 10 | pre = -float('inf') 11 | res = float('inf') 12 | 13 | def minDiffInBST(self, root: 'TreeNode') -> 'int': 14 | if root.left: 15 | self.minDiffInBST(root.left) 16 | self.res = min(self.res, root.val - self.pre) 17 | self.pre = root.val 18 | if root.right: 19 | self.minDiffInBST(root.right) 20 | return self.res -------------------------------------------------------------------------------- /code/784#Letter Case Permutation .py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCasePermutation(self, S): 3 | """ 4 | :type S: str 5 | :rtype: List[str] 6 | """ 7 | import itertools 8 | L = [[i.lower(), i.upper()] if i.isalpha() else i for i in S] 9 | return [''.join(i) for i in itertools.product(*L)] -------------------------------------------------------------------------------- /code/791#Custom Sort String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/custom-sort-string/description/ 2 | from collections import Counter 3 | class Solution: 4 | # 1 5 | # beat 100% 6 | # 1、使用collections.Counter() 将字符串返回成计数字典 7 | # 2、字典的keys()可以直接使用set操作 8 | # 3、最后结果由join连接所有小片段,减少内存使用 9 | # 4、生成器比List快 10 | def customSortString(self, S, T): 11 | """ 12 | :type S: str 13 | :type T: str 14 | :rtype: str 15 | """ 16 | c = Counter(T) 17 | lefted = c.keys()-set(S) 18 | return ''.join(letter*c[letter] for letter in ([s for s in S]+[l for l in lefted])) 19 | -------------------------------------------------------------------------------- /code/796#Rotate String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/rotate-string/ 2 | """ 3 | We are given two strings, A and B. 4 | 5 | A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. 6 | 7 | Example 1: 8 | Input: A = 'abcde', B = 'cdeab' 9 | Output: true 10 | 11 | Example 2: 12 | Input: A = 'abcde', B = 'abced' 13 | Output: false 14 | Note: 15 | 16 | A and B will have length at most 100. 17 | """ 18 | class Solution: 19 | def rotateString(self, A, B): 20 | """ 21 | :type A: str 22 | :type B: str 23 | :rtype: bool 24 | """ 25 | if len(B) != len(A): 26 | return False 27 | return B in A+A -------------------------------------------------------------------------------- /code/804#Unique Morse Code Words.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-morse-code-words/description/ 2 | class Solution: 3 | def uniqueMorseRepresentations(self, words): 4 | """ 5 | :type words: List[str] 6 | :rtype: int 7 | """ 8 | concatenation = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 9 | letter = "abcdefghijklmnopqrstuvwxyz" 10 | mapping = dict(zip(letter,concatenation)) 11 | return len(set("".join([mapping[c] for c in word]) for word in words)) -------------------------------------------------------------------------------- /code/809#Expressive Words.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/expressive-words/description/ 2 | class Solution: 3 | def expressiveWords(self, S, words): 4 | """ 5 | :type S: str 6 | :type words: List[str] 7 | :rtype: int 8 | """ 9 | return sum(self.check(S, W) for W in words) 10 | def check(self, S, W): 11 | i, j, i2, j2, n, m = 0, 0, 0, 0, len(S), len(W) 12 | while i < n and j < m: 13 | if S[i] != W[j]: return False 14 | while i2 < n and S[i2] == S[i]: i2 += 1 15 | while j2 < m and W[j2] == W[j]: j2 += 1 16 | if i2 - i != j2 - j and i2 - i < max(3, j2 - j): return False 17 | i, j = i2, j2 18 | return i == n and j == m -------------------------------------------------------------------------------- /code/819#Most Common Word.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/most-common-word/description/ 2 | from collections import Counter 3 | class Solution: 4 | def mostCommonWord(self, paragraph, banned): 5 | """ 6 | :type paragraph: str 7 | :type banned: List[str] 8 | :rtype: str 9 | """ 10 | count=collections.Counter(piece for piece in re.split('[ !?\',;.]',paragraph.lower()) if piece) 11 | banned=set(banned) 12 | return max((item for item in count.items() if item[0] not in banned),key=operator.itemgetter(1))[0] 13 | 14 | # re.split 15 | # 函数 re.split() 是非常实用的,因为它允许你为分隔符指定多个正则模式。 16 | # 比如,分隔符可以是逗号,分号或者是空格,并且后面紧跟着任意个的空格。 17 | # 只要这个模式被找到,那么匹配的分隔符两边的实体都会被当成是结果中的元素返回。 18 | # 返回结果为一个字段列表,这个跟 str.split() 返回值类型是一样的。 -------------------------------------------------------------------------------- /code/821#Shortest Distance to a Character.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/shortest-distance-to-a-character/ 2 | """ 3 | Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. 4 | 5 | Example 1: 6 | 7 | Input: S = "loveleetcode", C = 'e' 8 | Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] 9 | 10 | 11 | Note: 12 | 13 | S string length is in [1, 10000]. 14 | C is a single character, and guaranteed to be in string S. 15 | All letters in S and C are lowercase. 16 | """ 17 | class Solution: 18 | def shortestToChar(self, S, C): 19 | """ 20 | :type S: str 21 | :type C: str 22 | :rtype: List[int] 23 | """ 24 | n = len(S) 25 | ans = [0 if i == C else n for i in S] 26 | for i in range(n-1): 27 | ans[i+1] = min(ans[i+1],ans[i]+1) 28 | for j in range(n-1)[::-1]: 29 | ans[j] = min(ans[j],ans[j+1]+1) 30 | return ans 31 | 32 | 33 | -------------------------------------------------------------------------------- /code/83#Remove Duplicates from Sorted List.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ 2 | # Definition for singly-linked list. 3 | # class ListNode(object): 4 | # def __init__(self, x): 5 | # self.val = x 6 | # self.next = None 7 | 8 | class Solution(object): 9 | def deleteDuplicates(self, head): 10 | """ 11 | :type head: ListNode 12 | :rtype: ListNode 13 | """ 14 | if head is None or head.next is None: 15 | return head 16 | 17 | root, tail, head = head, head, head.next 18 | while head: 19 | if head.val != tail.val: 20 | tail.next = head 21 | tail = tail.next 22 | head = head.next 23 | tail.next = None 24 | 25 | return root 26 | -------------------------------------------------------------------------------- /code/830#Positions of Large Groups.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/positions-of-large-groups/description/ 2 | class Solution: 3 | def largeGroupPositions(self, S): 4 | """ 5 | :type S: str 6 | :rtype: List[List[int]] 7 | """ 8 | ans = [] 9 | i = 0 # The start of each group 10 | for j in range(len(S)): 11 | if j == len(S) - 1 or S[j] != S[j+1]: 12 | if j-i+1 >= 3: 13 | ans.append([i, j]) 14 | i = j+1 15 | return ans 16 | 17 | def largeGroupPositions(self, S): 18 | """ 19 | :type S: str 20 | :rtype: List[List[int]] 21 | """ 22 | i, j, n, res = 0, 0, len(S), [] 23 | 24 | while j < n: 25 | while j < n and S[i] == S[j]: 26 | j += 1 27 | if j - i >= 3: 28 | res.append((i, j-1)) 29 | i = j 30 | return res -------------------------------------------------------------------------------- /code/832#Flipping an Image.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/flipping-an-image/description/ 2 | class Solution: 3 | # in-place reverse 4 | def flipAndInvertImage(self, A): 5 | """ 6 | :type A: List[List[int]] 7 | :rtype: List[List[int]] 8 | """ 9 | for r in range(len(A)): 10 | for c in range(len(A[0])): 11 | # A[r][c] = 1-A[r][c] 12 | A[r][c] ^= 1 13 | for r in range(len(A)): 14 | A[r].reverse() 15 | return A 16 | # another space 17 | def flipAndInvertImage(self, A): 18 | """ 19 | :type A: List[List[int]] 20 | :rtype: List[List[int]] 21 | """ 22 | reverse = [] 23 | for i in A: 24 | temp = [] 25 | for j in reversed(i): 26 | if(j==0): 27 | temp.append(1) 28 | else: 29 | temp.append(0) 30 | reverse.append(temp) 31 | return (reverse) 32 | -------------------------------------------------------------------------------- /code/833#Find And Replace in String.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-and-replace-in-string/description/ 2 | class Solution(object): 3 | # 1 4 | # 反序很关键,可以从右往左遍历使用index 5 | # 利用zip函数 6 | def findReplaceString(self, S, indexes, sources, targets): 7 | """ 8 | :type S: str 9 | :type indexes: List[int] 10 | :type sources: List[str] 11 | :type targets: List[str] 12 | :rtype: str 13 | """ 14 | listOfS = list(S) 15 | distance = 0 16 | for index,source,target in sorted(zip(indexes, sources, targets),reverse=True): 17 | if S[i:i + len(s)] == s: 18 | listOfS[index:index+len(source)]=target 19 | return "".join(listOfS) 20 | 21 | def findReplaceString2(self, S, indexes, sources, targets): 22 | for i, s, t in sorted(zip(indexes, sources, targets), reverse=True): 23 | S = S[:i] + t + S[i + len(s):] if S[i:i + len(s)] == s else S 24 | return S -------------------------------------------------------------------------------- /code/84#Largest Rectangle in Histogram.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | class Solution: 3 | def largestRectangleArea(self, heights): 4 | """ 5 | :type heights: List[int] 6 | :rtype: int 7 | """ 8 | heights.append(0) 9 | stack = [-1] 10 | ans = 0 11 | for i in range(len(heights)): 12 | while heights[i] < heights[stack[-1]]: 13 | h = heights[stack.pop()] 14 | w = i - stack[-1] - 1 15 | ans = max(ans, h * w) 16 | stack.append(i) 17 | heights.pop() 18 | return ans -------------------------------------------------------------------------------- /code/844#Backspace String Compare.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def backspaceCompare(self, S, T): 3 | """ 4 | :type S: str 5 | :type T: str 6 | :rtype: bool 7 | """ 8 | def convert(string): 9 | stack = [] 10 | for s in string: 11 | if s == '#': 12 | if stack: 13 | stack.pop() 14 | else: 15 | stack.append(s) 16 | return stack 17 | return convert(S) == convert(T) -------------------------------------------------------------------------------- /code/85#Maximal Rectangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximalRectangle(self, matrix): 3 | """ 4 | :type matrix: List[List[str]] 5 | :rtype: int 6 | """ 7 | if not matrix or not matrix[0]: 8 | return 0 9 | n = len(matrix[0]) 10 | height = [0] * (n + 1) 11 | ans = 0 12 | for row in matrix: 13 | for i in range(n): 14 | height[i] = height[i] + 1 if row[i] == '1' else 0 15 | stack = [-1] 16 | for i in range(n + 1): 17 | while height[i] < height[stack[-1]]: 18 | h = height[stack.pop()] 19 | w = i - 1 - stack[-1] 20 | ans = max(ans, h * w) 21 | stack.append(i) 22 | return ans -------------------------------------------------------------------------------- /code/852#Peak Index in a Mountain Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/peak-index-in-a-mountain-array/ 2 | """ 3 | Let's call an array A a mountain if the following properties hold: 4 | 5 | A.length >= 3 6 | There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 7 | Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. 8 | 9 | Example 1: 10 | 11 | Input: [0,1,0] 12 | Output: 1 13 | Example 2: 14 | 15 | Input: [0,2,1,0] 16 | Output: 1 17 | Note: 18 | 19 | 3 <= A.length <= 10000 20 | 0 <= A[i] <= 10^6 21 | A is a mountain, as defined above. 22 | """ 23 | class Solution: 24 | def peakIndexInMountainArray(self, A): 25 | """ 26 | :type A: List[int] 27 | :rtype: int 28 | """ 29 | return A.index(max(A)) -------------------------------------------------------------------------------- /code/859#Buddy Strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/buddy-strings/description/ 2 | class Solution: 3 | # 1 4 | def buddyStrings(self, A, B): 5 | """ 6 | :type A: str 7 | :type B: str 8 | :rtype: bool 9 | """ 10 | if set(A)!=set(B): 11 | return False 12 | count = 0 13 | sum = 0 14 | for i,j in zip(A,B): 15 | if ord(i)-ord(j) != 0: 16 | sum += ord(i)-ord(j) 17 | count+=1 18 | if count>2: 19 | return False 20 | # if count==2: 21 | # return True 22 | # else: 23 | # if len(set(A)) 0 for row in grid for v in row)) -------------------------------------------------------------------------------- /code/888#Fair Candy Swap.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/fair-candy-swap/description/ 2 | class Solution: 3 | # 1 TLE 没通过 4 | def fairCandySwap(self, A, B): 5 | """ 6 | :type A: List[int] 7 | :type B: List[int] 8 | :rtype: List[int] 9 | """ 10 | sum_A = sum(A) 11 | sum_B = sum(B) 12 | diff = sum_A-sum_B 13 | for i in set(A): 14 | if i-diff//2 in set(B): 15 | return [i,i-diff//2] 16 | # 2 用set 17 | def fairCandySwap(self, A, B): 18 | """ 19 | :type A: List[int] 20 | :type B: List[int] 21 | :rtype: List[int] 22 | """ 23 | sb = set(B) 24 | diff = (sum(B) - sum(A)) // 2 25 | for num in A: 26 | if num + diff in sb: 27 | return num, num + diff 28 | -------------------------------------------------------------------------------- /code/890#Find and Replace Pattern.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/find-and-replace-pattern/description/ 2 | 3 | # 这个题目与之前的 205#Isomorphic Strings.py 是同样的道理 4 | # 可以参照这个文档中的函数is_isomorohic 5 | class Solution: 6 | # filter(function, iter)过滤出符合条件的成员,返回list 7 | def findAndReplacePattern(self, words, pattern): 8 | """ 9 | :type words: List[str] 10 | :type pattern: str 11 | :rtype: List[str] 12 | """ 13 | patter_list = [pattern.find(i) for i in pattern] 14 | def is_iso(word): 15 | return [word.find(j) for j in word]==patter_list 16 | return list(filter(is_iso,words)) -------------------------------------------------------------------------------- /code/892#Surface Area of 3D Shapes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def surfaceArea(self, grid: 'List[List[int]]') -> 'int': 3 | n, res = len(grid), 0 4 | for i in range(n): 5 | for j in range(n): 6 | if grid[i][j]: res += 2 + grid[i][j] * 4 7 | if i: res -= min(grid[i][j], grid[i - 1][j]) * 2 8 | if j: res -= min(grid[i][j], grid[i][j - 1]) * 2 9 | return res -------------------------------------------------------------------------------- /code/893#Groups of Special-Equivalent Strings.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/groups-of-special-equivalent-strings/description/ 2 | class Solution(object): 3 | def numSpecialEquivGroups(self, A): 4 | """ 5 | :type A: List[str] 6 | :rtype: int 7 | """ 8 | B = set() 9 | for s in A: 10 | a, b = s[::2], s[1::2] 11 | B.add((''.join(sorted(a)), ''.join(sorted(b)))) 12 | 13 | return len(B) -------------------------------------------------------------------------------- /code/896#Monotonic Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/monotonic-array/description/ 2 | class Solution: 3 | # 1 4 | def isMonotonic(self, A): 5 | is_reverse = False 6 | if A[0]>A[-1]: 7 | is_reverse=True 8 | B = sorted(A,reverse=is_reverse) 9 | return A==B 10 | # 2 11 | def isMonotonic(self, A): 12 | return A==sorted(B,reverse=True if A[0]>A[-1] else False) 13 | # 3 14 | def isMonotonic(self, A): 15 | if not A or len(A) < 2: 16 | return True 17 | if A[0] <= A[-1]: 18 | left = A[0] 19 | for x in A: 20 | if x >= left: 21 | left = x 22 | else: 23 | return False 24 | else: 25 | left = A[0] 26 | for x in A: 27 | if x <= left: 28 | left = x 29 | else: 30 | return False 31 | 32 | return True -------------------------------------------------------------------------------- /code/9#Palindrome Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # function1 3 | def isPalindrome(self, x): 4 | """ 5 | :type x: int 6 | :rtype: bool 7 | """ 8 | str_x = str(x) 9 | left = 0 10 | right = len(str_x)-1 11 | while left < right: 12 | if str_x[left] == str_x[right]: 13 | left+=1 14 | right-=1 15 | else: 16 | return False 17 | if left-right>=0: 18 | return True 19 | return False 20 | # function2 21 | def isPalindrome(self, x): 22 | return str(x) == str(x)[::-1] 23 | -------------------------------------------------------------------------------- /code/905#Sort Array By Parity.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sort-array-by-parity/description/ 2 | class Solution: 3 | # 1 4 | def sortArrayByParity(self, A): 5 | """ 6 | :type A: List[int] 7 | :rtype: List[int] 8 | """ 9 | 让奇数在后,偶数在前 10 | 两点法 11 | p1,p2 = 0,len(A)-1 12 | while p1=2 17 | 18 | def hasGroupsSizeX(self, deck): 19 | return reduce(fractions.gcd, collections.Counter(deck).values()) > 1 20 | 21 | -------------------------------------------------------------------------------- /code/922#Sort Array By Parity II.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/sort-array-by-parity-ii/description/ 2 | class Solution: 3 | def sortArrayByParityII(self, A): 4 | odd_list = [] 5 | even_list = [] 6 | 7 | for i in A: 8 | if i % 2 == 1: 9 | odd_list.append(i) 10 | else: 11 | even_list.append(i) 12 | 13 | result = [None]*(len(odd_list)+len(even_list)) 14 | result[::2] = even_list 15 | result[1::2] = odd_list 16 | return result 17 | 18 | def sortArrayByParityII(self, A): 19 | lastEvenPlace = 0 20 | lastOddPlace = 1 21 | result = A.copy() 22 | for i in A: 23 | if i%2 == 0: 24 | result[lastEvenPlace] = i 25 | lastEvenPlace += 2 26 | else: 27 | result[lastOddPlace] = i 28 | lastOddPlace += 2 29 | return result -------------------------------------------------------------------------------- /code/929#Unique Email Addresses.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/unique-email-addresses/description/ 2 | class Solution: 3 | # 1 4 | def numUniqueEmails1(self, emails): 5 | """ 6 | :type emails: List[str] 7 | :rtype: int 8 | """ 9 | splited_eamils = [email.split('@') for email in emails] 10 | trans_emails = ['@'.join(email[0].split('+')[0].replace('.','')+email[1]) for email in splited_eamils] 11 | return len(set(trans_emails)) 12 | # 2 使用set add 更快一些 13 | def numUniqueEmails2(self, emails): 14 | local_names = [] 15 | for index, address in enumerate(emails): 16 | name = address.split('@') 17 | local_names.append(name[0].replace('.', '').split('+')[0] + '@' + name[1]) 18 | return len(set(local_names)) -------------------------------------------------------------------------------- /code/937#Reorder Log Files.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/reorder-log-files/description/ 2 | class Solution: 3 | def reorderLogFiles(self, logs): 4 | """ 5 | :type logs: List[str] 6 | :rtype: List[str] 7 | """ 8 | digit_logs = [] 9 | letter_logs = [] 10 | for log in logs: 11 | if log[-1].isdigit(): 12 | digit_logs.append(log) 13 | else: 14 | letter_logs.append(log) 15 | letter_logs.sort(key=lambda a:a.split()[1:]) 16 | return letter_logs+digit_logs 17 | 18 | def reorderLogFiles(self, logs): 19 | l = filter(lambda l: l[l.find(" ") + 1].isalpha(), logs) 20 | d = filter(lambda l: l[l.find(" ") + 1].isdigit(), logs) 21 | return sorted(l, key = lambda x: (x[x.find(" "):], x[:x.find(" ")])) + list(d) 22 | -------------------------------------------------------------------------------- /code/941#Valid Mountain Array.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/valid-mountain-array/description/ 2 | class Solution: 3 | def validMountainArray(self, A): 4 | """ 5 | :type A: List[int] 6 | :rtype: bool 7 | """ 8 | i, j, n = 0, len(A) - 1, len(A) 9 | while i + 1 < n and A[i] < A[i + 1]: i += 1 10 | while j > 0 and A[j - 1] > A[j]: j -= 1 11 | return 0 < i == j < n - 1 12 | 13 | def validMountainArray(self, A): 14 | """ 15 | :type A: List[int] 16 | :rtype: bool 17 | """ 18 | if len(A) < 3: return False 19 | if A[0] >= A[1]: return False 20 | climb = True 21 | for a,b in zip(A,A[1:]): 22 | if climb: 23 | if ab: climb = False; continue 25 | return False 26 | else: 27 | if a>b: continue 28 | return False 29 | return not climb -------------------------------------------------------------------------------- /code/976#Largest Perimeter Triangle.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/largest-perimeter-triangle/ 2 | """ 3 | Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths. 4 | 5 | If it is impossible to form any triangle of non-zero area, return 0. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: [2,1,2] 12 | Output: 5 13 | Example 2: 14 | 15 | Input: [1,2,1] 16 | Output: 0 17 | Example 3: 18 | 19 | Input: [3,2,3,4] 20 | Output: 10 21 | Example 4: 22 | 23 | Input: [3,6,2,3] 24 | Output: 8 25 | 26 | 27 | Note: 28 | 29 | 3 <= A.length <= 10000 30 | 1 <= A[i] <= 10^6 31 | Accepted 32 | 5,145 33 | Submissions 34 | 9,204 35 | """ 36 | import heapq 37 | class Solution: 38 | def largestPerimeter(self, A): 39 | """ 40 | :type A: List[int] 41 | :rtype: int 42 | """ 43 | A = sorted(A)[::-1] 44 | for i in range(len(A) - 2): 45 | if A[i] < A[i + 1] + A[i + 2]: 46 | return A[i] + A[i + 1] + A[i + 2] 47 | return 0 -------------------------------------------------------------------------------- /code/989#Add to Array-Form of Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addToArrayForm(self, A: 'List[int]', K: 'int') -> 'List[int]': 3 | b = ''.join(list(map(str,A))) 4 | c = list(str(int(b) + K)) 5 | return list(map(int,c)) -------------------------------------------------------------------------------- /code/994#Rotting Oranges.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def orangesRotting(self, grid): 3 | n,m = len(grid), len(grid[0]) 4 | Q = collections.deque([]) 5 | cnt = 0 6 | for i in range(n): 7 | for j in range(m): 8 | if grid[i][j] == 1: cnt += 1 9 | if grid[i][j] == 2: Q.append((i,j)) 10 | res = 0 11 | while Q: 12 | for _ in range(len(Q)): 13 | i,j = Q.popleft() 14 | for x, y in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]: 15 | if 0<=x List[int]: 11 | """ 12 | 使用新的数组存储 13 | 时间 O(N) 14 | 空间 O(N) 15 | """ 16 | left = 0 17 | right = len(nums) - 1 18 | cur = len(nums) - 1 19 | result = [0] * len(nums) 20 | while left <= right: 21 | left_square = nums[left] * nums[left] 22 | right_square = nums[right] * nums[right] 23 | if left_square <= right_square: 24 | result[cur] = right_square 25 | right -= 1 26 | else: 27 | result[cur] = left_square 28 | left += 1 29 | cur -= 1 30 | return result 31 | 32 | -------------------------------------------------------------------------------- /code_thinking/data_struct.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2023/8/17 22:14 3 | # @Author : eachenkuang 4 | # @Email : eachen.kuang@foxmail.com 5 | # @File : data_struct.py 6 | from typing import Optional 7 | 8 | 9 | class ListNode: 10 | """ListNode""" 11 | def __init__(self, x: int = 0): 12 | self.val = x 13 | self.next = None 14 | 15 | 16 | class TreeNode: 17 | """TreeNode""" 18 | def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None): 19 | self.val = val 20 | self.left = left 21 | self.right = right 22 | -------------------------------------------------------------------------------- /code_thinking/hash_table/1_two_sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2024/1/17 23:01 3 | # @Author : eachenkuang 4 | # @Email : eachen.kuang@foxmail.com 5 | # @File : 1_two_sum.py 6 | from typing import List 7 | 8 | 9 | class Solution: 10 | def twoSum(self, nums: List[int], target: int) -> List[int]: 11 | """暴力法""" 12 | for i in range(len(nums)): 13 | for j in range(i+1, len(nums)): 14 | if nums[i] + nums[j] == target: 15 | return [i,j] 16 | 17 | def twoSum3(self, nums: List[int], target: int) -> List[int]: 18 | """使用字典法""" 19 | pair = {} 20 | for i in range(len(nums)): 21 | if nums[i] in pair.keys(): 22 | return [pair.get(nums[i]), i] 23 | else: 24 | pair[target-nums[i]] = i 25 | return [] 26 | 27 | 28 | -------------------------------------------------------------------------------- /code_thinking/string/459_repeated_substring_pattern.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2024/1/21 17:21 3 | # @Author : eachenkuang 4 | # @Email : eachen.kuang@foxmail.com 5 | # @File : 459_repeated_substring_pattern.py 6 | # https://leetcode.cn/problems/repeated-substring-pattern/submissions/497218492/ 7 | class Solution: 8 | def repeatedSubstringPattern(self, s: str) -> bool: 9 | """如果符合要求""" 10 | new_str = s + s 11 | return s in new_str[1:-1] 12 | 13 | def repeatedSubstringPattern2(self, s: str) -> bool: 14 | """使用find""" 15 | s1 = s + s 16 | return s1[1:len(s1) - 1].find(s) >= 0 17 | 18 | def repeatedSubstringPattern3(self, s: str) -> bool: 19 | pass 20 | --------------------------------------------------------------------------------