├── .gitignore ├── Interview ├── Easy Collection │ ├── Array │ │ ├── question_1.py │ │ ├── question_10.py │ │ ├── question_11.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ ├── question_4.py │ │ ├── question_5.py │ │ ├── question_6.py │ │ ├── question_7.py │ │ ├── question_8.py │ │ └── question_9.py │ ├── Design │ │ ├── question_1.py │ │ └── question_2.py │ ├── Dynamic Programming │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ └── question_4.py │ ├── Linked List │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ ├── question_4.py │ │ ├── question_5.py │ │ └── question_6.py │ ├── Math │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ └── question_4.py │ ├── Others │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ ├── question_4.py │ │ ├── question_5.py │ │ └── question_6.py │ ├── Sorting and Searching │ │ ├── question_1.py │ │ └── question_2.py │ ├── Strings │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ ├── question_4.py │ │ ├── question_5.py │ │ ├── question_6.py │ │ ├── question_7.py │ │ ├── question_8.py │ │ └── question_9.py │ └── Trees │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ ├── question_4.py │ │ └── question_5.py ├── Hard Collection │ ├── Array and Strings │ │ └── question_8.py │ └── Linked List │ │ └── question_2.py └── Medium Collection │ ├── Array and Strings │ └── question_3.py │ ├── Linked List │ └── question_1.py │ ├── Math │ ├── question_4.py │ └── question_5.py │ ├── Others │ ├── question_1.py │ └── question_3.py │ ├── Sorting and Searching │ ├── question_1.py │ ├── question_2.py │ ├── question_3.py │ ├── question_4.py │ ├── question_5.py │ ├── question_7.py │ └── question_8.py │ └── Trees and Graphs │ └── question_1.py ├── LCP ├── 1.Guess Numbers │ └── method_1.py ├── 33.Store Water │ └── method_1.py ├── 6.Take Coins │ └── method_1.py └── 77.rune reserve │ └── method_1.py ├── LCR └── 36.Evaluate the inverse Polish expression │ └── method_1.py ├── Learn ├── Array and String │ ├── Conclusion │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ ├── question_4.py │ │ ├── question_5.py │ │ └── question_6.py │ ├── Introduction to 2D Array │ │ └── question_4.py │ ├── Introduction to Array │ │ ├── question_1.py │ │ ├── question_2.py │ │ └── question_3.py │ ├── Introduction to String │ │ ├── question_1.py │ │ ├── question_2.py │ │ └── question_3.py │ └── Two-Pointer Technique │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ ├── question_4.py │ │ └── question_5.py ├── Binary Tree │ ├── Binary Tree Traversal │ │ ├── question_1.py │ │ ├── question_2.py │ │ ├── question_3.py │ │ └── question_4.py │ └── Recursion │ │ ├── question_1.py │ │ └── question_2.py ├── Linked List │ ├── Classic Problems │ │ ├── question_1.py │ │ └── question_5.py │ ├── Conclusion │ │ ├── question_1.py │ │ └── question_2.py │ ├── Singly Linked List │ │ └── question.py │ └── Two Pointer Technique │ │ ├── question_1.py │ │ └── question_4.py ├── N-ary Tree │ ├── Recursion │ │ └── question.py │ └── Traversal │ │ ├── question_1.py │ │ ├── question_2.py │ │ └── question_3.py └── Queue & Stack │ ├── Conclusion │ ├── question_1.py │ └── question_2.py │ ├── Queue │ └── question_1.py │ ├── Stack and DFS │ └── question_4.py │ └── Stack │ ├── question_1.py │ └── question_2.py ├── QuestionBank ├── 1.Two Sun │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 100.Same Tree │ ├── method_1.py │ └── method_2.py ├── 1002.Find Common Characters │ └── method_1.py ├── 1006.Clumsy Factorial │ └── method_1.py ├── 101.Symmetric Tree │ └── method_1.py ├── 1012.Complement of Base 10 Integer │ └── method_1.py ├── 102.Binary Tree Level Order Traversal │ └── method_1.py ├── 1021.Remove Outermost Parentheses │ └── method_1.py ├── 103.Binary Tree Zigzag Level Order Traversal │ └── method_1.py ├── 1038.Binary Search Tree to Greater Sum Tree │ └── method_1.py ├── 104.Maximum Depth of Binary Tree │ └── method_1.py ├── 1046.Last Stone Weight │ └── method_1.py ├── 1051.Height Checker │ └── method_1.py ├── 107.Binary Tree Level Order Traversal II │ └── method_1.py ├── 108.Convert Sorted Array to Binary Search Tree │ ├── method_1.py │ └── method_2.py ├── 11.Container With Most Water │ └── method_1.py ├── 110.Balanced Binary Tree │ └── method_1.py ├── 1108.Defanging an IP Address │ └── method_1.py ├── 111.Minimum Depth of Binary Tree │ └── method_1.py ├── 112.Path Sum │ └── method_1.py ├── 1128.Number of Equivalent Domino Pairs │ ├── method_1.py │ └── method_2.py ├── 113.Path Sum II │ └── method_1.py ├── 1137.N-th Tribonacci Number │ └── method_1.py ├── 114.Flatten Binary Tree to Linked List │ ├── method_1.py │ └── method_2.py ├── 1154.Day of the Year │ └── method_1.py ├── 116.Populating Next Right Pointers in Each Node │ └── method_1.py ├── 1161.Maximum Level Sum of a Binary Tree │ └── method_1.py ├── 117.Populating Next Right Pointers in Each Node II │ └── method_1.py ├── 1175.Prime Arrangements │ └── method_1.py ├── 118.Pascal's Triangle │ └── method_1.py ├── 1185.Day of the Week │ └── method_1.py ├── 1189.Maximum Number of Balloons │ └── method_1.py ├── 119..Pascal's Triangle II │ └── method_1.py ├── 120.Triangle │ └── method_1.py ├── 1207.Unique Number of Occurrences │ └── method_1.py ├── 121.Best Time to Buy and Sell Stock │ └── method_1.py ├── 1213.Intersection of Three Sorted Arrays │ └── method_1.py ├── 1217.Minimum Cost to Move Chips to The Same Position │ └── method_1.py ├── 1218.Longest Arithmetic Subsequence of Given Difference │ └── method_1.py ├── 122.Best Time to Buy and Sell Stock II │ └── method_1.py ├── 1232.Check If It Is a Straight Line │ └── method_1.py ├── 1249.Minimum Remove to Make Valid Parentheses │ └── method_1.py ├── 125.Valid Palindrome │ ├── method_1.py │ └── method_2.py ├── 1266.Minimum Time Visiting All Points │ └── method_1.py ├── 1281.Subtract the Product and Sum of Digits of an Integer │ └── method_1.py ├── 129.Sum Root to Leaf Numbers │ └── method_1.py ├── 1295.Find Numbers with Even Number of Digits │ └── method_1.py ├── 13.Roman to Integer │ └── method_1.py ├── 131.Palindrome Partitioning │ └── method_1.py ├── 1313.Decompress Run-Length Encoded List │ └── method_1.py ├── 1342.Number of Steps to Reduce a Number to Zero │ └── method_1.py ├── 1356.Sort Integers by The Number of 1 Bits │ └── method_1.py ├── 136.Single Number │ ├── mehtod_1.py │ └── mehtod_2.py ├── 1365.How Many Numbers Are Smaller Than the Current Number │ └── method_1.py ├── 137.Single Number II │ ├── method_1.py │ └── method_2.py ├── 1389.Create Target Array in the Given Order │ └── method_1.py ├── 139.Word Break │ └── method_1.py ├── 14.Longest Common Prefix │ └── method_1.py ├── 140.Word Break II │ └── method_1.py ├── 1403.Minimum Subsequence in Non-Increasing Order │ └── method_1.py ├── 141.Linked List Cycle │ ├── method_1.py │ └── method_2.py ├── 142.Linked List Cycle II │ └── method_1.py ├── 1431.Kids With the Greatest Number of Candies │ └── method_1.py ├── 144.Binary Tree Preorder Traversal │ └── method_1.py ├── 145.Binary Tree Postorder Traversal │ └── method_1.py ├── 146.LRU Cache │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 147.Insertion Sort List │ └── method_1.py ├── 1470.Shuffle the Array │ └── method_1.py ├── 148.Sort List │ └── method_1.py ├── 1480.Running Sum of 1d Array │ └── method_1.py ├── 1486.XOR Operation in an Array │ └── method_1.py ├── 15.3Sum │ ├── method_1.py │ └── method_2.py ├── 151.Reverse Words in a String │ └── method_1.py ├── 1512.Number of Good Pairs │ └── method_1.py ├── 1518.Water Bottles │ └── method_1.py ├── 152.Maximum Product Subarray │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 153.Find Minimum in Rotated Sorted Array │ └── method_1.py ├── 155.Min Stack │ ├── method_1.py │ └── method_2.py ├── 1556.Thousand Separator │ └── method_1.py ├── 1572.Matrix Diagonal Sum │ └── method_1.py ├── 1598.Crawler Log Folder │ └── method_1.py ├── 160.Intersection of Two Linked Lists │ └── method_1.py ├── 1603.Design Parking System │ └── method_1.py ├── 1614.Maximum Nesting Depth of the Parentheses │ └── method_1.py ├── 162.Find Peak Element │ └── method_1.py ├── 164.Maximum Gap │ └── method_1.py ├── 1662.Check If Two String Arrays are Equivalent │ └── method_1.py ├── 167.Two Sum II - Input array is sorted │ └── method_1.py ├── 1672.Richest Customer Wealth │ └── method_1.py ├── 168.Excel Sheet Column Title │ └── method_1.py ├── 169.Majority Element │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 171.Excel Sheet Column Number │ └── method_1.py ├── 172.Factorial Trailing Zeroes │ └── method_1.py ├── 1721.Swapping Nodes in a Linked List │ └── method_1.py ├── 1748.Sum of Unique Elements │ └── method_1.py ├── 1784.Check if Binary String Has at Most One Segment of Ones │ └── method_1.py ├── 189.Rotate Array │ ├── method_1.py │ └── method_2.py ├── 19.Remove Nth Node From End of List │ └── method_1.py ├── 190.Reverse Bits │ └── method_1.py ├── 191.Number of 1 Bits │ └── method_1.py ├── 198.House Robber │ └── method_1.py ├── 2.Add Two Numbers │ └── method_1.py ├── 20.Valid Parentheses │ └── method_1.py ├── 202.Happy Number │ └── method_1.py ├── 203.Remove Linked List Elements │ └── method_1.py ├── 2032.Two Out of Three │ └── method_1.py ├── 204.Count Primes │ └── method_1.py ├── 205.Isomorphic Strings │ └── method_1.py ├── 206.Reverse Linked List │ ├── method_1.py │ └── method_2.py ├── 208.Implement Trie (Prefix Tree) │ └── method_1.py ├── 21.Merge Two Sorted Lists │ └── method_1.py ├── 215.Kth Largest Element in an Array │ └── method_1.py ├── 216.Combination Sum III │ └── method_1.py ├── 217.Contains Duplicate │ └── method_1.py ├── 219.Contains Duplicate II │ └── method_1.py ├── 22.Generate Parentheses │ └── method_1.py ├── 221.Maximal Square │ └── method_1.py ├── 223.Rectangle Area │ └── method_1.py ├── 225.Implement Stack using Queues │ └── method_1.py ├── 226.Invert Binary Tree │ └── method_1.py ├── 2287.Rearrange Characters to Make Target String │ └── method_1.py ├── 230.Kth Smallest Element in a BST │ └── method_1.py ├── 231.Power of Two │ └── method_1.py ├── 232.Implement Queue using Stacks │ ├── method_1.py │ └── method_2.py ├── 234.Palindrome Linked List │ └── mehtod_1.py ├── 235.Lowest Common Ancestor of a Binary Search Tree │ └── method_1.py ├── 236.Lowest Common Ancestor of a Binary Tree │ └── method_1.py ├── 237.Delete Node in a Linked List │ └── method_1.py ├── 238.Product of Array Except Self │ └── method_1.py ├── 240.Search a 2D Matrix II │ └── method_1.py ├── 242.Valid Anagram │ └── method_1.py ├── 2481.Minimum Cuts to Divide a Circle │ └── method_1.py ├── 25.Reverse Nodes in k-Group │ └── method_1.py ├── 257.Binary Tree Paths │ └── method_1.py ├── 258.Add Digits │ └── method_1.py ├── 26.Remove Duplicates from Sorted Array │ ├── method_1.py │ └── method_2.py ├── 260.Single Number III │ └── method_1.py ├── 268.Missing Number │ ├── method_1.py │ └── method_2.py ├── 27.Remove Element │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 278.First Bad Version │ └── method_1.py ├── 28.Implement strStr() │ └── method_1.py ├── 283.Move Zeroes │ ├── method_1.py │ └── method_2.py ├── 284.Peeking Iterator │ ├── method_1.py │ └── method_2.py ├── 287.Find the Duplicate Number │ ├── method_1.py │ └── method_2.py ├── 29.Divide Two Integers │ └── method_1.py ├── 290.Word Pattern │ ├── method_1.py │ └── method_2.py ├── 295.Find Median from Data Stream │ └── method_1.py ├── 299.Bulls and Cows │ └── method_1.py ├── 3.Longest Substring Without Repeating Characters │ └── method_1.py ├── 30.Substring with Concatenation of All Words │ └── method_1.py ├── 303.Range Sum Query - Immutable │ ├── method_1.py │ └── method_2.py ├── 322.Coin Change │ └── method_1.py ├── 326.Power of Three │ └── method_1.py ├── 328.Odd Even Linked List │ └── method_1.py ├── 33.Search in Rotated Sorted Array │ └── method_1.py ├── 338.Counting Bits │ └── method_1.py ├── 34.Find First and Last Position of Element in Sorted Array │ └── method_1.py ├── 342.Power of Four │ ├── method_1.py │ └── method_2.py ├── 344.Reverse String │ └── method_1.py ├── 345.Reverse Vowels of a String │ └── method_1.py ├── 347.Top K Frequent Elements │ ├── method_1.py │ └── method_2.py ├── 349.Intersection of Two Arrays │ └── method_1.py ├── 35.Search Insert Position │ ├── method_1.py │ └── method_2.py ├── 350.Intersection of Two Arrays II │ ├── method_1.py │ └── method_2.py ├── 36.Valid Sudoku │ └── method_1.py ├── 367.Valid Perfect Square │ └── method_1.py ├── 371.Sum of Two Integers │ └── method_1.py ├── 374.Guess Number Higher or Lower │ └── method_1.py ├── 38.Count and Say │ └── method_1.py ├── 382.Linked List Random Node │ ├── method_1.py │ └── method_2.py ├── 384.Shuffle an Array │ └── method_1.py ├── 385.Mini Parser │ └── method_1.py ├── 387.First Unique Character in a String │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 389.Find the Difference │ └── method_1.py ├── 39.Combination Sum │ └── method_1.py ├── 392.Is Subsequence │ └── method_1.py ├── 397.Integer Replacement │ ├── method_1.py │ └── method_2.py ├── 4.Median of Two Sorted Arrays │ ├── method_1.py │ └── method_2.py ├── 40.Combination Sum II │ └── method_1.py ├── 404.Sum of Left Leaves │ └── method_1.py ├── 405.Convert a Number to Hexadecimal │ └── method_1.py ├── 412.Fizz Buzz │ └── method_1.py ├── 414.Third Maximum Number │ └── method_1.py ├── 415.Add Strings │ └── method_1.py ├── 429.N-ary Tree Level Order Traversal │ └── method_1.py ├── 43.Multiply Strings │ └── method_1.py ├── 430.Flatten a Multilevel Doubly Linked List │ └── method_1.py ├── 434.Number of Segments in a String │ ├── method_1.py │ └── method_2.py ├── 442.Find All Duplicates in an Array │ ├── method_1.py │ └── method_2.py ├── 445.Add Two Numbers II │ └── method_1.py ├── 448.Find All Numbers Disappeared in an Array │ └── method_1.py ├── 451.Sort Characters By Frequency │ └── method_1.py ├── 454.4Sum II │ └── method_1.py ├── 459.Repeated Substring Pattern │ └── method_1.py ├── 46.Permutations │ └── method_1.py ├── 461.Hamming Distance │ └── method_1.py ├── 47.Permutations II │ └── method_1.py ├── 476.Number Complement │ └── method_1.py ├── 48.Rotate Image │ └── method_1.py ├── 485.Max Consecutive Ones │ └── method_1.py ├── 486.Predict the Winner │ └── method_1.py ├── 49.Group Anagrams │ └── method_1.py ├── 495.Teemo Attacking │ └── method_1.py ├── 5.Longest Palindromic Substring │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 50.Pow(x, n) │ ├── method_1.py │ └── method_2.py ├── 501.Find Mode in Binary Search Tree │ └── method_1.py ├── 509.Fibonacci Number │ ├── method_1.py │ └── method_2.py ├── 515.Find Largest Value in Each Tree Row │ └── method_1.py ├── 520.Detect Capital │ └── method_1.py ├── 53.Maximum Subarray │ └── method_1.py ├── 530.Minimum Absolute Difference in BST │ └── method_1.py ├── 537.Complex Number Multiplication │ └── method_1.py ├── 538.Convert BST to Greater Tree │ └── method_1.py ├── 551.Student Attendance Record I │ ├── method_1.py │ └── method_2.py ├── 557.Reverse Words in a String III │ └── method_1.py ├── 559.Maximum Depth of N-ary Tree │ └── method_1.py ├── 56.Merge Intervals │ ├── method_1.py │ └── method_2.py ├── 560.Subarray Sum Equals K │ └── method_1.py ├── 561.Array Partition I │ └── method_1.py ├── 566.Reshape the Matrix │ └── method_1.py ├── 567.Permutation in String │ └── method_1.py ├── 572.Subtree of Another Tree │ └── method_1.py ├── 5738.Sum of Digits in Base K │ └── method_1.py ├── 575.Distribute Candies │ └── method_1.py ├── 58.Length of Last Word │ └── method_1.py ├── 589.N-ary Tree Preorder Traversal │ └── method_1.py ├── 590.N-ary Tree Postorder Traversal │ └── method_1.py ├── 6.leetcode.com │ └── method_1.py ├── 61.Rotate List │ └── method_1.py ├── 617.Merge Two Binary Trees │ └── method_1.py ├── 622.Design Circular Queue │ └── method_1.py ├── 628.Maximum Product of Three Numbers │ └── method_1.py ├── 633.Sum of Square Numbers │ └── method_1.py ├── 637.Average of Levels in Binary Tree │ └── method_1.py ├── 643.Maximum Average Subarray I │ └── method_1.py ├── 648.Replace Words │ └── method_1.py ├── 657.Robot Return to Origin │ └── method_1.py ├── 658.Find K Closest Elements │ ├── method_1.py │ └── method_2.py ├── 66.Plus One │ ├── method_1.py │ └── method_2.py ├── 665.Non-decreasing Array │ └── method_1.py ├── 67.Add Binary │ └── method_1.py ├── 670.Maximum Swap │ └── method_1.py ├── 674.Longest Continuous Increasing Subsequence │ └── method_1.py ├── 677.Map Sum Pairs │ └── method_1.py ├── 680.Valid Palindrome II │ └── method_1.py ├── 682.Baseball Game │ └── method_1.py ├── 69.Sqrt(x) │ └── method_1.py ├── 693.Binary Number with Alternating Bits │ └── method_1.py ├── 7.Reverse Integer │ ├── method_1.py │ ├── method_2.py │ ├── method_3.py │ └── method_4.py ├── 70.Climbing Stairs │ └── method_1.py ├── 700.Search in a Binary Search Tree │ └── method_1.py ├── 704.Binary Search │ ├── method_1.py │ └── method_2.py ├── 705.Design HashSet │ └── method_1.py ├── 706.Design HashMap │ └── method_1.py ├── 707.Design Linked List │ └── method_1.py ├── 709.To Lower Case │ └── method_1.py ├── 71.Simplify Path │ └── method_1.py ├── 724.Find Pivot Index │ └── method-1.py ├── 728.Self Dividing Numbers │ └── method_1.py ├── 738.Monotone Increasing Digits │ └── method_1.py ├── 739.Daily Temperatures │ └── method_1.py ├── 744.Find Smallest Letter Greater Than Target │ └── method_1.py ├── 747.Largest Number At Least Twice of Others │ └── method_1.py ├── 75.Sort Colors │ ├── method_1.py │ └── method_2.py ├── 762.Prime Number of Set Bits in Binary Representation │ ├── method_1.py │ └── method_2.py ├── 766.Toeplitz Matrix │ └── method_1.py ├── 77.Combinations │ └── method_1.py ├── 771.Jewels and Stones │ └── method_1.py ├── 78.Subsets │ └── method_1.py ├── 781.Rabbits in Forest │ └── method_1.py ├── 783.Minimum Distance Between BST Nodes │ └── method_1.py ├── 79.Word Search │ └── method_1.py ├── 796.Rotate String │ └── method_1.py ├── 8.String to Integer (atoi) │ └── method_1.py ├── 804.Unique Morse Code Words │ └── method_1.py ├── 807.Max Increase to Keep City Skyline │ └── method_1.py ├── 811.Subdomain Visit Count │ └── method_1.py ├── 82.Remove Duplicates from Sorted List II │ ├── method_1.py │ └── method_2.py ├── 821.Shortest Distance to a Character │ └── method_1.py ├── 83.Remove Duplicates from Sorted List │ └── method_1.py ├── 830.Positions of Large Groups │ └── method_1.py ├── 832.Flipping an Image │ └── method_1.py ├── 844.Backspace String Compare │ └── method_1.py ├── 852.Peak Index in a Mountain Array │ └── method_1.py ├── 860.Lemonade Change │ └── method_1.py ├── 867.Transpose Matrix │ ├── method_1.py │ ├── method_2.py │ └── method_3.py ├── 868.Binary Gap │ └── method_1.py ├── 875.Koko Eating Bananas │ └── method_1.py ├── 876.Middle of the Linked List │ └── method_1.py ├── 88.Merge Sorted Array │ ├── method_1.py │ └── method_2.py ├── 884.Uncommon Words from Two Sentences │ └── method_1.py ├── 896.Monotonic Array │ └── method_1.py ├── 897.Increasing Order Search Tree │ └── method_1.py ├── 9.Palindrome Number │ ├── method_1.py │ └── method_2.py ├── 905.Sort Array By Parity │ └── method_1.py ├── 921.Minimum Add to Make Parentheses Valid │ └── method_1.py ├── 922.Sort Array By Parity II │ └── method_1.py ├── 925.Long Pressed Name │ └── method_1.py ├── 93.Restore IP Addresses │ └── method_1.py ├── 933.Number of Recent Calls │ └── method_1.py ├── 938.Range Sum of BST │ └── method_1.py ├── 94.Binary Tree Inorder Traversal │ ├── method_1.py │ └── method_3.py ├── 941.Valid Mountain Array │ └── method_1.py ├── 942.DI String Match │ └── method_1.py ├── 961.N-Repeated Element in Size 2N Array │ └── method_1.py ├── 965.Univalued Binary Tree │ └── method_1.py ├── 970.Powerful Integers │ └── method_1.py ├── 973.K Closest Points to Origin │ └── method_1.py ├── 974.Subarray Sums Divisible by K │ └── method_1.py ├── 976.Largest Perimeter Triangle │ └── method_1.py ├── 977.Squares of a Sorted Array │ └── method_1.py ├── 98.Validate Binary Search Tree │ └── method_1.py ├── 985.Sum of Even Numbers After Queries │ └── method_1.py ├── 989.Add to Array-Form of Integer │ └── method_1.py └── 993.Cousins in Binary Tree │ └── method_1.py ├── README.md └── interviewQuestion ├── 01.01.Is Unique LCCI └── method_1.py ├── 01.05.One Away LCCI └── method_1.py ├── 02.05.Sum Lists LCCI └── method_1.py ├── 16.01.Swap Numbers LCCI └── method_1.py ├── 16.02.Words Frequency LCCI └── method_1.py ├── 17.04.Missing Number LCCI └── method_1.py ├── 17.10.Find Majority Element LCCI └── method_1.py ├── 17.11.Find Closest LCCI └── method_1.py ├── 17.14.Smallest K LCCI └── method_1.py ├── 17.22.Word Transformer LCCI └── method_1.py ├── 剑指 Offer 64.求1+2+…+n └── method_1.py └── 剑指 Offer II 074.合并区间 └── method_1.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .vscode -------------------------------------------------------------------------------- /Interview/Easy Collection/Array/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/10 下午10:22 3 | # @Author : cancan 4 | # @File : question_2.py 5 | # @Function : 买卖股票的最佳时机 6 | 7 | """ 8 | Question: 9 | 假设有一个数组,它的第 i 个元素是一个给定的股票在第 i 天的价格。 10 | 设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。 11 | 然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。 12 | """ 13 | 14 | 15 | class Solution: 16 | def maxProfit(self, prices): 17 | """ 18 | :type prices: List[int] 19 | :rtype: int 20 | """ 21 | l = len(prices) 22 | t = 0 23 | for i, v in enumerate(prices): 24 | next = i + 1 25 | if next < l and prices[next] > prices[i]: 26 | t += prices[next] - prices[i] 27 | 28 | return t 29 | 30 | 31 | if __name__ == '__main__': 32 | t = Solution() 33 | a = [6, 1, 3, 2, 4, 7] 34 | r = t.maxProfit(a) 35 | print(r) 36 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Array/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/10 下午10:22 3 | # @Author : cancan 4 | # @File : question_2.py 5 | # @Function : 存在重复 6 | 7 | """ 8 | Question: 9 | 给定一个整数数组,判断是否存在重复元素。 10 | 如果任何值在数组中出现至少两次,函数应该返回 true。如果每个元素都不相同,则返回 false。 11 | """ 12 | 13 | 14 | class Solution: 15 | def containsDuplicate(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: bool 19 | """ 20 | return len(set(nums)) != len(nums) 21 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Array/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/4/17 9:42 4 | # @Author : cancan 5 | # @File : question_5.py 6 | # @Function : 只出现一次的数字 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组,除了某个元素外其余元素均出现两次。请找出这个只出现一次的元素。 11 | 12 | Note: 13 | 你的算法应该是一个线性时间复杂度。 你可以不用额外空间来实现它吗? 14 | """ 15 | 16 | class Solution: 17 | def singleNumber(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | r = 0 23 | for i in nums: 24 | r ^= i 25 | 26 | return r 27 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Dynamic Programming/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/27 下午12:57 3 | # @Author : cancan 4 | # @File : question_1.py 5 | # @Function : 爬楼梯 6 | 7 | """ 8 | Question: 9 | 假设你正在爬楼梯。需要 n 步你才能到达楼顶。 10 | 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 11 | 12 | Note: 13 | 给定 n 是一个正整数。 14 | 15 | Example 1: 16 | 输入: 2 17 | 输出: 2 18 | 解释: 有两种方法可以爬到楼顶。 19 | 1. 1 步 + 1 步 20 | 2. 2 步 21 | 22 | Example 2: 23 | 输入: 3 24 | 输出: 3 25 | 解释: 有三种方法可以爬到楼顶。 26 | 1. 1 步 + 1 步 + 1 步 27 | 2. 1 步 + 2 步 28 | 3. 2 步 + 1 步 29 | """ 30 | 31 | 32 | class Solution: 33 | def climbStairs(self, n): 34 | """ 35 | :type n: int 36 | :rtype: int 37 | """ 38 | 39 | a = b = 1 40 | for _ in range(n - 1): 41 | a, b = b, a + b 42 | 43 | return b 44 | 45 | 46 | if __name__ == "__main__": 47 | a = Solution() 48 | n = 6 49 | print(a.climbStairs(n)) 50 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Dynamic Programming/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/27 下午2:50 3 | # @Author : cancan 4 | # @File : question_3.py 5 | # @Function : 最大子序和 6 | 7 | """ 8 | Question: 9 | 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 10 | 11 | Example: 12 | 输入: [-2,1,-3,4,-1,2,1,-5,4], 13 | 输出: 6 14 | 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 15 | 16 | Follow up: 17 | 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 18 | """ 19 | 20 | 21 | class Solution: 22 | def maxSubArray(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: int 26 | """ 27 | r = nums[0] 28 | s = 0 29 | for _ in nums: 30 | s = max(s + _, _) 31 | r = max(r, s) 32 | return r 33 | 34 | 35 | if __name__ == "__main__": 36 | a = Solution() 37 | n = [1, 2, -1] 38 | print(a.maxSubArray(n)) -------------------------------------------------------------------------------- /Interview/Easy Collection/Linked List/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午1:30 3 | # @Author : cancan 4 | # @File : question_1.py 5 | # @Function : 删除链表的结点 6 | 7 | """ 8 | Question: 9 | 请编写一个函数,使其可以删除某个链表中给定的(非末尾的)节点,您将只被给予要求被删除的节点。 10 | 比如:假设该链表为 1 -> 2 -> 3 -> 4 ,给定您的为该链表中值为 3 的第三个节点, 11 | 那么在调用了您的函数之后,该链表则应变成 1 -> 2 -> 4 。 12 | """ 13 | 14 | 15 | # Definition for singly-linked list. 16 | # class ListNode(object): 17 | # def __init__(self, x): 18 | # self.val = x 19 | # self.next = None 20 | 21 | 22 | class Solution(object): 23 | def deleteNode(self, node): 24 | """ 25 | :type node: ListNode 26 | :rtype: void Do not return anything, modify node in-place instead. 27 | """ 28 | node.val = node.next.val 29 | node.next = node.next.next -------------------------------------------------------------------------------- /Interview/Easy Collection/Linked List/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午3:06 3 | # @Author : cancan 4 | # @File : question_3.py 5 | # @Function : 反转链表 6 | 7 | """ 8 | Question: 9 | 反转一个单链表。 10 | 11 | Example: 12 | 输入: 1->2->3->4->5->NULL 13 | 输出: 5->4->3->2->1->NULL 14 | 15 | Follow up: 16 | 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? 17 | """ 18 | 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode(object): 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.next = None 25 | 26 | class Solution(object): 27 | def reverseList(self, head): 28 | """ 29 | :type head: ListNode 30 | :rtype: ListNode 31 | """ 32 | if not head or not head.next: 33 | return head 34 | 35 | def f(node, pre): 36 | t = node.next 37 | node.next = pre 38 | if not t: 39 | return node 40 | else: 41 | return f(t, node) 42 | 43 | return f(head, None) 44 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Linked List/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午7:28 3 | # @Author : cancan 4 | # @File : question_5.py 5 | # @Function : 回文链表 6 | 7 | """ 8 | Question: 9 | 请检查一个链表是否为回文链表。 10 | 11 | Follow up: 12 | 你能在 O(n) 的时间和 O(1) 的额外空间中做到吗 13 | """ 14 | 15 | 16 | # Definition for singly-linked list. 17 | # class ListNode(object): 18 | # def __init__(self, x): 19 | # self.val = x 20 | # self.next = None 21 | 22 | class Solution(object): 23 | def isPalindrome(self, head): 24 | """ 25 | :type head: ListNode 26 | :rtype: bool 27 | """ 28 | if not head: 29 | return True 30 | t = [head.val] 31 | n = head.next 32 | while n: 33 | t.append(n.val) 34 | n = n.next 35 | 36 | l = len(t) 37 | i = l // 2 38 | if l % 2 == 0: 39 | return t[:i] == t[i:][::-1] 40 | else: 41 | return t[:i] == t[i + 1:][::-1] 42 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Math/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/25 15:19 4 | # @Author : cancan 5 | # @File : question_2.py 6 | # @Function : 计数质数 7 | 8 | """ 9 | Question: 10 | 统计所有小于非负整数 n 的质数的数量。 11 | 12 | Example: 13 | 输入: 10 14 | 输出: 4 15 | 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 16 | """ 17 | 18 | 19 | class Solution: 20 | def countPrimes(self, n): 21 | """ 22 | :type n: int 23 | :rtype: int 24 | """ 25 | if n < 3: 26 | return 0 27 | 28 | if n < 3: 29 | return 0 30 | 31 | digits = [1] * n 32 | digits[0] = digits[1] = 0 33 | 34 | for i in range(2, int(n ** 0.5) + 1): 35 | if digits[i] == 1: 36 | for j in range(i + i, n, i): 37 | digits[j] = 0 38 | 39 | return sum(digits) 40 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Math/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/15 下午1:44 3 | # @Author : cancan 4 | # @File : question_3.py 5 | # @Function : 3的幂 6 | 7 | """ 8 | Question: 9 | 给定一个整数,写一个函数来判断它是否是 3 的幂次方。 10 | 11 | Example 1: 12 | 输入: 27 13 | 输出: true 14 | 15 | Example 2: 16 | 输入: 0 17 | 输出: false 18 | 19 | Example 3: 20 | 输入: 9 21 | 输出: true 22 | 23 | Example 4: 24 | 输入: 45 25 | 输出: false 26 | 27 | Follow up: 28 | 你能不使用循环或者递归来完成本题吗? 29 | """ 30 | 31 | 32 | class Solution(object): 33 | def isPowerOfThree(self, n): 34 | """ 35 | :type n: int 36 | :rtype: bool 37 | """ 38 | if n == 0: 39 | return False 40 | while True: 41 | if n == 1: 42 | return True 43 | if n % 3 == 0: 44 | n = n // 3 45 | else: 46 | return False 47 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Others/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/26 11:15 4 | # @Author : cancan 5 | # @File : question_1.py 6 | # @Function : 位1的个数 7 | 8 | """ 9 | Question: 10 | 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 11 | 12 | Example 1: 13 | 输入: 11 14 | 输出: 3 15 | 解释: 整数 11 的二进制表示为 00000000000000000000000000001011 16 | 17 | Example 2: 18 | 输入: 128 19 | 输出: 1 20 | 解释: 整数 128 的二进制表示为 00000000000000000000000010000000 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def hammingWeight(self, n): 26 | """ 27 | :type n: int 28 | :rtype: int 29 | """ 30 | return bin(n).count('1') 31 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Others/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/26 11:27 4 | # @Author : cancan 5 | # @File : question_3.py 6 | # @Function : 颠倒二进制位 7 | 8 | """ 9 | Question: 10 | 颠倒给定的 32 位无符号整数的二进制位。 11 | 12 | Example: 13 | 输入: 43261596 14 | 输出: 964176192 15 | 解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 , 16 | 返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。 17 | 18 | Follow up: 19 | 如果多次调用这个函数,你将如何优化你的算法? 20 | """ 21 | 22 | 23 | class Solution: 24 | # @param n, an integer 25 | # @return an integer 26 | def reverseBits(self, n): 27 | return int('{0:032}'.format(int(bin(n)[2:]))[::-1], 2) 28 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Others/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 19:06 4 | # @Author : cancan 5 | # @File : question_4.py 6 | # @Function : 杨辉三角 7 | 8 | """ 9 | Question: 10 | 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 11 | 在杨辉三角中,每个数是它左上方和右上方的数的和。 12 | 13 | Example: 14 | 输入: 5 15 | 输出: 16 | [ 17 | [1], 18 | [1,1], 19 | [1,2,1], 20 | [1,3,3,1], 21 | [1,4,6,4,1] 22 | ] 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def generate(self, numRows): 28 | """ 29 | :type numRows: int 30 | :rtype: List[List[int]] 31 | """ 32 | if numRows == 0: 33 | return [] 34 | if numRows == 1: 35 | return [[1]] 36 | res = [[1]] 37 | r = [1, 1] 38 | for i in range(1, numRows): 39 | res.append(r) 40 | t = [1] 41 | for x in range(len(r) - 1): 42 | t.append(r[x] + r[x + 1]) 43 | t.append(1) 44 | r = t 45 | 46 | return res 47 | 48 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Others/question_6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/28 下午2:08 3 | # @Author : cancan 4 | # @File : question_6.py 5 | # @Function : 缺失数字 6 | 7 | """ 8 | Question: 9 | 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。 10 | 11 | Example 1: 12 | 输入: [3,0,1] 13 | 输出: 2 14 | 15 | Example 2: 16 | 输入: [9,6,4,2,3,5,7,0,1] 17 | 输出: 8 18 | 19 | Note: 20 | 你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现? 21 | """ 22 | 23 | 24 | class Solution1: 25 | def missingNumber(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | nums.sort() 31 | 32 | if nums[0] != 0: 33 | return 0 34 | 35 | for i in range(len(nums) - 1): 36 | if nums[i + 1] - nums[i] != 1: 37 | return nums[i] + 1 38 | 39 | return nums[-1] + 1 40 | 41 | 42 | class Solution2: 43 | def missingNumber(self, nums): 44 | """ 45 | :type nums: List[int] 46 | :rtype: int 47 | """ 48 | return len(nums) * (1 + len(nums)) // 2 - sum(nums) 49 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Strings/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/3 9:58 4 | # @Author : cancan 5 | # @File : question_1.py 6 | # @Function : 反转字符串 7 | 8 | """ 9 | Question: 10 | 请编写一个函数,其功能是将输入的字符串反转过来。 11 | 12 | Example: 13 | 输入:s = "hello" 14 | 返回:"olleh" 15 | """ 16 | 17 | 18 | class Solution: 19 | def reverseString(self, s): 20 | """ 21 | :type s: str 22 | :rtype: str 23 | """ 24 | return s[::-1] 25 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Strings/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/4 9:53 4 | # @Author : cancan 5 | # @File : question_5.py 6 | # @Function : 验证回文字符串 7 | 8 | """ 9 | Question: 10 | 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 11 | 12 | Note: 13 | 本题中,我们将空字符串定义为有效的回文串。 14 | 15 | Example 1: 16 | 输入: "A man, a plan, a canal: Panama" 17 | 输出: true 18 | 19 | Example 2: 20 | 输入: "race a car" 21 | 输出: false 22 | """ 23 | 24 | 25 | class Solution1: 26 | def isPalindrome(self, s): 27 | """ 28 | :type s: str 29 | :rtype: bool 30 | """ 31 | import re 32 | s = ''.join(re.findall(r'(\w+|\d+)', s)).lower() 33 | return s == s[::-1] 34 | 35 | 36 | class Solution2: 37 | def isPalindrome(self, s): 38 | """ 39 | :type s: str 40 | :rtype: bool 41 | """ 42 | s = list(filter(str.isalnum, s.lower())) 43 | return s == s[::-1] 44 | -------------------------------------------------------------------------------- /Interview/Easy Collection/Strings/question_7.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 上午11:11 3 | # @Author : cancan 4 | # @File : question_7.py 5 | # @Function : 实现strStr() 6 | 7 | """ 8 | Question: 9 | 实现 strStr() 函数。 10 | 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 11 | 12 | Example 1: 13 | 输入: haystack = "hello", needle = "ll" 14 | 输出: 2 15 | 16 | Example 2: 17 | 输入: haystack = "aaaaa", needle = "bba" 18 | 输出: -1 19 | 20 | Note: 21 | 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 22 | 对于本题而言,当 needle 是空字符串时我们应当返回 0 。 23 | 这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 24 | """ 25 | 26 | 27 | class Solution: 28 | def strStr(self, haystack, needle): 29 | """ 30 | :type haystack: str 31 | :type needle: str 32 | :rtype: int 33 | """ 34 | try: 35 | return haystack.index(needle) 36 | except ValueError: 37 | return -1 38 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Array and Strings/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/8/4 下午7:10 3 | # @Author : cancan 4 | # @File : question_3.py 5 | # @Function : 字谜分组 6 | 7 | """ 8 | Question: 9 | 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 10 | 11 | Example: 12 | 输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 13 | 输出: 14 | [ 15 | ["ate","eat","tea"], 16 | ["nat","tan"], 17 | ["bat"] 18 | ] 19 | 20 | Note 21 | 1.所有输入均为小写字母。 22 | 2.不考虑答案输出的顺序。 23 | """ 24 | 25 | 26 | class Solution: 27 | def groupAnagrams(self, strs): 28 | """ 29 | :type strs: List[str] 30 | :rtype: List[List[str]] 31 | """ 32 | t = {} 33 | 34 | for i in strs: 35 | s = ''.join(sorted(i)) 36 | if s in t: 37 | t[s].append(i) 38 | else: 39 | t[s] = [i] 40 | 41 | return [i for i in t.values()] 42 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Math/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/21 下午6:35 3 | # @Author : cancan 4 | # @File : question_4.py 5 | # @Function : Pow(x, n) 6 | 7 | """ 8 | Question: 9 | 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 10 | 11 | Example 1: 12 | 输入: 2.00000, 10 13 | 输出: 1024.00000 14 | 15 | Example 2: 16 | 输入: 2.10000, 3 17 | 输出: 9.26100 18 | 19 | Example 3: 20 | 输入: 2.00000, -2 21 | 输出: 0.25000 22 | 解释: 2-2 = 1/22 = 1/4 = 0.25 23 | 24 | Note: 25 | -100.0 < x < 100.0 26 | n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 27 | """ 28 | 29 | 30 | class Solution: 31 | def myPow(self, x, n): 32 | """ 33 | :type x: float 34 | :type n: int 35 | :rtype: float 36 | """ 37 | return x ** n 38 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Math/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/10 9:40 4 | # @Author : cancan 5 | # @File : question_5.py 6 | # @Function : x 的平方根 7 | 8 | """ 9 | Question: 10 | 实现 int sqrt(int x) 函数。 11 | 计算并返回 x 的平方根,其中 x 是非负整数。 12 | 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 13 | 14 | Example 1: 15 | 输入: 4 16 | 输出: 2 17 | 18 | Example 2: 19 | 输入: 8 20 | 输出: 2 21 | 说明: 8 的平方根是 2.82842..., 22 | 由于返回类型是整数,小数部分将被舍去。 23 | """ 24 | 25 | 26 | class Solution: 27 | def mySqrt(self, x): 28 | """ 29 | :type x: int 30 | :rtype: int 31 | """ 32 | return int(x ** 0.5) 33 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Others/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/6/30 下午2:54 3 | # @Author : cancan 4 | # @File : question_1.py 5 | # @Function : 两整数之和 6 | 7 | """ 8 | Question: 9 | 不使用运算符 + 和-,计算两整数a 、b之和。 10 | 11 | Example: 12 | 若 a = 1 ,b = 2,返回 3。 13 | """ 14 | 15 | 16 | class Solution: 17 | def getSum(self, a, b): 18 | """ 19 | :type a: int 20 | :type b: int 21 | :rtype: int 22 | """ 23 | return sum([a, b]) 24 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Others/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/1 14:49 4 | # @Author : cancan 5 | # @File : question_3.py 6 | # @Function : 求众数 7 | 8 | """ 9 | Question: 10 | 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 11 | 你可以假设数组是非空的,并且给定的数组总是存在众数。 12 | 13 | Example 1: 14 | 输入: [3,2,3] 15 | 输出: 3 16 | 17 | Example 2: 18 | 输入: [2,2,1,1,1,2,2] 19 | 输出: 2 20 | """ 21 | 22 | 23 | class Solution: 24 | def majorityElement(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | 30 | d = len(nums) / 2 31 | 32 | for i in set(nums): 33 | if nums.count(i) > d: 34 | return i 35 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Sorting and Searching/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/2 16:17 4 | # @Author : cancan 5 | # @File : question_1.py 6 | # @Function : 颜色分类 7 | 8 | """ 9 | Question: 10 | 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序, 11 | 使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 12 | 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 13 | 14 | Note: 15 | 不能使用代码库中的排序函数来解决这道题。 16 | 17 | Example: 18 | 输入: [2,0,2,1,1,0] 19 | 输出: [0,0,1,1,2,2] 20 | 21 | Follow up 22 | 1.一个直观的解决方案是使用计数排序的两趟扫描算法。首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 23 | 2.你能想出一个仅使用常数空间的一趟扫描算法吗? 24 | """ 25 | 26 | 27 | class Solution: 28 | def sortColors(self, nums): 29 | """ 30 | :type nums: List[int] 31 | :rtype: void Do not return anything, modify nums in-place instead. 32 | """ 33 | return nums.sort() 34 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Sorting and Searching/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/7 13:58 4 | # @Author : cancan 5 | # @File : question_2.py 6 | # @Function : 前K个高频元素 7 | 8 | """ 9 | Question: 10 | 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 11 | 12 | Example 13 | 给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]。 14 | 15 | Note 16 | 1.你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。 17 | 2.你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 18 | """ 19 | 20 | from collections import Counter 21 | 22 | 23 | class Solution: 24 | def topKFrequent(self, nums, k): 25 | """ 26 | :type nums: List[int] 27 | :type k: int 28 | :rtype: List[int] 29 | """ 30 | 31 | return [i[0] for i in Counter(nums).most_common()[:k]] 32 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Sorting and Searching/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/3 17:53 4 | # @Author : cancan 5 | # @File : question_3.py 6 | # @Function : 数组中的第K个最大元素 7 | 8 | """ 9 | Question: 10 | 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 11 | 12 | Example 1: 13 | 输入: [3,2,1,5,6,4] 和 k = 2 14 | 输出: 5 15 | 16 | Example 2: 17 | 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 18 | 输出: 4 19 | 20 | Note: 21 | 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def findKthLargest(self, nums, k): 27 | """ 28 | :type nums: List[int] 29 | :type k: int 30 | :rtype: int 31 | """ 32 | return sorted(nums)[-k] 33 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Sorting and Searching/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/8 17:35 4 | # @Author : cancan 5 | # @File : question_4.py 6 | # @Function : 寻找峰值 7 | 8 | """ 9 | Question: 10 | 峰值元素是指其值大于左右相邻值的元素。 11 | 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 12 | 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 13 | 你可以假设 nums[-1] = nums[n] = -∞。 14 | 15 | Example 1: 16 | 输入: nums = [1,2,3,1] 17 | 输出: 2 18 | 解释: 3 是峰值元素,你的函数应该返回其索引 2。 19 | 20 | Example 2: 21 | 输入: nums = [1,2,1,3,5,6,4] 22 | 输出: 1 或 5 23 | 解释: 你的函数可以返回索引 1,其峰值元素为 2; 24 | 或者返回索引 5, 其峰值元素为 6。 25 | 26 | Note: 27 | 你的解法应该是 O(logN) 时间复杂度的。 28 | """ 29 | 30 | 31 | class Solution: 32 | def findPeakElement(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | return nums.index(max(nums)) 38 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Sorting and Searching/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/21 下午5:43 3 | # @Author : cancan 4 | # @File : question_5.py 5 | # @Function : 在排序数组中查找元素的第一个和最后一个位置 6 | 7 | """ 8 | Question: 9 | 给定一个按照升序排列的整数数组 nums,和一个目标值 target。 10 | 找出给定目标值在数组中的开始位置和结束位置。 11 | 你的算法时间复杂度必须是 O(log n) 级别。 12 | 如果数组中不存在目标值,返回 [-1, -1]。 13 | 14 | Example 1: 15 | 输入: nums = [5,7,7,8,8,10], target = 8 16 | 输出: [3,4] 17 | 18 | Example 2: 19 | 输入: nums = [5,7,7,8,8,10], target = 6 20 | 输出: [-1,-1] 21 | """ 22 | 23 | 24 | class Solution: 25 | def searchRange(self, nums, target): 26 | """ 27 | :type nums: List[int] 28 | :type target: int 29 | :rtype: List[int] 30 | """ 31 | if target not in nums: 32 | return [-1, -1] 33 | 34 | start = nums.index(target) 35 | end = start + 1 36 | l = len(nums) 37 | 38 | while end < l and nums[end] == target: 39 | end += 1 40 | 41 | end -= 1 42 | 43 | return [start, end] 44 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Sorting and Searching/question_7.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/8 18:05 4 | # @Author : cancan 5 | # @File : question_7.py 6 | # @Function : 搜索旋转排序数组 7 | 8 | """ 9 | Question: 10 | 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 11 | ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 12 | 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 13 | 你可以假设数组中不存在重复的元素。 14 | 你的算法时间复杂度必须是 O(log n) 级别。 15 | 16 | Example 1: 17 | 输入: nums = [4,5,6,7,0,1,2], target = 0 18 | 输出: 4 19 | 20 | Example 2: 21 | 输入: nums = [4,5,6,7,0,1,2], target = 3 22 | 输出: -1 23 | """ 24 | 25 | 26 | class Solution: 27 | def search(self, nums, target): 28 | """ 29 | :type nums: List[int] 30 | :type target: int 31 | :rtype: int 32 | """ 33 | if target not in nums: 34 | return -1 35 | return nums.index(target) 36 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Sorting and Searching/question_8.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/8 18:16 4 | # @Author : cancan 5 | # @File : question_8.py 6 | # @Function : 搜索二维矩阵 II 7 | 8 | """ 9 | Question: 10 | 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: 11 | 1.每行的元素从左到右升序排列。 12 | 2.每列的元素从上到下升序排列。 13 | 14 | Example: 15 | 现有矩阵 matrix 如下: 16 | [ 17 | [1, 4, 7, 11, 15], 18 | [2, 5, 8, 12, 19], 19 | [3, 6, 9, 16, 22], 20 | [10, 13, 14, 17, 24], 21 | [18, 21, 23, 26, 30] 22 | ] 23 | 给定 target = 5,返回 true。 24 | 给定 target = 20,返回 false。 25 | """ 26 | 27 | 28 | class Solution: 29 | def searchMatrix(self, matrix, target): 30 | """ 31 | :type matrix: List[List[int]] 32 | :type target: int 33 | :rtype: bool 34 | """ 35 | for item in matrix: 36 | if target in item: 37 | return True 38 | return False 39 | -------------------------------------------------------------------------------- /Interview/Medium Collection/Trees and Graphs/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/8/5 下午3:10 3 | # @Author : cancan 4 | # @File : question_1.py 5 | # @Function : 中序遍历二叉树 6 | 7 | """ 8 | Question: 9 | 给定一个二叉树,返回它的中序 遍历。 10 | 11 | Example: 12 | 输入: [1,null,2,3] 13 | 1 14 | \ 15 | 2 16 | / 17 | 3 18 | 输出: [1,3,2] 19 | 20 | Follow up: 21 | 递归算法很简单,你可以通过迭代算法完成吗? 22 | """ 23 | 24 | 25 | # Definition for a binary tree node. 26 | # class TreeNode: 27 | # def __init__(self, x): 28 | # self.val = x 29 | # self.left = None 30 | # self.right = None 31 | 32 | class Solution: 33 | def inorderTraversal(self, root): 34 | """ 35 | :type root: TreeNode 36 | :rtype: List[int] 37 | """ 38 | if root is None: 39 | return [] 40 | r = [] 41 | r.extend(self.inorderTraversal(root.left)) 42 | r.append(root.val) 43 | r.extend(self.inorderTraversal(root.right)) 44 | return r 45 | -------------------------------------------------------------------------------- /LCP/1.Guess Numbers/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/9/26 14:39 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 猜数字 7 | 8 | 9 | """ 10 | Question: 11 | 小A 和 小B 在玩猜数字。小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜。他们一共进行三次这个游戏,请返回 小A 猜对了几次? 12 | 输入的guess数组为 小A 每次的猜测,answer数组为 小B 每次的选择。guess和answer的长度都等于3。 13 | 14 | Example 1: 15 | 输入:guess = [1,2,3], answer = [1,2,3] 16 | 输出:3 17 | 解释:小A 每次都猜对了。 18 | 19 | Example 2: 20 | 输入:guess = [2,2,3], answer = [3,2,1] 21 | 输出:1 22 | 解释:小A 只猜对了第二次。 23 | 24 | Note: 25 | guess的长度 = 3 26 | answer的长度 = 3 27 | guess的元素取值为 {1, 2, 3} 之一。 28 | answer的元素取值为 {1, 2, 3} 之一。 29 | """ 30 | 31 | from typing import List 32 | 33 | 34 | class Solution: 35 | def game(self, guess: List[int], answer: List[int]) -> int: 36 | ans = 0 37 | if guess[0] == answer[0]: 38 | ans += 1 39 | if guess[1] == answer[1]: 40 | ans += 1 41 | if guess[2] == answer[2]: 42 | ans += 1 43 | return ans 44 | -------------------------------------------------------------------------------- /LCP/6.Take Coins/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2021/2/20 11:50 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 拿硬币 7 | 8 | """ 9 | 桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。 10 | 11 | 示例 1: 12 | 输入:[4,2,1] 13 | 输出:4 14 | 解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。 15 | 16 | 示例 2: 17 | 输入:[2,3,10] 18 | 输出:8 19 | 20 | 限制: 21 | - 1 <= n <= 4 22 | - 1 <= coins[i] <= 10 23 | """ 24 | 25 | from typing import List 26 | 27 | 28 | class Solution: 29 | def minCount(self, coins: List[int]) -> int: 30 | ans = 0 31 | for v in coins: 32 | div, mod = divmod(v, 2) 33 | ans += div 34 | if mod > 0: 35 | ans += 1 36 | return ans 37 | -------------------------------------------------------------------------------- /Learn/Array and String/Conclusion/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/7 下午10:52 3 | # @Author : cancan 4 | # @File : question_1.py 5 | # @Function : 旋转数据 6 | 7 | """ 8 | Question: 9 | 将包含 n 个元素的数组向右旋转 k 步。 10 | 11 | Example: 12 | 如果n = 7,k = 3,给定数组[1,2,3,4,5,6,7],向右旋转后的结果为[5,6,7,1,2,3,4]。 13 | 14 | Note: 15 | 尽可能找到更多的解决方案,这里最少有三种不同的方法解决这个问题。 16 | """ 17 | 18 | 19 | class Solution: 20 | def rotate(self, nums, k): 21 | """ 22 | :type nums: List[int] 23 | :type k: int 24 | :rtype: void Do not return anything, modify nums in-place instead. 25 | """ 26 | l = len(nums) 27 | nums[:k], nums[k: l] = nums[l - k: l], nums[: l - k] 28 | -------------------------------------------------------------------------------- /Learn/Array and String/Conclusion/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 18:59 4 | # @Author : cancan 5 | # @File : question_2.py 6 | # @Function : 杨辉三角 II 7 | 8 | """ 9 | Question: 10 | 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 11 | 在杨辉三角中,每个数是它左上方和右上方的数的和。 12 | 13 | Example: 14 | 输入: 3 15 | 输出: [1,3,3,1] 16 | 17 | Follow up: 18 | 你可以优化你的算法到 O(k) 空间复杂度吗? 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def getRow(self, rowIndex): 24 | """ 25 | :type rowIndex: int 26 | :rtype: List[int] 27 | """ 28 | if rowIndex == 0: 29 | return [1] 30 | r = [1, 1] 31 | for i in range(1, rowIndex): 32 | t = [1] 33 | for x in range(len(r) - 1): 34 | t.append(r[x] + r[x + 1]) 35 | t.append(1) 36 | r = t 37 | 38 | return r 39 | -------------------------------------------------------------------------------- /Learn/Array and String/Conclusion/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 18:17 4 | # @Author : cancan 5 | # @File : question_3.py 6 | # @Function : 翻转字符串里的单词 7 | 8 | """ 9 | Question: 10 | 11 | 给定一个字符串,逐个翻转字符串中的每个单词。 12 | 13 | Example: 14 | 输入: "the sky is blue", 15 | 输出: "blue is sky the". 16 | 17 | Note: 18 | 1.无空格字符构成一个单词。 19 | 2.输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 20 | 3.如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 21 | 22 | Follow up: 23 | 请选用C语言的用户尝试使用 O(1) 时间复杂度的原地解法。 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def reverseWords(self, s): 29 | """ 30 | :type s: str 31 | :rtype: str 32 | """ 33 | return ' '.join(s.split()[::-1]) 34 | -------------------------------------------------------------------------------- /Learn/Array and String/Conclusion/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/1 下午6:39 3 | # @Author : cancan 4 | # @File : question_4.py 5 | # @Function : 反转字符串中的单词 III 6 | 7 | """ 8 | Question: 9 | 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 10 | 11 | Example: 12 | 输入: "Let's take LeetCode contest" 13 | 输出: "s'teL ekat edoCteeL tsetnoc" 14 | 15 | Note: 16 | 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 17 | """ 18 | 19 | 20 | class Solution: 21 | def reverseWords(self, s): 22 | """ 23 | :type s: str 24 | :rtype: str 25 | """ 26 | return ' '.join([i[::-1] for i in s.split()]) 27 | -------------------------------------------------------------------------------- /Learn/Array and String/Conclusion/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/7 下午10:52 3 | # @Author : cancan 4 | # @File : question_5.py 5 | # @Function : 从排序数组中删除重复项 6 | 7 | """ 8 | Question: 9 | 给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。 10 | 不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。 11 | 12 | Example: 13 | 给定数组: nums = [1,1,2], 14 | 你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2 15 | 不需要理会新的数组长度后面的元素 16 | """ 17 | 18 | 19 | class Solution: 20 | def removeDuplicates(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: int 24 | """ 25 | a = [] 26 | d = [] 27 | for i, v in enumerate(nums): 28 | if v not in a: 29 | a.append(v) 30 | else: 31 | d.append(i) 32 | 33 | for i in sorted(d, reverse=True): 34 | del nums[i] 35 | 36 | return len(nums) 37 | -------------------------------------------------------------------------------- /Learn/Array and String/Conclusion/question_6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/1 下午9:30 3 | # @Author : cancan 4 | # @File : question_6.py 5 | # @Function : 移动零 6 | 7 | """ 8 | Question: 9 | 给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。 10 | 例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。 11 | 12 | Note: 13 | 1.必须在原数组上操作,不要为一个新数组分配额外空间。 14 | 2.尽量减少操作总数。 15 | """ 16 | 17 | 18 | class Solution: 19 | def moveZeroes(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: void Do not return anything, modify nums in-place instead. 23 | """ 24 | i = 0 25 | c = 0 26 | while (i < len(nums) - c): 27 | if nums[i] == 0: 28 | nums.pop(i) 29 | nums.append(0) 30 | c += 1 31 | else: 32 | i += 1 33 | -------------------------------------------------------------------------------- /Learn/Array and String/Introduction to 2D Array/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 19:06 4 | # @Author : cancan 5 | # @File : question_4.py 6 | # @Function : 杨辉三角 7 | 8 | """ 9 | Question: 10 | 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 11 | 在杨辉三角中,每个数是它左上方和右上方的数的和。 12 | 13 | Example: 14 | 输入: 5 15 | 输出: 16 | [ 17 | [1], 18 | [1,1], 19 | [1,2,1], 20 | [1,3,3,1], 21 | [1,4,6,4,1] 22 | ] 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def generate(self, numRows): 28 | """ 29 | :type numRows: int 30 | :rtype: List[List[int]] 31 | """ 32 | if numRows == 0: 33 | return [] 34 | if numRows == 1: 35 | return [[1]] 36 | res = [[1]] 37 | r = [1, 1] 38 | for i in range(1, numRows): 39 | res.append(r) 40 | t = [1] 41 | for x in range(len(r) - 1): 42 | t.append(r[x] + r[x + 1]) 43 | t.append(1) 44 | r = t 45 | 46 | return res 47 | 48 | -------------------------------------------------------------------------------- /Learn/Array and String/Introduction to Array/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/23 11:58 4 | # @Author : cancan 5 | # @File : question_2.py 6 | # @Function : 至少是其他数字两倍的最大数 7 | 8 | """ 9 | Question: 10 | 在一个给定的数组nums中,总是存在一个最大元素 。 11 | 查找数组中的最大元素是否至少是数组中每个其他数字的两倍。 12 | 如果是,则返回最大元素的索引,否则返回-1。 13 | 14 | Example 1: 15 | 输入: nums = [3, 6, 1, 0] 16 | 输出: 1 17 | 解释: 6是最大的整数, 对于数组中的其他整数, 18 | 6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1. 19 | 20 | Example 2: 21 | 输入: nums = [1, 2, 3, 4] 22 | 输出: -1 23 | 解释: 4没有超过3的两倍大, 所以我们返回 -1. 24 | 25 | Note: 26 | 1.nums 的长度范围在[1, 50]. 27 | 2.每个 nums[i] 的整数范围在 [0, 99]. 28 | """ 29 | 30 | 31 | class Solution(object): 32 | def dominantIndex(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | m = max(nums) 38 | index = nums.index(m) 39 | del nums[index] 40 | 41 | for i in nums: 42 | if m < 2 * i: 43 | return -1 44 | 45 | return index 46 | -------------------------------------------------------------------------------- /Learn/Array and String/Introduction to Array/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/1 下午9:01 3 | # @Author : cancan 4 | # @File : question_4.py 5 | # @Function : 加一 6 | 7 | """ 8 | Question: 9 | 给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。 10 | 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。 11 | 你可以假设除了整数 0 之外,这个整数不会以零开头。 12 | 13 | Example 1: 14 | 输入: [1,2,3] 15 | 输出: [1,2,4] 16 | 解释: 输入数组表示数字 123。 17 | 18 | Example 2: 19 | 输入: [4,3,2,1] 20 | 输出: [4,3,2,2] 21 | 解释: 输入数组表示数字 4321。 22 | """ 23 | 24 | 25 | class Solution: 26 | def plusOne(self, digits): 27 | """ 28 | :type digits: List[int] 29 | :rtype: List[int] 30 | """ 31 | s1 = '' 32 | for i in digits: 33 | s1 += str(i) 34 | 35 | s1 = str(int(s1) + 1) 36 | 37 | r = [] 38 | 39 | for i in s1: 40 | r.append(int(i)) 41 | 42 | return r 43 | -------------------------------------------------------------------------------- /Learn/Array and String/Introduction to String/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/14 上午11:31 3 | # @Author : cancan 4 | # @File : question_1.py 5 | # @Function : 二进制求和 6 | 7 | """ 8 | Question: 9 | 给定两个二进制字符串,返回他们的和(用二进制表示)。 10 | 输入为非空字符串且只包含数字 1 和 0。 11 | 12 | Example 1: 13 | 输入: a = "11", b = "1" 14 | 输出: "100" 15 | 16 | Example 2: 17 | 输入: a = "1010", b = "1011" 18 | 输出: "10101" 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def addBinary(self, a, b): 24 | """ 25 | :type a: str 26 | :type b: str 27 | :rtype: str 28 | """ 29 | return bin(int(a, 2) + int(b, 2))[2:] 30 | -------------------------------------------------------------------------------- /Learn/Array and String/Introduction to String/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 上午11:11 3 | # @Author : cancan 4 | # @File : question_2.py 5 | # @Function : 实现strStr() 6 | 7 | """ 8 | Question: 9 | 实现 strStr() 函数。 10 | 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 11 | 12 | Example 1: 13 | 输入: haystack = "hello", needle = "ll" 14 | 输出: 2 15 | 16 | Example 2: 17 | 输入: haystack = "aaaaa", needle = "bba" 18 | 输出: -1 19 | 20 | Note: 21 | 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 22 | 对于本题而言,当 needle 是空字符串时我们应当返回 0 。 23 | 这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 24 | """ 25 | 26 | 27 | class Solution: 28 | def strStr(self, haystack, needle): 29 | """ 30 | :type haystack: str 31 | :type needle: str 32 | :rtype: int 33 | """ 34 | try: 35 | return haystack.index(needle) 36 | except ValueError: 37 | return -1 38 | -------------------------------------------------------------------------------- /Learn/Array and String/Introduction to String/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午1:03 3 | # @Author : cancan 4 | # @File : question_3.py 5 | # @Function : 最长公共前缀 6 | 7 | """ 8 | Question: 9 | 编写一个函数来查找字符串数组中的最长公共前缀。 10 | 如果不存在公共前缀,返回空字符串 ""。 11 | 12 | Example 1: 13 | 输入: ["flower","flow","flight"] 14 | 输出: "fl" 15 | 16 | Example 2: 17 | 输入: ["dog","racecar","car"] 18 | 输出: "" 19 | 解释: 输入不存在公共前缀。 20 | 21 | Note: 22 | 所有输入只包含小写字母 a-z 。 23 | """ 24 | 25 | 26 | class Solution: 27 | def longestCommonPrefix(self, strs): 28 | """ 29 | :type strs: List[str] 30 | :rtype: str 31 | """ 32 | t = min(strs, key=lambda x: len(x)) if strs else '' 33 | l = len(t) 34 | for i in strs: 35 | if t == i: 36 | continue 37 | for y in range(l): 38 | if t[:y + 1] != i[:y + 1]: 39 | t = '' if y == 0 else t[:y] 40 | break 41 | return t 42 | -------------------------------------------------------------------------------- /Learn/Array and String/Two-Pointer Technique/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/3 9:58 4 | # @Author : cancan 5 | # @File : question_1.py 6 | # @Function : 反转字符串 7 | 8 | """ 9 | Question: 10 | 请编写一个函数,其功能是将输入的字符串反转过来。 11 | 12 | Example: 13 | 输入:s = "hello" 14 | 返回:"olleh" 15 | """ 16 | 17 | class Solution: 18 | def reverseString(self, s): 19 | """ 20 | :type s: str 21 | :rtype: str 22 | """ 23 | return s[::-1] -------------------------------------------------------------------------------- /Learn/Array and String/Two-Pointer Technique/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/23 15:05 4 | # @Author : cancan 5 | # @File : question_2.py 6 | # @Function : 数组拆分 I 7 | 8 | """ 9 | Question: 10 | 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., 11 | (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。 12 | 13 | Example 1: 14 | 输入: [1,4,3,2] 15 | 输出: 4 16 | 解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4). 17 | 18 | Note: 19 | 1.n 是正整数,范围在 [1, 10000]. 20 | 2.数组中的元素范围在 [-10000, 10000]. 21 | """ 22 | 23 | 24 | class Solution: 25 | def arrayPairSum(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | nums.sort() 31 | l = len(nums) 32 | s = 0 33 | 34 | for i in range(0, l, 2): 35 | s += nums[i] 36 | 37 | return s 38 | -------------------------------------------------------------------------------- /Learn/Array and String/Two-Pointer Technique/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/20 10:59 4 | # @Author : cancan 5 | # @File : question_3.py 6 | # @Function : 两数之和 II - 输入有序数组 7 | 8 | """ 9 | Question: 10 | 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 11 | 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 12 | 13 | NOte: 14 | 1.返回的下标值(index1 和 index2)不是从零开始的。 15 | 2.你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 16 | 17 | Example: 18 | 输入: numbers = [2, 7, 11, 15], target = 9 19 | 输出: [1,2] 20 | 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def twoSum(self, numbers, target): 26 | """ 27 | :type numbers: List[int] 28 | :type target: int 29 | :rtype: List[int] 30 | """ 31 | t = {} 32 | for i, v in enumerate(numbers): 33 | if v in t: 34 | return [t[v] + 1, i + 1] 35 | else: 36 | t[target - v] = i 37 | -------------------------------------------------------------------------------- /Learn/Array and String/Two-Pointer Technique/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/20 10:59 4 | # @Author : cancan 5 | # @File : question_4.py 6 | # @Function : 移除元素 7 | 8 | """ 9 | Question: 10 | 给定一个数组和一个值,删除该值的所有实例并返回新的长度。 11 | 不要为另一个数组分配额外的空间,您必须在固定内存的情况下这样做。 12 | 元素的顺序可以更改。不管你留了多少新长度。 13 | 14 | Example: 15 | 给定一个数组和值 nums = [3,2,2,3], val = 3 16 | 您的函数应该返回length = 2,而nums的前两个元素为2。 17 | """ 18 | 19 | class Solution(object): 20 | def removeElement(self, nums, val): 21 | """ 22 | :type nums: List[int] 23 | :type val: int 24 | :rtype: int 25 | """ 26 | l = len(nums) 27 | d = 0 28 | for i in range(l): 29 | if nums[i - d] == val: 30 | del nums[i - d] 31 | d += 1 -------------------------------------------------------------------------------- /Learn/Array and String/Two-Pointer Technique/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/24 14:58 4 | # @Author : cancan 5 | # @File : question_5.py 6 | # @Function : 最大连续1的个数 7 | 8 | """ 9 | Question: 10 | 给定一个二进制数组, 计算其中最大连续1的个数。 11 | 12 | Example 1: 13 | 输入: [1,1,0,1,1,1] 14 | 输出: 3 15 | 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3. 16 | 17 | Note 18 | 1.输入的数组只包含 0 和1。 19 | 2.输入数组的长度是正整数,且不超过 10,000。 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def findMaxConsecutiveOnes(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | t = {1: 0} 30 | r = t[1] 31 | 32 | for i, v in enumerate(nums): 33 | if v == 1: 34 | t[v] += 1 35 | else: 36 | if t[1] > r: 37 | r = t[1] 38 | t[1] = 0 39 | 40 | return t[1] if t[1] > r else r 41 | -------------------------------------------------------------------------------- /Learn/Binary Tree/Binary Tree Traversal/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 17:33 4 | # @Author : cancan 5 | # @File : question_1.py 6 | # @Function : 二叉树的前序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的 前序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [1,2,3] 20 | 21 | Follow up: 22 | 递归算法很简单,你可以通过迭代算法完成吗? 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution: 34 | def preorderTraversal(self, root): 35 | """ 36 | :type root: TreeNode 37 | :rtype: List[int] 38 | """ 39 | if not root: 40 | return [] 41 | r = [] 42 | r.append(root.val) 43 | r.extend(self.preorderTraversal(root.left)) 44 | r.extend(self.preorderTraversal(root.right)) 45 | return r 46 | -------------------------------------------------------------------------------- /Learn/Binary Tree/Binary Tree Traversal/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 14:18 4 | # @Author : cancan 5 | # @File : question_2.py 6 | # @Function : 二叉树的中序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的中序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [1,3,2] 20 | """ 21 | 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.left = None 28 | # self.right = None 29 | 30 | class Solution: 31 | def inorderTraversal(self, root): 32 | """ 33 | :type root: TreeNode 34 | :rtype: List[int] 35 | """ 36 | if root is None: 37 | return [] 38 | r = [] 39 | r.extend(self.inorderTraversal(root.left)) 40 | r.append(root.val) 41 | r.extend(self.inorderTraversal(root.right)) 42 | return r 43 | -------------------------------------------------------------------------------- /Learn/Binary Tree/Binary Tree Traversal/question_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 17:29 4 | # @Author : cancan 5 | # @File : question_3.py 6 | # @Function : 二叉树的后序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的 后序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [3,2,1] 20 | 21 | Follow up: 22 | 递归算法很简单,你可以通过迭代算法完成吗? 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution: 34 | def postorderTraversal(self, root): 35 | """ 36 | :type root: TreeNode 37 | :rtype: List[int] 38 | """ 39 | if not root: 40 | return [] 41 | r = [] 42 | r.extend(self.postorderTraversal(root.left)) 43 | r.extend(self.postorderTraversal(root.right)) 44 | r.append(root.val) 45 | return r 46 | -------------------------------------------------------------------------------- /Learn/Linked List/Classic Problems/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午3:06 3 | # @Author : cancan 4 | # @File : question_1.py 5 | # @Function : 反转链表 6 | 7 | """ 8 | Question: 9 | 反转一个单链表。 10 | 11 | Example: 12 | 输入: 1->2->3->4->5->NULL 13 | 输出: 5->4->3->2->1->NULL 14 | 15 | Follow up: 16 | 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? 17 | """ 18 | 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode(object): 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.next = None 25 | 26 | class Solution(object): 27 | def reverseList(self, head): 28 | """ 29 | :type head: ListNode 30 | :rtype: ListNode 31 | """ 32 | if not head or not head.next: 33 | return head 34 | 35 | def f(node, pre): 36 | t = node.next 37 | node.next = pre 38 | if not t: 39 | return node 40 | else: 41 | return f(t, node) 42 | 43 | return f(head, None) 44 | -------------------------------------------------------------------------------- /Learn/Linked List/Classic Problems/question_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午7:28 3 | # @Author : cancan 4 | # @File : question_5.py 5 | # @Function : 回文链表 6 | 7 | """ 8 | Question: 9 | 请检查一个链表是否为回文链表。 10 | 11 | Follow up: 12 | 你能在 O(n) 的时间和 O(1) 的额外空间中做到吗 13 | """ 14 | 15 | 16 | # Definition for singly-linked list. 17 | # class ListNode(object): 18 | # def __init__(self, x): 19 | # self.val = x 20 | # self.next = None 21 | 22 | class Solution(object): 23 | def isPalindrome(self, head): 24 | """ 25 | :type head: ListNode 26 | :rtype: bool 27 | """ 28 | if not head: 29 | return True 30 | t = [head.val] 31 | n = head.next 32 | while n: 33 | t.append(n.val) 34 | n = n.next 35 | 36 | l = len(t) 37 | i = l // 2 38 | if l % 2 == 0: 39 | return t[:i] == t[i:][::-1] 40 | else: 41 | return t[:i] == t[i + 1:][::-1] 42 | -------------------------------------------------------------------------------- /Learn/N-ary Tree/Traversal/question_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/2 16:09 4 | # @Author : cancan 5 | # @File : question_1.py 6 | # @Function : N叉树的前序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个N叉树,返回其节点值的前序遍历。 11 | 12 | Example: 13 | 给定一个 3叉树 : 14 | 1 15 | / | \ 16 | 3 2 4 17 | / \ 18 | 5 6 19 | 返回其前序遍历: [1,3,5,6,2,4]。 20 | 21 | Note: 22 | 递归法很简单,你可以使用迭代法完成此题吗? 23 | """ 24 | 25 | """ 26 | # Definition for a Node. 27 | class Node(object): 28 | def __init__(self, val, children): 29 | self.val = val 30 | self.children = children 31 | """ 32 | 33 | 34 | class Solution(object): 35 | def preorder(self, root): 36 | """ 37 | :type root: Node 38 | :rtype: List[int] 39 | """ 40 | if not root: return [] 41 | 42 | result = [] 43 | 44 | def f(node, result): 45 | result.append(node.val) 46 | for item in node.children: 47 | f(item, result) 48 | 49 | f(root, result) 50 | 51 | return result 52 | -------------------------------------------------------------------------------- /Learn/N-ary Tree/Traversal/question_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/16 15:42 4 | # @Author : cancan 5 | # @File : question_2.py 6 | # @Function : N叉树的后序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个N叉树,返回其节点值的后序遍历。 11 | 12 | Example: 13 | 例如,给定一个 3叉树 : 14 | 1 15 | / | \ 16 | 3 2 4 17 | / \ 18 | 5 6 19 | 返回其后序遍历: [5,6,3,2,4,1]. 20 | 21 | Note: 22 | 递归法很简单,你可以使用迭代法完成此题吗? 23 | """ 24 | 25 | """ 26 | # Definition for a Node. 27 | class Node(object): 28 | def __init__(self, val, children): 29 | self.val = val 30 | self.children = children 31 | """ 32 | 33 | 34 | class Solution(object): 35 | def postorder(self, root): 36 | """ 37 | :type root: Node 38 | :rtype: List[int] 39 | """ 40 | result = [] 41 | 42 | def f(node, data): 43 | if not node: return 44 | 45 | for item in node.children: 46 | f(item, data) 47 | 48 | data.append(node.val) 49 | 50 | f(root, result) 51 | 52 | return result 53 | -------------------------------------------------------------------------------- /Learn/Queue & Stack/Stack and DFS/question_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 14:18 4 | # @Author : cancan 5 | # @File : question_4.py 6 | # @Function : 二叉树的中序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的中序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [1,3,2] 20 | """ 21 | 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.left = None 28 | # self.right = None 29 | 30 | class Solution: 31 | def inorderTraversal(self, root): 32 | """ 33 | :type root: TreeNode 34 | :rtype: List[int] 35 | """ 36 | if root is None: 37 | return [] 38 | r = [] 39 | r.extend(self.inorderTraversal(root.left)) 40 | r.append(root.val) 41 | r.extend(self.inorderTraversal(root.right)) 42 | return r 43 | -------------------------------------------------------------------------------- /QuestionBank/1.Two Sun/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 给定一个整数数组,两个数字的返回索引,它们加到一个特定的目标。 6 | 您可能假设每个输入都有一个完全的解决方案,您可能不会重复使用相同的元素两次。 7 | 8 | Example: 9 | Given nums = [2, 7, 11, 15], target = 9 10 | Because nums[0] + nums[1] = 2 + 7 = 9 11 | return [0, 1] 12 | """ 13 | 14 | class Solution(object): 15 | def twoSum(self, nums, target): 16 | """ 17 | :type nums: List[int] 18 | :type target: int 19 | :rtype: List[int] 20 | """ 21 | 22 | nums_len_list = range(len(nums)) 23 | for i in nums_len_list: 24 | n = target - nums[i] 25 | if (nums.count(n) != 0) and (nums.index(n) != i): 26 | return [i, nums.index(n)] 27 | -------------------------------------------------------------------------------- /QuestionBank/1.Two Sun/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 给定一个整数数组,两个数字的返回索引,它们加到一个特定的目标。 6 | 您可能假设每个输入都有一个完全的解决方案,您可能不会重复使用相同的元素两次。 7 | 8 | Example: 9 | Given nums = [2, 7, 11, 15], target = 9 10 | Because nums[0] + nums[1] = 2 + 7 = 9 11 | return [0, 1] 12 | """ 13 | 14 | class Solution(object): 15 | def twoSum(self, nums, target): 16 | """ 17 | :type nums: List[int] 18 | :type target: int 19 | :rtype: List[int] 20 | """ 21 | 22 | result_dict = {} 23 | for i, t in enumerate(nums): 24 | if t in result_dict: 25 | return [result_dict[t], i] 26 | else: 27 | n = target - t 28 | result_dict[n] = i 29 | -------------------------------------------------------------------------------- /QuestionBank/1.Two Sun/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # @Time : 2018/5/1 下午9:58 3 | # @Author : cancan 4 | # @File : method_3.py 5 | # @Function : 两数之和 6 | 7 | """ 8 | Question: 9 | 给定一个整数数组,两个数字的返回索引,它们加到一个特定的目标。 10 | 您可能假设每个输入都有一个完全的解决方案,您可能不会重复使用相同的元素两次。 11 | 12 | Example: 13 | Given nums = [2, 7, 11, 15], target = 9 14 | Because nums[0] + nums[1] = 2 + 7 = 9 15 | return [0, 1] 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def twoSum(self, nums, target): 21 | """ 22 | :type nums: List[int] 23 | :type target: int 24 | :rtype: List[int] 25 | """ 26 | t = {} 27 | for i in range(len(nums)): 28 | d = target - nums[i] 29 | if d in t: 30 | return [t[d], i] 31 | else: 32 | t[nums[i]] = i 33 | -------------------------------------------------------------------------------- /QuestionBank/1051.Height Checker/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/6/28 11:06 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 高度检查器 7 | 8 | """ 9 | Question: 10 | 学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。 11 | 请你返回至少有多少个学生没有站在正确位置数量。该人数指的是:能让所有学生以 非递减 高度排列的必要移动人数。 12 | 13 | Example: 14 | 输入:[1,1,4,2,1,3] 15 | 输出:3 16 | 解释: 17 | 高度为 4、3 和最后一个 1 的学生,没有站在正确的位置。 18 | 19 | Note: 20 | 1 <= heights.length <= 100 21 | 1 <= heights[i] <= 100 22 | """ 23 | 24 | 25 | class Solution: 26 | def heightChecker(self, heights): 27 | tmp = sorted(heights) 28 | ans = 0 29 | 30 | for i, v in enumerate(heights): 31 | if v != tmp[i]: 32 | ans += 1 33 | 34 | return ans 35 | -------------------------------------------------------------------------------- /QuestionBank/11.Container With Most Water/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 给定n个非负整数,a1,a2,…an,每个表示坐标(i,ai)的点。 6 | 画出两条直线,即(i,ai)和(i,0)的两个端点,找到两条直线, 7 | 与x轴组成一个容器,求出最多能装多少水。 8 | 9 | Note: 10 | 您不能倾斜容器,n至少是2。 11 | """ 12 | 13 | class Solution(object): 14 | def maxArea(self, height): 15 | """ 16 | :type height: List[int] 17 | :rtype: int 18 | """ 19 | 20 | ans = 0 21 | left = 0 22 | l = len(height) 23 | right = l - 1 24 | while left < right: 25 | a = height[left] 26 | b = height[right] 27 | temp = min(a, b) * (right - left) 28 | if temp > ans: 29 | ans = temp 30 | if a > b: 31 | right -= 1 32 | else: 33 | left += 1 34 | 35 | return ans 36 | -------------------------------------------------------------------------------- /QuestionBank/1108.Defanging an IP Address/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/7/8 17:34 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : IP 地址无效化 7 | 8 | """ 9 | Question: 10 | 给你一个有效的 IPv4 地址 address,返回这个 IP 地址的无效化版本。 11 | 所谓无效化 IP 地址,其实就是用 "[.]" 代替了每个 "."。 12 | 13 | Example 1: 14 | 输入:address = "1.1.1.1" 15 | 输出:"1[.]1[.]1[.]1" 16 | 17 | Example 2: 18 | 输入:address = "255.100.50.0" 19 | 输出:"255[.]100[.]50[.]0" 20 | 21 | Note: 22 | 给出的 address 是一个有效的 IPv4 地址 23 | """ 24 | 25 | 26 | class Solution: 27 | def defangIPaddr(self, address): 28 | return address.replace(".", "[.]") 29 | -------------------------------------------------------------------------------- /QuestionBank/1137.N-th Tribonacci Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/8/27 16:47 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 第 N 个泰波那契数 7 | 8 | """ 9 | Question: 10 | 泰波那契序列 Tn 定义如下:  11 | T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2 12 | 给你整数 n,请返回第 n 个泰波那契数 Tn 的值。 13 | 14 | Example 1: 15 | 输入:n = 4 16 | 输出:4 17 | 解释: 18 | T_3 = 0 + 1 + 1 = 2 19 | T_4 = 1 + 1 + 2 = 4 20 | 21 | Example 2: 22 | 输入:n = 25 23 | 输出:1389537 24 | 25 | Note: 26 | 0 <= n <= 37 27 | 答案保证是一个 32 位整数,即 answer <= 2^31 - 1。 28 | """ 29 | 30 | 31 | class Solution: 32 | def tribonacci(self, n: int) -> int: 33 | tmp = [0, 1, 1] 34 | 35 | if n <= 2: 36 | return tmp[n] 37 | 38 | n -= 2 39 | 40 | while n > 0: 41 | tmp[0], tmp[1], tmp[2] = tmp[1], tmp[2], tmp[0] + tmp[1] + tmp[2] 42 | 43 | return tmp[2] 44 | -------------------------------------------------------------------------------- /QuestionBank/118.Pascal's Triangle/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 19:06 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 杨辉三角 7 | 8 | """ 9 | Question: 10 | 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 11 | 在杨辉三角中,每个数是它左上方和右上方的数的和。 12 | 13 | Example: 14 | 输入: 5 15 | 输出: 16 | [ 17 | [1], 18 | [1,1], 19 | [1,2,1], 20 | [1,3,3,1], 21 | [1,4,6,4,1] 22 | ] 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def generate(self, numRows): 28 | """ 29 | :type numRows: int 30 | :rtype: List[List[int]] 31 | """ 32 | if numRows == 0: 33 | return [] 34 | if numRows == 1: 35 | return [[1]] 36 | res = [[1]] 37 | r = [1, 1] 38 | for i in range(1, numRows): 39 | res.append(r) 40 | t = [1] 41 | for x in range(len(r) - 1): 42 | t.append(r[x] + r[x + 1]) 43 | t.append(1) 44 | r = t 45 | 46 | return res 47 | 48 | -------------------------------------------------------------------------------- /QuestionBank/1185.Day of the Week/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/9/25 12:00 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 一周中的第几天 7 | 8 | """ 9 | Question: 10 | 给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。 11 | 输入为三个整数:day、month 和 year,分别表示日、月、年。 12 | 您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}。 13 | 14 | Example 1: 15 | 输入:day = 31, month = 8, year = 2019 16 | 输出:"Saturday" 17 | 18 | Example 2: 19 | 输入:day = 18, month = 7, year = 1999 20 | 输出:"Sunday" 21 | 22 | Example 3: 23 | 输入:day = 15, month = 8, year = 1993 24 | 输出:"Sunday" 25 | 26 | Note: 27 | 给出的日期一定是在 1971 到 2100 年之间的有效日期。 28 | """ 29 | 30 | import datetime 31 | 32 | 33 | class Solution: 34 | def dayOfTheWeek(self, day: int, month: int, year: int) -> str: 35 | weekDay = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 36 | return weekDay[datetime.datetime(year, month, day).weekday()] 37 | -------------------------------------------------------------------------------- /QuestionBank/1189.Maximum Number of Balloons/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/9/25 11:36 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : “气球” 的最大数量 7 | 8 | """ 9 | Question: 10 | 给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。 11 | 字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。 12 | 13 | Example 1: 14 | 输入:text = "nlaebolko" 15 | 输出:1 16 | 17 | Example 2: 18 | 输入:text = "loonbalxballpoon" 19 | 输出:2 20 | 21 | Example 3: 22 | 输入:text = "leetcode" 23 | 输出:0 24 | 25 | Note: 26 | 1 <= text.length <= 10^4 27 | text 全部由小写英文字母组成 28 | """ 29 | 30 | 31 | class Solution: 32 | def maxNumberOfBalloons(self, text: str) -> int: 33 | tmp = {"b": 0, "a": 0, "l": 0, "o": 0, "n": 0} 34 | 35 | for v in text: 36 | if v in tmp: 37 | tmp[v] += 1 38 | 39 | tmp["l"] = tmp["l"] // 2 40 | tmp["o"] = tmp["o"] // 2 41 | 42 | ans = tmp["b"] 43 | for v in tmp.values(): 44 | if v < ans: 45 | ans = v 46 | 47 | return ans 48 | -------------------------------------------------------------------------------- /QuestionBank/119..Pascal's Triangle II/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 18:59 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 杨辉三角 II 7 | 8 | """ 9 | Question: 10 | 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 11 | 在杨辉三角中,每个数是它左上方和右上方的数的和。 12 | 13 | Example: 14 | 输入: 3 15 | 输出: [1,3,3,1] 16 | 17 | Follow up: 18 | 你可以优化你的算法到 O(k) 空间复杂度吗? 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def getRow(self, rowIndex): 24 | """ 25 | :type rowIndex: int 26 | :rtype: List[int] 27 | """ 28 | if rowIndex == 0: 29 | return [1] 30 | r = [1, 1] 31 | for i in range(1, rowIndex): 32 | t = [1] 33 | for x in range(len(r) - 1): 34 | t.append(r[x] + r[x + 1]) 35 | t.append(1) 36 | r = t 37 | 38 | return r 39 | -------------------------------------------------------------------------------- /QuestionBank/120.Triangle/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/3/27 14:22 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 三角形最小路径和 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 12 | 13 | Example, 14 | 给定三角形: 15 | [ 16 | [2], 17 | [3,4], 18 | [6,5,7], 19 | [4,1,8,3] 20 | ] 21 | 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 22 | 23 | Note: 24 | 如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。 25 | """ 26 | 27 | 28 | class Solution: 29 | def minimumTotal(self, triangle): 30 | 31 | if not triangle: 32 | return 0 33 | 34 | for row in range(len(triangle) - 1, 0, -1): 35 | for col, _ in enumerate(triangle[row - 1]): 36 | triangle[row - 1][col] += \ 37 | min(triangle[row][col], triangle[row][col + 1]) 38 | 39 | return triangle[0][0] 40 | -------------------------------------------------------------------------------- /QuestionBank/121.Best Time to Buy and Sell Stock/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/27 下午1:57 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 买卖股票的最佳时机 6 | 7 | """ 8 | Question: 9 | 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 10 | 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 11 | 注意你不能在买入股票前卖出股票。 12 | 13 | Example 1: 14 | 输入: [7,1,5,3,6,4] 15 | 输出: 5 16 | 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 17 | 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 18 | 19 | Example 2: 20 | 输入: [7,6,4,3,1] 21 | 输出: 0 22 | 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 23 | """ 24 | 25 | 26 | class Solution: 27 | def maxProfit(self, prices): 28 | """ 29 | :type prices: List[int] 30 | :rtype: int 31 | """ 32 | if not prices: 33 | return 0 34 | mi = prices[0] 35 | d = 0 36 | for i in prices[1:]: 37 | if i < mi: 38 | mi = i 39 | if i - mi > d: 40 | d = i - mi 41 | return d 42 | -------------------------------------------------------------------------------- /QuestionBank/1213.Intersection of Three Sorted Arrays/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/10/8 11:36 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 三个有序数组的交集 7 | 8 | """ 9 | Question: 10 | 给出三个均为 严格递增排列 的整数数组 arr1,arr2 和 arr3。 11 | 返回一个由 仅 在这三个数组中 同时出现 的整数所构成的有序数组。 12 | 13 | Example: 14 | 输入: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8] 15 | 输出: [1,5] 16 | 解释: 只有 1 和 5 同时在这三个数组中出现. 17 | 18 | Note: 19 | 1 <= arr1.length, arr2.length, arr3.length <= 1000 20 | 1 <= arr1[i], arr2[i], arr3[i] <= 2000 21 | """ 22 | 23 | from typing import List 24 | 25 | 26 | class Solution: 27 | def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: 28 | ans = list(set(arr1) & set(arr2) & set(arr3)) 29 | ans.sort() 30 | return ans 31 | -------------------------------------------------------------------------------- /QuestionBank/122.Best Time to Buy and Sell Stock II/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/10 下午10:22 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 买卖股票的最佳时机 6 | 7 | """ 8 | Question: 9 | 假设有一个数组,它的第 i 个元素是一个给定的股票在第 i 天的价格。 10 | 设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。 11 | 然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。 12 | """ 13 | 14 | class Solution: 15 | def maxProfit(self, prices): 16 | """ 17 | :type prices: List[int] 18 | :rtype: int 19 | """ 20 | l = len(prices) 21 | t = 0 22 | for i, v in enumerate(prices): 23 | next = i + 1 24 | if next < l and prices[next] > prices[i]: 25 | t += prices[next] - prices[i] 26 | 27 | return t 28 | -------------------------------------------------------------------------------- /QuestionBank/125.Valid Palindrome/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/4 9:53 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 验证回文字符串 7 | 8 | """ 9 | Question: 10 | 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 11 | 12 | Note: 13 | 本题中,我们将空字符串定义为有效的回文串。 14 | 15 | Example 1: 16 | 输入: "A man, a plan, a canal: Panama" 17 | 输出: true 18 | 19 | Example 2: 20 | 输入: "race a car" 21 | 输出: false 22 | """ 23 | 24 | 25 | class Solution: 26 | def isPalindrome(self, s): 27 | """ 28 | :type s: str 29 | :rtype: bool 30 | """ 31 | import re 32 | s = ''.join(re.findall(r'(\w+|\d+)', s)).lower() 33 | return s == s[::-1] 34 | -------------------------------------------------------------------------------- /QuestionBank/125.Valid Palindrome/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/4 9:53 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 验证回文字符串 7 | 8 | """ 9 | Question: 10 | 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 11 | 12 | Note: 13 | 本题中,我们将空字符串定义为有效的回文串。 14 | 15 | Example 1: 16 | 输入: "A man, a plan, a canal: Panama" 17 | 输出: true 18 | 19 | Example 2: 20 | 输入: "race a car" 21 | 输出: false 22 | """ 23 | 24 | 25 | class Solution: 26 | def isPalindrome(self, s): 27 | """ 28 | :type s: str 29 | :rtype: bool 30 | """ 31 | s = list(filter(str.isalnum, s.lower())) 32 | return s == s[::-1] 33 | -------------------------------------------------------------------------------- /QuestionBank/1281.Subtract the Product and Sum of Digits of an Integer/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/20 21:27 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 整数的各位积和之差 7 | 8 | """ 9 | 给你一个整数 n,请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。 10 | 11 | 示例 1: 12 | 输入:n = 234 13 | 输出:15 14 | 解释: 15 | 各位数之积 = 2 * 3 * 4 = 24 16 | 各位数之和 = 2 + 3 + 4 = 9 17 | 结果 = 24 - 9 = 15 18 | 19 | 示例 2: 20 | 输入:n = 4421 21 | 输出:21 22 | 解释: 23 | 各位数之积 = 4 * 4 * 2 * 1 = 32 24 | 各位数之和 = 4 + 4 + 2 + 1 = 11 25 | 结果 = 32 - 11 = 21 26 |   27 | 提示: 28 | 1 <= n <= 10^5 29 | """ 30 | 31 | 32 | class Solution: 33 | def subtractProductAndSum(self, n: int) -> int: 34 | a, b = divmod(n, 10) 35 | mul = b 36 | add = b 37 | while a > 0: 38 | a, b = divmod(a, 10) 39 | mul *= b 40 | add += b 41 | return mul - add 42 | -------------------------------------------------------------------------------- /QuestionBank/1295.Find Numbers with Even Number of Digits/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/18 18:44 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 统计位数为偶数的数字 7 | 8 | """ 9 | 给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。 10 | 11 | 示例 1: 12 | 输入:nums = [12,345,2,6,7896] 13 | 输出:2 14 | 解释: 15 | 12 是 2 位数字(位数为偶数)  16 | 345 是 3 位数字(位数为奇数)   17 | 2 是 1 位数字(位数为奇数)  18 | 6 是 1 位数字 位数为奇数)  19 | 7896 是 4 位数字(位数为偶数)   20 | 因此只有 12 和 7896 是位数为偶数的数字 21 | 22 | 示例 2: 23 | 输入:nums = [555,901,482,1771] 24 | 输出:1 25 | 解释: 26 | 只有 1771 是位数为偶数的数字。 27 | 28 | 提示: 29 | 1 <= nums.length <= 500 30 | 1 <= nums[i] <= 10^5 31 | """ 32 | 33 | from typing import List 34 | 35 | 36 | class Solution: 37 | def findNumbers(self, nums: List[int]) -> int: 38 | ans = 0 39 | for v in nums: 40 | if len(str(v)) % 2 == 0: 41 | ans += 1 42 | return ans 43 | -------------------------------------------------------------------------------- /QuestionBank/1313.Decompress Run-Length Encoded List/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/22 21:33 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 解压缩编码列表 7 | 8 | """ 9 | 给你一个以行程长度编码压缩的整数列表 nums 。 10 | 考虑每对相邻的两个元素 [freq, val] = [nums[2*i], nums[2*i+1]] (其中 i >= 0 ),每一对都表示解压后子列表中有 freq 个值为 val 的元素,你需要从左到右连接所有子列表以生成解压后的列表。 11 | 请你返回解压后的列表。 12 | 13 | 示例: 14 | 输入:nums = [1,2,3,4] 15 | 输出:[2,4,4,4] 16 | 解释:第一对 [1,2] 代表着 2 的出现频次为 1,所以生成数组 [2]。 17 | 第二对 [3,4] 代表着 4 的出现频次为 3,所以生成数组 [4,4,4]。 18 | 最后将它们串联到一起 [2] + [4,4,4] = [2,4,4,4]。 19 | 20 | 示例 2: 21 | 输入:nums = [1,1,2,3] 22 | 输出:[1,3,3] 23 | 24 | 提示: 25 | - 2 <= nums.length <= 100 26 | - nums.length % 2 == 0 27 | - 1 <= nums[i] <= 100 28 | """ 29 | 30 | from typing import List 31 | 32 | 33 | class Solution: 34 | def decompressRLElist(self, nums: List[int]) -> List[int]: 35 | ans = [] 36 | for idx in range(0, len(nums), 2): 37 | ans += [nums[idx + 1]] * nums[idx] 38 | return ans 39 | -------------------------------------------------------------------------------- /QuestionBank/136.Single Number/mehtod_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/4/17 9:42 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 只出现一次的数字 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组,除了某个元素外其余元素均出现两次。请找出这个只出现一次的元素。 11 | 12 | Note: 13 | 你的算法应该是一个线性时间复杂度。 你可以不用额外空间来实现它吗? 14 | """ 15 | 16 | class Solution: 17 | def singleNumber(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | from collections import Counter 23 | c = Counter(nums) 24 | return c.most_common()[-1][0] 25 | -------------------------------------------------------------------------------- /QuestionBank/136.Single Number/mehtod_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/4/17 9:42 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 只出现一次的数字 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组,除了某个元素外其余元素均出现两次。请找出这个只出现一次的元素。 11 | 12 | Note: 13 | 你的算法应该是一个线性时间复杂度。 你可以不用额外空间来实现它吗? 14 | """ 15 | 16 | class Solution: 17 | def singleNumber(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: int 21 | """ 22 | r = 0 23 | for i in nums: 24 | r ^= i 25 | 26 | return r 27 | -------------------------------------------------------------------------------- /QuestionBank/137.Single Number II/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/31 15:01 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 只出现一次的数字 II 7 | 8 | """ 9 | Question: 10 | 给定一个非空整数数组,除了某个元素只出现一次以外, 11 | 其余每个元素均出现了三次。找出那个只出现了一次的元素。 12 | 13 | Note 14 | 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 15 | 16 | Example 1: 17 | 输入: [2,2,3,2] 18 | 输出: 3 19 | 20 | Example 2: 21 | 输入: [0,1,0,1,0,1,99] 22 | 输出: 99 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def singleNumber(self, nums): 28 | """ 29 | :type nums: List[int] 30 | :rtype: int 31 | """ 32 | t = {i: 0 for i in nums} 33 | 34 | for i in nums: 35 | t[i] += 1 36 | 37 | for k, v in t.items(): 38 | if v == 1: 39 | return k 40 | -------------------------------------------------------------------------------- /QuestionBank/137.Single Number II/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/31 15:01 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 只出现一次的数字 II 7 | 8 | """ 9 | Question: 10 | 给定一个非空整数数组,除了某个元素只出现一次以外, 11 | 其余每个元素均出现了三次。找出那个只出现了一次的元素。 12 | 13 | Note 14 | 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 15 | 16 | Example 1: 17 | 输入: [2,2,3,2] 18 | 输出: 3 19 | 20 | Example 2: 21 | 输入: [0,1,0,1,0,1,99] 22 | 输出: 99 23 | """ 24 | 25 | 26 | class Solution(object): 27 | def singleNumber(self, nums): 28 | """ 29 | :type nums: List[int] 30 | :rtype: int 31 | """ 32 | return (3 * sum(set(nums)) - sum(nums)) // 2 33 | -------------------------------------------------------------------------------- /QuestionBank/14.Longest Common Prefix/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午1:03 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 最长公共前缀 6 | 7 | """ 8 | Question: 9 | 编写一个函数来查找字符串数组中的最长公共前缀。 10 | 如果不存在公共前缀,返回空字符串 ""。 11 | 12 | Example 1: 13 | 输入: ["flower","flow","flight"] 14 | 输出: "fl" 15 | 16 | Example 2: 17 | 输入: ["dog","racecar","car"] 18 | 输出: "" 19 | 解释: 输入不存在公共前缀。 20 | 21 | Note: 22 | 所有输入只包含小写字母 a-z 。 23 | """ 24 | 25 | 26 | class Solution: 27 | def longestCommonPrefix(self, strs): 28 | """ 29 | :type strs: List[str] 30 | :rtype: str 31 | """ 32 | t = min(strs, key=lambda x: len(x)) if strs else '' 33 | l = len(t) 34 | for i in strs: 35 | if t == i: 36 | continue 37 | for y in range(l): 38 | if t[:y + 1] != i[:y + 1]: 39 | t = '' if y == 0 else t[:y] 40 | break 41 | return t 42 | -------------------------------------------------------------------------------- /QuestionBank/144.Binary Tree Preorder Traversal/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 17:33 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 二叉树的前序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的 前序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [1,2,3] 20 | 21 | Follow up: 22 | 递归算法很简单,你可以通过迭代算法完成吗? 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution: 34 | def preorderTraversal(self, root): 35 | """ 36 | :type root: TreeNode 37 | :rtype: List[int] 38 | """ 39 | if not root: 40 | return [] 41 | r = [] 42 | r.append(root.val) 43 | r.extend(self.preorderTraversal(root.left)) 44 | r.extend(self.preorderTraversal(root.right)) 45 | return r 46 | -------------------------------------------------------------------------------- /QuestionBank/145.Binary Tree Postorder Traversal/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 17:29 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 二叉树的后序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的 后序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [3,2,1] 20 | 21 | Follow up: 22 | 递归算法很简单,你可以通过迭代算法完成吗? 23 | """ 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution: 34 | def postorderTraversal(self, root): 35 | """ 36 | :type root: TreeNode 37 | :rtype: List[int] 38 | """ 39 | if not root: 40 | return [] 41 | r = [] 42 | r.extend(self.postorderTraversal(root.left)) 43 | r.extend(self.postorderTraversal(root.right)) 44 | r.append(root.val) 45 | return r 46 | -------------------------------------------------------------------------------- /QuestionBank/1470.Shuffle the Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/14 21:13 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 重新排列数组 7 | 8 | """ 9 | Question: 10 | 给你一个数组 nums ,数组中有 2n 个元素,按 [x1,x2,...,xn,y1,y2,...,yn] 的格式排列。 11 | 请你将数组按 [x1,y1,x2,y2,...,xn,yn] 格式重新排列,返回重排后的数组。 12 | 13 | Example 1: 14 | 输入:nums = [2,5,1,3,4,7], n = 3 15 | 输出:[2,3,5,4,1,7] 16 | 解释:由于 x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 ,所以答案为 [2,3,5,4,1,7] 17 | 18 | Example 2: 19 | 输入:nums = [1,2,3,4,4,3,2,1], n = 4 20 | 输出:[1,4,2,3,3,2,4,1] 21 | 22 | Example 3: 23 | 输入:nums = [1,1,2,2], n = 2 24 | 输出:[1,2,1,2] 25 | 26 | Note: 27 | - 1 <= n <= 500 28 | - nums.length == 2n 29 | - 1 <= nums[i] <= 10^3 30 | """ 31 | 32 | from typing import List 33 | 34 | 35 | class Solution: 36 | def shuffle(self, nums: List[int], n: int) -> List[int]: 37 | ans = [] 38 | for idx in range(n): 39 | ans.append(nums[idx]) 40 | ans.append(nums[idx + n]) 41 | return ans 42 | -------------------------------------------------------------------------------- /QuestionBank/1480.Running Sum of 1d Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/14 21:00 4 | # @Author : cancan 5 | # @File : method_.py 6 | # @Function : 一维数组的动态和 7 | 8 | """ 9 | Question: 10 | 给你一个数组 nums 。数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]…nums[i]) 。 11 | 请返回 nums 的动态和。 12 | 13 | Example 1: 14 | 输入:nums = [1,2,3,4] 15 | 输出:[1,3,6,10] 16 | 解释:动态和计算过程为 [1, 1+2, 1+2+3, 1+2+3+4] 。 17 | 18 | Example 2: 19 | 输入:nums = [1,1,1,1,1] 20 | 输出:[1,2,3,4,5] 21 | 解释:动态和计算过程为 [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1] 。 22 | 23 | Example 3: 24 | 输入:nums = [3,1,2,10,1] 25 | 输出:[3,4,6,16,17] 26 | 27 | Note: 28 | 1 <= nums.length <= 1000 29 | -10^6 <= nums[i] <= 10^6 30 | """ 31 | 32 | from typing import List 33 | 34 | 35 | class Solution: 36 | def runningSum(self, nums: List[int]) -> List[int]: 37 | tmp = 0 38 | ans = [] 39 | for v in nums: 40 | tmp += v 41 | ans.append(tmp) 42 | return ans 43 | -------------------------------------------------------------------------------- /QuestionBank/1486.XOR Operation in an Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/15 20:43 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 数组异或操作 7 | 8 | """ 9 | Question: 10 | 给你两个整数,n 和 start 。 11 | 数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length 。 12 | 请返回 nums 中所有元素按位异或(XOR)后得到的结果。 13 | 14 | Example 1: 15 | 输入:n = 5, start = 0 16 | 输出:8 17 | 解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。 18 | "^" 为按位异或 XOR 运算符。 19 | 20 | Example 2: 21 | 输入:n = 4, start = 3 22 | 输出:8 23 | 解释:数组 nums 为 [3, 5, 7, 9],其中 (3 ^ 5 ^ 7 ^ 9) = 8. 24 | 25 | Example 3: 26 | 输入:n = 1, start = 7 27 | 输出:7 28 | 29 | Example 4: 30 | 输入:n = 10, start = 5 31 | 输出:2 32 | 33 | Note: 34 | - 1 <= n <= 1000 35 | - 0 <= start <= 1000 36 | - n == nums.length 37 | """ 38 | 39 | 40 | class Solution: 41 | def xorOperation(self, n: int, start: int) -> int: 42 | ans = start 43 | for v in range(1, n): 44 | ans ^= start + 2 * v 45 | return ans 46 | -------------------------------------------------------------------------------- /QuestionBank/151.Reverse Words in a String/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 18:17 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 翻转字符串里的单词 7 | 8 | """ 9 | Question: 10 | 11 | 给定一个字符串,逐个翻转字符串中的每个单词。 12 | 13 | Example: 14 | 输入: "the sky is blue", 15 | 输出: "blue is sky the". 16 | 17 | Note: 18 | 1.无空格字符构成一个单词。 19 | 2.输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 20 | 3.如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 21 | 22 | Follow up: 23 | 请选用C语言的用户尝试使用 O(1) 时间复杂度的原地解法。 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def reverseWords(self, s): 29 | """ 30 | :type s: str 31 | :rtype: str 32 | """ 33 | return ' '.join(s.split()[::-1]) 34 | -------------------------------------------------------------------------------- /QuestionBank/1512.Number of Good Pairs/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/14 20:03 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 好数对的数目 7 | 8 | """ 9 | Question: 10 | 给你一个整数数组 nums 。 11 | 如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。 12 | 返回好数对的数目。 13 | 14 | Example 1: 15 | 输入:nums = [1,2,3,1,1,3] 16 | 输出:4 17 | 解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始 18 | 19 | Example 2: 20 | 输入:nums = [1,1,1,1] 21 | 输出:6 22 | 解释:数组中的每组数字都是好数对 23 | 24 | Example 3: 25 | 输入:nums = [1,2,3] 26 | 输出:0 27 | 28 | Note 29 | 1 <= nums.length <= 100 30 | 1 <= nums[i] <= 100 31 | """ 32 | 33 | from typing import List 34 | 35 | 36 | class Solution: 37 | def numIdenticalPairs(self, nums: List[int]) -> int: 38 | tmp = {} 39 | ans = 0 40 | for v in nums: 41 | if v not in tmp: 42 | tmp[v] = 1 43 | else: 44 | ans += tmp[v] 45 | tmp[v] += 1 46 | return ans 47 | -------------------------------------------------------------------------------- /QuestionBank/152.Maximum Product Subarray/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-13 17:04 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 乘积最大子序列 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。 11 | 12 | Example 1: 13 | 输入: [2,3,-2,4] 14 | 输出: 6 15 | 解释: 子数组 [2,3] 有最大乘积 6。 16 | 17 | Example 2: 18 | 输入: [-2,0,-1] 19 | 输出: 0 20 | 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 21 | """ 22 | 23 | 24 | class Solution: 25 | def maxProduct(self, nums): 26 | if not nums: 27 | return 0 28 | 29 | res = nums[0] 30 | l = len(nums) 31 | 32 | for start in range(l): 33 | temp = nums[start] 34 | 35 | if temp > res: 36 | res = temp 37 | 38 | for end in range(start + 1, l): 39 | temp *= nums[end] 40 | 41 | if temp > res: 42 | res = temp 43 | 44 | return res 45 | -------------------------------------------------------------------------------- /QuestionBank/152.Maximum Product Subarray/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-13 17:04 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 乘积最大子序列 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。 11 | 12 | Example 1: 13 | 输入: [2,3,-2,4] 14 | 输出: 6 15 | 解释: 子数组 [2,3] 有最大乘积 6。 16 | 17 | Example 2: 18 | 输入: [-2,0,-1] 19 | 输出: 0 20 | 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。 21 | """ 22 | 23 | 24 | class Solution: 25 | def maxProduct(self, nums): 26 | if not nums: 27 | return 0 28 | mx = mn = ret = nums[0] 29 | for v in nums[1:]: 30 | mx, mn = max(v, v * mx, v * mn), min(v, v * mx, v * mn) 31 | ret = max(mx, ret) 32 | return ret 33 | -------------------------------------------------------------------------------- /QuestionBank/153.Find Minimum in Rotated Sorted Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/11/29 18:18 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 寻找旋转排序数组中的最小值 7 | 8 | """ 9 | Question: 10 | 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 11 | ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 12 | 请找出其中最小的元素。 13 | 你可以假设数组中不存在重复元素。 14 | 15 | Example 1: 16 | 输入: [3,4,5,1,2] 17 | 输出: 1 18 | 19 | Example 2: 20 | 输入: [4,5,6,7,0,1,2] 21 | 输出: 0 22 | """ 23 | 24 | from typing import List 25 | 26 | 27 | class Solution: 28 | def findMin(self, nums: List[int]) -> int: 29 | return min(nums) 30 | -------------------------------------------------------------------------------- /QuestionBank/1556.Thousand Separator/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/5/7 10:11 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 千位分隔数 7 | 8 | """ 9 | 给你一个整数 n,请你每隔三位添加点(即 "." 符号)作为千位分隔符,并将结果以字符串格式返回。 10 | 11 | Example 1: 12 | 输入:n = 987 13 | 输出:"987" 14 | 15 | Example 2: 16 | 输入:n = 1234 17 | 输出:"1.234" 18 | 19 | Example 3: 20 | 输入:n = 123456789 21 | 输出:"123.456.789" 22 | 23 | Example 4: 24 | 输入:n = 0 25 | 输出:"0" 26 |   27 | Note: 28 | - 0 <= n < 2^31 29 | """ 30 | 31 | 32 | class Solution: 33 | def thousandSeparator(self, n: int) -> str: 34 | ret = '' 35 | run = True 36 | while run: 37 | a, b = divmod(n, 1000) 38 | if a == 0: 39 | run = False 40 | ret = str(b) + '.' + ret 41 | else: 42 | ret = '%03d' % b + '.' + ret 43 | n = a 44 | 45 | return ret[:-1] 46 | -------------------------------------------------------------------------------- /QuestionBank/162.Find Peak Element/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/8 17:35 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 寻找峰值 7 | 8 | """ 9 | Question: 10 | 峰值元素是指其值大于左右相邻值的元素。 11 | 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 12 | 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 13 | 你可以假设 nums[-1] = nums[n] = -∞。 14 | 15 | Example 1: 16 | 输入: nums = [1,2,3,1] 17 | 输出: 2 18 | 解释: 3 是峰值元素,你的函数应该返回其索引 2。 19 | 20 | Example 2: 21 | 输入: nums = [1,2,1,3,5,6,4] 22 | 输出: 1 或 5 23 | 解释: 你的函数可以返回索引 1,其峰值元素为 2; 24 | 或者返回索引 5, 其峰值元素为 6。 25 | 26 | Note: 27 | 你的解法应该是 O(logN) 时间复杂度的。 28 | """ 29 | 30 | 31 | class Solution: 32 | def findPeakElement(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | return nums.index(max(nums)) 38 | -------------------------------------------------------------------------------- /QuestionBank/164.Maximum Gap/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/10 11:52 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 最大间距 7 | 8 | """ 9 | Question: 10 | 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 11 | 如果数组元素个数小于 2,则返回 0。 12 | 13 | Example 1: 14 | 输入: [3,6,9,1] 15 | 输出: 3 16 | 解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。 17 | 18 | Example 2: 19 | 输入: [10] 20 | 输出: 0 21 | 解释: 数组元素个数小于 2,因此返回 0。 22 | 23 | Note: 24 | 1.你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。 25 | 2.请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。 26 | """ 27 | 28 | 29 | class Solution: 30 | def maximumGap(self, nums): 31 | """ 32 | :type nums: List[int] 33 | :rtype: int 34 | """ 35 | l = len(nums) 36 | if l < 2: 37 | return 0 38 | 39 | nums.sort() 40 | r = 0 41 | 42 | for i, v in enumerate(nums[:l - 1]): 43 | t = nums[i + 1] - v 44 | if t > r: 45 | r = t 46 | 47 | return r 48 | -------------------------------------------------------------------------------- /QuestionBank/167.Two Sum II - Input array is sorted/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/20 10:59 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 两数之和 II - 输入有序数组 7 | 8 | """ 9 | Question: 10 | 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 11 | 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 12 | 13 | NOte: 14 | 1.返回的下标值(index1 和 index2)不是从零开始的。 15 | 2.你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 16 | 17 | Example: 18 | 输入: numbers = [2, 7, 11, 15], target = 9 19 | 输出: [1,2] 20 | 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def twoSum(self, numbers, target): 26 | """ 27 | :type numbers: List[int] 28 | :type target: int 29 | :rtype: List[int] 30 | """ 31 | t = {} 32 | for i, v in enumerate(numbers): 33 | if v in t: 34 | return [t[v] + 1, i + 1] 35 | else: 36 | t[target - v] = i 37 | -------------------------------------------------------------------------------- /QuestionBank/168.Excel Sheet Column Title/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/3/19 16:08 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : Excel表列名称 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个正整数,返回它在 Excel 表中相对应的列名称。 12 | 13 | Exmpale, 14 | 1 -> A 15 | 2 -> B 16 | 3 -> C 17 | ... 18 | 26 -> Z 19 | 27 -> AA 20 | 28 -> AB 21 | ... 22 | 23 | Example 1: 24 | 输入: 1 25 | 输出: "A" 26 | 27 | Example 2: 28 | 输入: 28 29 | 输出: "AB" 30 | 31 | Example 3: 32 | 输入: 701 33 | 输出: "ZY" 34 | """ 35 | 36 | from string import ascii_uppercase 37 | 38 | class Solution: 39 | def convertToTitle(self, n: int) -> str: 40 | r = '' 41 | 42 | while n: 43 | n -= 1 44 | a, b = divmod(n, 26) 45 | r = ascii_uppercase[b] + r 46 | n = a 47 | 48 | return r 49 | -------------------------------------------------------------------------------- /QuestionBank/169.Majority Element/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/1 14:49 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 求众数 7 | 8 | """ 9 | Question: 10 | 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 11 | 你可以假设数组是非空的,并且给定的数组总是存在众数。 12 | 13 | Example 1: 14 | 输入: [3,2,3] 15 | 输出: 3 16 | 17 | Example 2: 18 | 输入: [2,2,1,1,1,2,2] 19 | 输出: 2 20 | """ 21 | 22 | 23 | class Solution: 24 | def majorityElement(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | 30 | d = len(nums) / 2 31 | 32 | for i in set(nums): 33 | if nums.count(i) > d: 34 | return i 35 | -------------------------------------------------------------------------------- /QuestionBank/169.Majority Element/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/1 14:49 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 求众数 7 | 8 | """ 9 | Question: 10 | 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 11 | 你可以假设数组是非空的,并且给定的数组总是存在众数。 12 | 13 | Example 1: 14 | 输入: [3,2,3] 15 | 输出: 3 16 | 17 | Example 2: 18 | 输入: [2,2,1,1,1,2,2] 19 | 输出: 2 20 | """ 21 | 22 | 23 | class Solution: 24 | def majorityElement(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | from collections import defaultdict 30 | 31 | d = len(nums) / 2 32 | t = defaultdict(int) 33 | 34 | for i in nums: 35 | t[i] += 1 36 | if t[i] > d: 37 | return i 38 | 39 | -------------------------------------------------------------------------------- /QuestionBank/169.Majority Element/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/1 14:49 4 | # @Author : cancan 5 | # @File : method_3.py 6 | # @Function : 求众数 7 | 8 | """ 9 | Question: 10 | 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 11 | 你可以假设数组是非空的,并且给定的数组总是存在众数。 12 | 13 | Example 1: 14 | 输入: [3,2,3] 15 | 输出: 3 16 | 17 | Example 2: 18 | 输入: [2,2,1,1,1,2,2] 19 | 输出: 2 20 | """ 21 | 22 | 23 | class Solution: 24 | def majorityElement(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | from collections import Counter 30 | return Counter(nums).most_common()[0][0] 31 | 32 | -------------------------------------------------------------------------------- /QuestionBank/171.Excel Sheet Column Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-19 16:24 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : Excel表列序号 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个Excel表格中的列名称,返回其相应的列序号。 12 | 13 | Example, 14 | A -> 1 15 | B -> 2 16 | C -> 3 17 | ... 18 | Z -> 26 19 | AA -> 27 20 | AB -> 28 21 | ... 22 | 23 | Example 1: 24 | 输入: "A" 25 | 输出: 1 26 | 27 | Example 2: 28 | 输入: "AB" 29 | 输出: 28 30 | 31 | Example 3: 32 | 输入: "ZY" 33 | 输出: 701 34 | """ 35 | 36 | from string import ascii_uppercase 37 | 38 | 39 | class Solution: 40 | def titleToNumber(self, s: str) -> int: 41 | d = {v: i + 1 for i, v in enumerate(ascii_uppercase)} 42 | 43 | r = 0 44 | 45 | for i, v in enumerate(s[::-1]): 46 | r += 26 ** i * d[v] 47 | 48 | return r 49 | -------------------------------------------------------------------------------- /QuestionBank/172.Factorial Trailing Zeroes/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-05 22:05 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 阶乘后的零 7 | 8 | """ 9 | Question: 10 | 给定一个整数 n,返回 n! 结果尾数中零的数量。 11 | 12 | Example 1: 13 | 输入: 3 14 | 输出: 0 15 | 解释: 3! = 6, 尾数中没有零。 16 | 17 | Example 2: 18 | 输入: 5 19 | 输出: 1 20 | 解释: 5! = 120, 尾数中有 1 个零. 21 | 22 | Note: 23 | 你算法的时间复杂度应为 O(log n) 。 24 | """ 25 | 26 | 27 | class Solution: 28 | def trailingZeroes(self, n: int) -> int: 29 | total = 0 30 | while n > 4: 31 | n //= 5 32 | total += n 33 | return total 34 | -------------------------------------------------------------------------------- /QuestionBank/1748.Sum of Unique Elements/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/5/7 10:05 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 唯一元素的和 7 | 8 | """ 9 | 给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。 10 | 请你返回 nums 中唯一元素的 和 。 11 | 12 | Example 1: 13 | 输入:nums = [1,2,3,2] 14 | 输出:4 15 | 解释:唯一元素为 [1,3] ,和为 4 。 16 | 17 | Example 2: 18 | 输入:nums = [1,1,1,1,1] 19 | 输出:0 20 | 解释:没有唯一元素,和为 0 。 21 | 22 | Example 3 : 23 | 输入:nums = [1,2,3,4,5] 24 | 输出:15 25 | 解释:唯一元素为 [1,2,3,4,5] ,和为 15 。 26 | 27 | 提示: 28 | - 1 <= nums.length <= 100 29 | - 1 <= nums[i] <= 100 30 | """ 31 | 32 | 33 | class Solution: 34 | def sumOfUnique(self, nums: List[int]) -> int: 35 | ret = 0 36 | tmp = {} 37 | for v in nums: 38 | if v not in tmp: 39 | ret += v 40 | tmp[v] = 1 41 | else: 42 | if tmp[v] == 1: 43 | ret -= v 44 | tmp[v] = -1 45 | return ret 46 | -------------------------------------------------------------------------------- /QuestionBank/1784.Check if Binary String Has at Most One Segment of Ones/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/5/7 10:01 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 查二进制字符串字段 7 | 8 | """ 9 | 给你一个二进制字符串 s ,该字符串 不含前导零 。 10 | 如果 s 包含 零个或一个由连续的 '1' 组成的字段 ,返回 true​​​ 。否则,返回 false 。 11 | 12 | Example 1: 13 | 输入:s = "1001" 14 | 输出:false 15 | 解释:字符串中的 1 没有形成一个连续字段。 16 | 17 | Example 2: 18 | 输入:s = "110" 19 | 输出:true 20 |   21 | Note: 22 | - 1 <= s.length <= 100 23 | - s[i]​​​​ 为 '0' 或 '1' 24 | - s[0] 为 '1' 25 | """ 26 | 27 | 28 | class Solution: 29 | def checkOnesSegment(self, s: str) -> bool: 30 | idx1 = -1 31 | for idx, v in enumerate(s): 32 | if v == '1': 33 | if idx == -1: 34 | idx1 = idx 35 | else: 36 | if idx - idx1 != 1: 37 | return False 38 | else: 39 | idx1 = idx 40 | 41 | return True 42 | -------------------------------------------------------------------------------- /QuestionBank/189.Rotate Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/7 下午10:52 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 旋转数据 6 | 7 | """ 8 | Question: 9 | 将包含 n 个元素的数组向右旋转 k 步。 10 | 11 | Example: 12 | 如果n = 7,k = 3,给定数组[1,2,3,4,5,6,7],向右旋转后的结果为[5,6,7,1,2,3,4]。 13 | 14 | Note: 15 | 尽可能找到更多的解决方案,这里最少有三种不同的方法解决这个问题。 16 | """ 17 | 18 | 19 | class Solution: 20 | def rotate(self, nums, k): 21 | """ 22 | :type nums: List[int] 23 | :type k: int 24 | :rtype: void Do not return anything, modify nums in-place instead. 25 | """ 26 | a = list(reversed(nums)) 27 | for _ in range(k): 28 | b = a[0] 29 | del a[0] 30 | a.append(b) 31 | 32 | nums.clear() 33 | nums.extend(list(reversed(a))) 34 | -------------------------------------------------------------------------------- /QuestionBank/189.Rotate Array/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/7 下午10:52 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 旋转数据 6 | 7 | """ 8 | Question: 9 | 将包含 n 个元素的数组向右旋转 k 步。 10 | 11 | Example: 12 | 如果n = 7,k = 3,给定数组[1,2,3,4,5,6,7],向右旋转后的结果为[5,6,7,1,2,3,4]。 13 | 14 | Note: 15 | 尽可能找到更多的解决方案,这里最少有三种不同的方法解决这个问题。 16 | """ 17 | 18 | 19 | class Solution: 20 | def rotate(self, nums, k): 21 | """ 22 | :type nums: List[int] 23 | :type k: int 24 | :rtype: void Do not return anything, modify nums in-place instead. 25 | """ 26 | l = len(nums) 27 | nums[:k], nums[k: l] = nums[l-k: l], nums[: l-k] 28 | -------------------------------------------------------------------------------- /QuestionBank/190.Reverse Bits/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/26 11:27 4 | # @Author : cancan 5 | # @File : method_3.py 6 | # @Function : 颠倒二进制位 7 | 8 | """ 9 | Question: 10 | 颠倒给定的 32 位无符号整数的二进制位。 11 | 12 | Example: 13 | 输入: 43261596 14 | 输出: 964176192 15 | 解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 , 16 | 返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。 17 | 18 | Follow up: 19 | 如果多次调用这个函数,你将如何优化你的算法? 20 | """ 21 | 22 | 23 | class Solution: 24 | # @param n, an integer 25 | # @return an integer 26 | def reverseBits(self, n): 27 | return int('{0:032}'.format(int(bin(n)[2:]))[::-1], 2) 28 | -------------------------------------------------------------------------------- /QuestionBank/191.Number of 1 Bits/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/5 18:07 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 位1的个数 7 | 8 | """ 9 | Question: 10 | 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 11 | 12 | Example 1: 13 | 输入: 11 14 | 输出: 3 15 | 解释: 整数 11 的二进制表示为 00000000000000000000000000001011 16 | 17 | Example 2: 18 | 输入: 128 19 | 输出: 1 20 | 解释: 整数 128 的二进制表示为 00000000000000000000000010000000 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def hammingWeight(self, n): 26 | """ 27 | :type n: int 28 | :rtype: int 29 | """ 30 | return bin(n).count('1') 31 | -------------------------------------------------------------------------------- /QuestionBank/202.Happy Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/9/19 21:05 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 快乐数 7 | 8 | """ 9 | Question: 10 | 编写一个算法来判断一个数是不是“快乐数”。 11 | 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和, 12 | 然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。 13 | 14 | Example: 15 | 输入: 19 16 | 输出: true 17 | 解释: 18 | 12 + 92 = 82 19 | 82 + 22 = 68 20 | 62 + 82 = 100 21 | 12 + 02 + 02 = 1 22 | """ 23 | 24 | 25 | class Solution: 26 | def isHappy(self, n): 27 | """ 28 | :type n: int 29 | :rtype: bool 30 | """ 31 | 32 | d = [] 33 | 34 | while 1: 35 | d.append(n) 36 | n = str(n) 37 | t = 0 38 | for i in n: 39 | t += int(i) ** 2 40 | if t == 1: 41 | return True 42 | n = t 43 | if n in d: 44 | return False 45 | -------------------------------------------------------------------------------- /QuestionBank/204.Count Primes/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/25 15:19 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 计数质数 7 | 8 | """ 9 | Question: 10 | 统计所有小于非负整数 n 的质数的数量。 11 | 12 | Example: 13 | 输入: 10 14 | 输出: 4 15 | 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 16 | """ 17 | 18 | 19 | class Solution: 20 | def countPrimes(self, n): 21 | """ 22 | :type n: int 23 | :rtype: int 24 | """ 25 | if n < 3: 26 | return 0 27 | 28 | if n < 3: 29 | return 0 30 | 31 | digits = [1] * n 32 | digits[0] = digits[1] = 0 33 | 34 | for i in range(2, int(n ** 0.5) + 1): 35 | if digits[i] == 1: 36 | for j in range(i + i, n, i): 37 | digits[j] = 0 38 | 39 | return sum(digits) 40 | -------------------------------------------------------------------------------- /QuestionBank/205.Isomorphic Strings/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-19 16:45 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 同构字符串 7 | 8 | 9 | """ 10 | Question: 11 | 给定两个字符串 s 和 t,判断它们是否是同构的。 12 | 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。 13 | 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。 14 | 15 | Example 1: 16 | 输入: s = "egg", t = "add" 17 | 输出: true 18 | 19 | Example 2: 20 | 输入: s = "foo", t = "bar" 21 | 输出: false 22 | 23 | Example 3: 24 | 输入: s = "paper", t = "title" 25 | 输出: true 26 | 27 | Note: 28 | 你可以假设 s 和 t 具有相同的长度。 29 | """ 30 | 31 | 32 | class Solution: 33 | def isIsomorphic(self, s: str, t: str) -> bool: 34 | 35 | for i, v in enumerate(s): 36 | if s.index(v) != t.index(t[i]): 37 | return False 38 | 39 | return True 40 | -------------------------------------------------------------------------------- /QuestionBank/206.Reverse Linked List/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午3:06 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 反转链表 6 | 7 | """ 8 | Question: 9 | 反转一个单链表。 10 | 11 | Example: 12 | 输入: 1->2->3->4->5->NULL 13 | 输出: 5->4->3->2->1->NULL 14 | 15 | Follow up: 16 | 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? 17 | """ 18 | 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode(object): 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.next = None 25 | 26 | class Solution(object): 27 | def reverseList(self, head): 28 | """ 29 | :type head: ListNode 30 | :rtype: ListNode 31 | """ 32 | if not head or not head.next: 33 | return head 34 | 35 | def f(node, pre): 36 | t = node.next 37 | node.next = pre 38 | if not t: 39 | return node 40 | else: 41 | return f(t, node) 42 | 43 | return f(head, None) 44 | -------------------------------------------------------------------------------- /QuestionBank/206.Reverse Linked List/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午3:06 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 反转链表 6 | 7 | """ 8 | Question: 9 | 反转一个单链表。 10 | 11 | Example: 12 | 输入: 1->2->3->4->5->NULL 13 | 输出: 5->4->3->2->1->NULL 14 | 15 | Follow up: 16 | 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? 17 | """ 18 | 19 | 20 | # Definition for singly-linked list. 21 | # class ListNode(object): 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.next = None 25 | 26 | class Solution(object): 27 | def reverseList(self, head): 28 | """ 29 | :type head: ListNode 30 | :rtype: ListNode 31 | """ 32 | if not head or not head.next: 33 | return head 34 | 35 | pre = None 36 | 37 | while head: 38 | tmp = head.next 39 | head.next = pre 40 | pre = head 41 | head = tmp 42 | 43 | return pre 44 | -------------------------------------------------------------------------------- /QuestionBank/215.Kth Largest Element in an Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/3 17:53 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 数组中的第K个最大元素 7 | 8 | """ 9 | Question: 10 | 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 11 | 12 | Example 1: 13 | 输入: [3,2,1,5,6,4] 和 k = 2 14 | 输出: 5 15 | 16 | Example 2: 17 | 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 18 | 输出: 4 19 | 20 | Note: 21 | 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def findKthLargest(self, nums, k): 27 | """ 28 | :type nums: List[int] 29 | :type k: int 30 | :rtype: int 31 | """ 32 | return sorted(nums)[-k] 33 | -------------------------------------------------------------------------------- /QuestionBank/217.Contains Duplicate/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/10 下午10:22 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 存在重复 6 | 7 | """ 8 | Question: 9 | 给定一个整数数组,判断是否存在重复元素。 10 | 如果任何值在数组中出现至少两次,函数应该返回 true。如果每个元素都不相同,则返回 false。 11 | """ 12 | 13 | 14 | class Solution: 15 | def containsDuplicate(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: bool 19 | """ 20 | return len(set(nums)) != len(nums) 21 | -------------------------------------------------------------------------------- /QuestionBank/219.Contains Duplicate II/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-19 16:57 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 存在重复元素 II 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j, 12 | 使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。 13 | 14 | Example 1: 15 | 输入: nums = [1,2,3,1], k = 3 16 | 输出: true 17 | 18 | Example 2: 19 | 输入: nums = [1,0,1,1], k = 1 20 | 输出: true 21 | 22 | Example 3: 23 | 输入: nums = [1,2,3,1,2,3], k = 2 24 | 输出: false 25 | """ 26 | 27 | 28 | class Solution: 29 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 30 | 31 | t = {} 32 | 33 | for i, v in enumerate(nums): 34 | if v in t: 35 | if i - t[v] <= k: 36 | return True 37 | else: 38 | t[v] = i 39 | else: 40 | t[v] = i 41 | 42 | return False 43 | -------------------------------------------------------------------------------- /QuestionBank/22.Generate Parentheses/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/4/10 9:42 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 括号生成 7 | 8 | 9 | """ 10 | Question: 11 | 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 12 | 13 | Example,给出 n = 3,生成结果为: 14 | [ 15 | "((()))", 16 | "(()())", 17 | "(())()", 18 | "()(())", 19 | "()()()" 20 | ] 21 | """ 22 | 23 | 24 | class Solution: 25 | def generateParenthesis(self, n): 26 | ans = [] 27 | 28 | def dfs(s='', left=0, right=0): 29 | if len(s) == 2 * n: 30 | ans.append(s) 31 | 32 | if left < n: 33 | dfs(s + '(', left + 1, right) 34 | 35 | if right < left: 36 | dfs(s + ')', left, right + 1) 37 | 38 | dfs() 39 | 40 | return ans 41 | -------------------------------------------------------------------------------- /QuestionBank/231.Power of Two/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/15 下午1:39 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 2的幂 6 | 7 | """ 8 | Question: 9 | 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 10 | 11 | Example 1: 12 | 输入: 1 13 | 输出: true 14 | 解释: 20 = 1 15 | 16 | Example 2: 17 | 输入: 16 18 | 输出: true 19 | 解释: 24 = 16 20 | 21 | Example 3: 22 | 输入: 218 23 | 输出: false 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def isPowerOfTwo(self, n): 29 | """ 30 | :type n: int 31 | :rtype: bool 32 | """ 33 | if n == 0: 34 | return False 35 | while True: 36 | if n == 1: 37 | return True 38 | if n % 2 == 0: 39 | n = n // 2 40 | else: 41 | return False 42 | -------------------------------------------------------------------------------- /QuestionBank/234.Palindrome Linked List/mehtod_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午7:28 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 回文链表 6 | 7 | """ 8 | Question: 9 | 请检查一个链表是否为回文链表。 10 | 11 | Follow up: 12 | 你能在 O(n) 的时间和 O(1) 的额外空间中做到吗 13 | """ 14 | 15 | 16 | # Definition for singly-linked list. 17 | # class ListNode(object): 18 | # def __init__(self, x): 19 | # self.val = x 20 | # self.next = None 21 | 22 | class Solution(object): 23 | def isPalindrome(self, head): 24 | """ 25 | :type head: ListNode 26 | :rtype: bool 27 | """ 28 | if not head: 29 | return True 30 | t = [head.val] 31 | n = head.next 32 | while n: 33 | t.append(n.val) 34 | n = n.next 35 | 36 | l = len(t) 37 | i = l // 2 38 | if l % 2 == 0: 39 | return t[:i] == t[i:][::-1] 40 | else: 41 | return t[:i] == t[i + 1:][::-1] 42 | -------------------------------------------------------------------------------- /QuestionBank/237.Delete Node in a Linked List/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 下午1:30 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 删除链表的结点 6 | 7 | """ 8 | Question: 9 | 请编写一个函数,使其可以删除某个链表中给定的(非末尾的)节点,您将只被给予要求被删除的节点。 10 | 比如:假设该链表为 1 -> 2 -> 3 -> 4 ,给定您的为该链表中值为 3 的第三个节点, 11 | 那么在调用了您的函数之后,该链表则应变成 1 -> 2 -> 4 。 12 | """ 13 | 14 | 15 | # Definition for singly-linked list. 16 | # class ListNode(object): 17 | # def __init__(self, x): 18 | # self.val = x 19 | # self.next = None 20 | 21 | 22 | class Solution(object): 23 | def deleteNode(self, node): 24 | """ 25 | :type node: ListNode 26 | :rtype: void Do not return anything, modify node in-place instead. 27 | """ 28 | node.val = node.next.val 29 | node.next = node.next.next 30 | -------------------------------------------------------------------------------- /QuestionBank/238.Product of Array Except Self/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-14 15:35 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 除自身以外数组的乘积 7 | 8 | 9 | """ 10 | Question: 11 | 给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output , 12 | 其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。 13 | 14 | Example: 15 | 输入: [1,2,3,4] 16 | 输出: [24,12,8,6] 17 | 18 | Note: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 19 | 20 | Follow up: 21 | 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。) 22 | """ 23 | 24 | 25 | class Solution: 26 | def productExceptSelf(self, nums: list[int]) -> list[int]: 27 | t = {} 28 | res = [] 29 | 30 | for i, v in enumerate(nums): 31 | if v in t: 32 | res.append(t[v]) 33 | else: 34 | p = 1 35 | for j in nums[:i]: 36 | p *= j 37 | for j in nums[i + 1:]: 38 | p *= j 39 | 40 | t[v] = p 41 | 42 | res.append(p) 43 | 44 | return res 45 | -------------------------------------------------------------------------------- /QuestionBank/240.Search a 2D Matrix II/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/8 18:16 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 搜索二维矩阵 II 7 | 8 | """ 9 | Question: 10 | 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: 11 | 1.每行的元素从左到右升序排列。 12 | 2.每列的元素从上到下升序排列。 13 | 14 | Example: 15 | 现有矩阵 matrix 如下: 16 | [ 17 | [1, 4, 7, 11, 15], 18 | [2, 5, 8, 12, 19], 19 | [3, 6, 9, 16, 22], 20 | [10, 13, 14, 17, 24], 21 | [18, 21, 23, 26, 30] 22 | ] 23 | 给定 target = 5,返回 true。 24 | 给定 target = 20,返回 false。 25 | """ 26 | 27 | 28 | class Solution: 29 | def searchMatrix(self, matrix, target): 30 | """ 31 | :type matrix: List[List[int]] 32 | :type target: int 33 | :rtype: bool 34 | """ 35 | for item in matrix: 36 | if target in item: 37 | return True 38 | return False 39 | -------------------------------------------------------------------------------- /QuestionBank/2481.Minimum Cuts to Divide a Circle/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/12/30 17:28 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 分割圆的最少切割次数 7 | 8 | """ 9 | 圆内一个 有效切割 ,符合以下二者之一: 10 | 该切割是两个端点在圆上的线段,且该线段经过圆心。 11 | 该切割是一端在圆心另一端在圆上的线段。 12 | 一些有效和无效的切割如下图所示。 13 | 给你一个整数 n ,请你返回将圆切割成相等的 n 等分的 最少 切割次数。 14 | 15 | 示例 1: 16 | 输入:n = 4 17 | 输出:2 18 | 解释: 19 | 上图展示了切割圆 2 次,得到四等分。 20 | 21 | 示例 2: 22 | 输入:n = 3 23 | 输出:3 24 | 解释: 25 | 最少需要切割 3 次,将圆切成三等分。 26 | 少于 3 次切割无法将圆切成大小相等面积相同的 3 等分。 27 | 同时可以观察到,第一次切割无法将圆切割开。 28 | 29 | 提示: 30 | 1 <= n <= 100 31 | """ 32 | 33 | 34 | class Solution: 35 | def numberOfCuts(self, n: int) -> int: 36 | if n <= 1: 37 | return 0 38 | return n // 2 if n % 2 == 0 else n 39 | -------------------------------------------------------------------------------- /QuestionBank/258.Add Digits/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/1 下午12:05 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 各位相加 6 | 7 | """ 8 | Question: 9 | 给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。 10 | 11 | Example: 12 | 输入: 38 13 | 输出: 2 14 | 解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。 15 | 16 | Follow up: 17 | 你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗? 18 | """ 19 | 20 | 21 | class Solution: 22 | def addDigits(self, num): 23 | """ 24 | :type num: int 25 | :rtype: int 26 | """ 27 | return self.foo(num) 28 | 29 | def foo(self, num): 30 | if num < 10: 31 | return num 32 | else: 33 | s = str(num) 34 | return self.foo(sum([int(_) for _ in s])) 35 | -------------------------------------------------------------------------------- /QuestionBank/26.Remove Duplicates from Sorted Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/7 下午10:52 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 从排序数组中删除重复项 6 | 7 | """ 8 | Question: 9 | 给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。 10 | 不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。 11 | 12 | Example: 13 | 给定数组: nums = [1,1,2], 14 | 你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2 15 | 不需要理会新的数组长度后面的元素 16 | """ 17 | 18 | 19 | class Solution: 20 | def removeDuplicates(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: int 24 | """ 25 | a = [] 26 | d = [] 27 | for i, v in enumerate(nums): 28 | if v not in a: 29 | a.append(v) 30 | else: 31 | d.append(i) 32 | 33 | for i in sorted(d, reverse=True): 34 | del nums[i] 35 | 36 | return len(nums) 37 | -------------------------------------------------------------------------------- /QuestionBank/26.Remove Duplicates from Sorted Array/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/7 下午10:52 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 从排序数组中删除重复项 6 | 7 | """ 8 | Question: 9 | 给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。 10 | 不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。 11 | 12 | Example: 13 | 给定数组: nums = [1,1,2], 14 | 你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2 15 | 不需要理会新的数组长度后面的元素 16 | """ 17 | 18 | 19 | class Solution: 20 | def removeDuplicates(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: int 24 | """ 25 | a = nums.copy() 26 | nums.clear() 27 | nums.extend(sorted(list(set(a)), reverse=False)) 28 | return len(nums) 29 | -------------------------------------------------------------------------------- /QuestionBank/260.Single Number III/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/10 10:48 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 只出现一次的数字 III 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。 11 | 12 | Example: 13 | 输入: [1,2,1,3,2,5] 14 | 输出: [3,5] 15 | 16 | Note: 17 | 1.结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。 18 | 2.你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现? 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def singleNumber(self, nums): 24 | """ 25 | :type nums: List[int] 26 | :rtype: List[int] 27 | """ 28 | t = {} 29 | for i in nums: 30 | if i in t: 31 | t[i] += 1 32 | else: 33 | t[i] = 1 34 | 35 | return [k for k, v in t.items() if v == 1] 36 | -------------------------------------------------------------------------------- /QuestionBank/268.Missing Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/28 下午2:08 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 缺失数字 6 | 7 | """ 8 | Question: 9 | 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。 10 | 11 | Example 1: 12 | 输入: [3,0,1] 13 | 输出: 2 14 | 15 | Example 2: 16 | 输入: [9,6,4,2,3,5,7,0,1] 17 | 输出: 8 18 | 19 | Note: 20 | 你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现? 21 | """ 22 | 23 | 24 | class Solution: 25 | def missingNumber(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | nums.sort() 31 | 32 | if nums[0] != 0: 33 | return 0 34 | 35 | for i in range(len(nums) - 1): 36 | if nums[i + 1] - nums[i] != 1: 37 | return nums[i] + 1 38 | 39 | return nums[-1] + 1 40 | -------------------------------------------------------------------------------- /QuestionBank/268.Missing Number/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/28 下午2:08 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 缺失数字 6 | 7 | """ 8 | Question: 9 | 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。 10 | 11 | Example 1: 12 | 输入: [3,0,1] 13 | 输出: 2 14 | 15 | Example 2: 16 | 输入: [9,6,4,2,3,5,7,0,1] 17 | 输出: 8 18 | 19 | Note: 20 | 你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现? 21 | """ 22 | 23 | 24 | class Solution: 25 | def missingNumber(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | return len(nums) * (1 + len(nums)) // 2 - sum(nums) 31 | -------------------------------------------------------------------------------- /QuestionBank/27.Remove Element/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/20 10:59 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 移除元素 7 | 8 | """ 9 | Question: 10 | 给定一个数组和一个值,删除该值的所有实例并返回新的长度。 11 | 不要为另一个数组分配额外的空间,您必须在固定内存的情况下这样做。 12 | 元素的顺序可以更改。不管你留了多少新长度。 13 | 14 | Example: 15 | 给定一个数组和值 nums = [3,2,2,3], val = 3 16 | 您的函数应该返回length = 2,而nums的前两个元素为2。 17 | """ 18 | 19 | class Solution(object): 20 | def removeElement(self, nums, val): 21 | """ 22 | :type nums: List[int] 23 | :type val: int 24 | :rtype: int 25 | """ 26 | while 1: 27 | try: 28 | nums.pop(nums.index(val)) 29 | except: 30 | return len(nums) -------------------------------------------------------------------------------- /QuestionBank/27.Remove Element/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/20 10:59 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 移除元素 7 | 8 | """ 9 | Question: 10 | 给定一个数组和一个值,删除该值的所有实例并返回新的长度。 11 | 不要为另一个数组分配额外的空间,您必须在固定内存的情况下这样做。 12 | 元素的顺序可以更改。不管你留了多少新长度。 13 | 14 | Example: 15 | 给定一个数组和值 nums = [3,2,2,3], val = 3 16 | 您的函数应该返回length = 2,而nums的前两个元素为2。 17 | """ 18 | 19 | class Solution(object): 20 | def removeElement(self, nums, val): 21 | """ 22 | :type nums: List[int] 23 | :type val: int 24 | :rtype: int 25 | """ 26 | l = len(nums) 27 | d = 0 28 | for i in range(l): 29 | if nums[i - d] == val: 30 | del nums[i - d] 31 | d += 1 -------------------------------------------------------------------------------- /QuestionBank/27.Remove Element/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/20 10:59 4 | # @Author : cancan 5 | # @File : method_3.py 6 | # @Function : 移除元素 7 | 8 | """ 9 | Question: 10 | 给定一个数组和一个值,删除该值的所有实例并返回新的长度。 11 | 不要为另一个数组分配额外的空间,您必须在固定内存的情况下这样做。 12 | 元素的顺序可以更改。不管你留了多少新长度。 13 | 14 | Example: 15 | 给定一个数组和值 nums = [3,2,2,3], val = 3 16 | 您的函数应该返回length = 2,而nums的前两个元素为2。 17 | """ 18 | 19 | 20 | class Solution: 21 | def removeElement(self, nums, val): 22 | l = len(nums) 23 | s = 0 24 | 25 | while s < l: 26 | if nums[s] == val: 27 | del nums[s] 28 | l -= 1 29 | else: 30 | s += 1 31 | -------------------------------------------------------------------------------- /QuestionBank/28.Implement strStr()/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/5 上午11:11 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 实现strStr() 6 | 7 | """ 8 | Question: 9 | 实现 strStr() 函数。 10 | 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 11 | 12 | Example 1: 13 | 输入: haystack = "hello", needle = "ll" 14 | 输出: 2 15 | 16 | Example 2: 17 | 输入: haystack = "aaaaa", needle = "bba" 18 | 输出: -1 19 | 20 | Note: 21 | 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 22 | 对于本题而言,当 needle 是空字符串时我们应当返回 0 。 23 | 这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 24 | """ 25 | 26 | 27 | class Solution: 28 | def strStr(self, haystack, needle): 29 | """ 30 | :type haystack: str 31 | :type needle: str 32 | :rtype: int 33 | """ 34 | try: 35 | return haystack.index(needle) 36 | except ValueError: 37 | return -1 38 | -------------------------------------------------------------------------------- /QuestionBank/283.Move Zeroes/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/1 下午9:30 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 移动零 6 | 7 | """ 8 | Question: 9 | 给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。 10 | 例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。 11 | 12 | Note: 13 | 1.必须在原数组上操作,不要为一个新数组分配额外空间。 14 | 2.尽量减少操作总数。 15 | """ 16 | 17 | 18 | class Solution: 19 | def moveZeroes(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: void Do not return anything, modify nums in-place instead. 23 | """ 24 | 25 | n = [] 26 | for i, v in enumerate(nums): 27 | if v == 0: 28 | n.append(i) 29 | l = len(n) 30 | n = reversed(n) 31 | for i in n: 32 | del nums[i] 33 | 34 | nums.extend([0] * l) 35 | -------------------------------------------------------------------------------- /QuestionBank/283.Move Zeroes/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/1 下午9:30 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 移动零 6 | 7 | """ 8 | Question: 9 | 给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。 10 | 例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。 11 | 12 | Note: 13 | 1.必须在原数组上操作,不要为一个新数组分配额外空间。 14 | 2.尽量减少操作总数。 15 | """ 16 | 17 | 18 | class Solution: 19 | def moveZeroes(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: void Do not return anything, modify nums in-place instead. 23 | """ 24 | i = 0 25 | c = 0 26 | while (i < len(nums) - c): 27 | if nums[i] == 0: 28 | nums.pop(i) 29 | nums.append(0) 30 | c += 1 31 | else: 32 | i += 1 33 | -------------------------------------------------------------------------------- /QuestionBank/287.Find the Duplicate Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/10 11:09 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 寻找重复数 7 | 8 | """ 9 | Question: 10 | 给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n), 11 | 可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。 12 | 13 | Example 1: 14 | 输入: [1,3,4,2,2] 15 | 输出: 2 16 | 17 | Example 2: 18 | 输入: [3,1,3,4,2] 19 | 输出: 3 20 | 21 | Note: 22 | 1.不能更改原数组(假设数组是只读的)。 23 | 2.只能使用额外的 O(1) 的空间。 24 | 3.时间复杂度小于 O(n2) 。 25 | 4.数组中只有一个重复的数字,但它可能不止重复出现一次。 26 | """ 27 | 28 | 29 | class Solution(object): 30 | def findDuplicate(self, nums): 31 | """ 32 | :type nums: List[int] 33 | :rtype: int 34 | """ 35 | t = {} 36 | 37 | for i in nums: 38 | if i in t: 39 | return i 40 | else: 41 | t[i] = 1 42 | -------------------------------------------------------------------------------- /QuestionBank/287.Find the Duplicate Number/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/10 11:09 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 寻找重复数 7 | 8 | """ 9 | Question: 10 | 给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n), 11 | 可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。 12 | 13 | Example 1: 14 | 输入: [1,3,4,2,2] 15 | 输出: 2 16 | 17 | Example 2: 18 | 输入: [3,1,3,4,2] 19 | 输出: 3 20 | 21 | Note: 22 | 1.不能更改原数组(假设数组是只读的)。 23 | 2.只能使用额外的 O(1) 的空间。 24 | 3.时间复杂度小于 O(n2) 。 25 | 4.数组中只有一个重复的数字,但它可能不止重复出现一次。 26 | """ 27 | 28 | 29 | class Solution(object): 30 | def findDuplicate(self, nums): 31 | """ 32 | :type nums: List[int] 33 | :rtype: int 34 | """ 35 | s = set(nums) 36 | d = len(nums) - len(s) 37 | return (sum(nums) - sum(s)) // d 38 | -------------------------------------------------------------------------------- /QuestionBank/3.Longest Substring Without Repeating Characters/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # @Function : 无重复字符的最长子串 3 | 4 | """ 5 | Question: 6 | 给定一个字符串,查找没有重复字符的最长子字符串的长度。 7 | 8 | Examples: 9 | Given "abcabcbb", the answer is "abc", which the length is 3. 10 | Given "bbbbb", the answer is "b", with the length of 1. 11 | Given "pwwkew", the answer is "wke", with the length of 3. 12 | 13 | Note: 14 | 答案必须是一个子字符串,“pwke”是一个子序列,而不是子字符串。 15 | """ 16 | 17 | class Solution(object): 18 | def lengthOfLongestSubstring(self, s): 19 | """ 20 | :type s: str 21 | :rtype: int 22 | """ 23 | left = 0 24 | v_i = {} 25 | ans = 0 26 | for index, value in enumerate(s): 27 | 28 | if value in v_i and v_i[value] >= left: 29 | left = v_i[value] + 1 30 | v_i[value] = index 31 | ans = max(ans, index - left + 1) 32 | 33 | return ans 34 | -------------------------------------------------------------------------------- /QuestionBank/303.Range Sum Query - Immutable/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/14 上午10:52 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 区域和检索 - 数组不可变 6 | 7 | """ 8 | Question: 9 | 给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。 10 | 11 | Example 12 | 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() 13 | sumRange(0, 2) -> 1 14 | sumRange(2, 5) -> -1 15 | sumRange(0, 5) -> -3 16 | 17 | Note: 18 | 1.你可以假设数组不可变。 19 | 2.会多次调用 sumRange 方法。 20 | """ 21 | 22 | 23 | class NumArray: 24 | 25 | def __init__(self, nums): 26 | """ 27 | :type nums: List[int] 28 | """ 29 | self.nums = nums 30 | 31 | def sumRange(self, i, j): 32 | """ 33 | :type i: int 34 | :type j: int 35 | :rtype: int 36 | """ 37 | return sum(self.nums[i:j + 1]) 38 | 39 | # Your NumArray object will be instantiated and called as such: 40 | # obj = NumArray(nums) 41 | # param_1 = obj.sumRange(i,j) 42 | -------------------------------------------------------------------------------- /QuestionBank/326.Power of Three/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/15 下午1:44 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 3的幂 6 | 7 | """ 8 | Question: 9 | 给定一个整数,写一个函数来判断它是否是 3 的幂次方。 10 | 11 | Example 1: 12 | 输入: 27 13 | 输出: true 14 | 15 | Example 2: 16 | 输入: 0 17 | 输出: false 18 | 19 | Example 3: 20 | 输入: 9 21 | 输出: true 22 | 23 | Example 4: 24 | 输入: 45 25 | 输出: false 26 | 27 | Follow up: 28 | 你能不使用循环或者递归来完成本题吗? 29 | """ 30 | 31 | 32 | class Solution(object): 33 | def isPowerOfThree(self, n): 34 | """ 35 | :type n: int 36 | :rtype: bool 37 | """ 38 | if n == 0: 39 | return False 40 | while True: 41 | if n == 1: 42 | return True 43 | if n % 3 == 0: 44 | n = n // 3 45 | else: 46 | return False 47 | -------------------------------------------------------------------------------- /QuestionBank/33.Search in Rotated Sorted Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/8 18:05 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 搜索旋转排序数组 7 | 8 | """ 9 | Question: 10 | 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 11 | ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 12 | 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 13 | 你可以假设数组中不存在重复的元素。 14 | 你的算法时间复杂度必须是 O(log n) 级别。 15 | 16 | Example 1: 17 | 输入: nums = [4,5,6,7,0,1,2], target = 0 18 | 输出: 4 19 | 20 | Example 2: 21 | 输入: nums = [4,5,6,7,0,1,2], target = 3 22 | 输出: -1 23 | """ 24 | 25 | 26 | class Solution: 27 | def search(self, nums, target): 28 | """ 29 | :type nums: List[int] 30 | :type target: int 31 | :rtype: int 32 | """ 33 | if target not in nums: 34 | return -1 35 | return nums.index(target) 36 | -------------------------------------------------------------------------------- /QuestionBank/338.Counting Bits/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/31 15:20 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : Bit位计数 7 | 8 | """ 9 | Question: 10 | 给定一个非负整数 num。 对于范围 0 ≤ i ≤ num 中的每个数字 i ,计算其二进制数中的1的数目并将它们作为数组返回。 11 | 12 | Example 13 | 比如给定 num = 5 ,应该返回 [0,1,1,2,1,2]. 14 | 15 | Follow up: 16 | 1.给出时间复杂度为O(n * sizeof(integer)) 的解答非常容易。 但是你可以在线性时间O(n)内用一次遍历做到吗? 17 | 2.要求算法的空间复杂度为O(n)。 18 | 3.你能进一步完善解法吗? 在c ++或任何其他语言中不使用任何内置函数(如c++里的 __builtin_popcount)来执行此操作。 19 | 20 | Credits: 21 | 特别感谢 @syedee 添加此问题及所有测试用例。 22 | """ 23 | 24 | 25 | class Solution(object): 26 | def countBits(self, num): 27 | """ 28 | :type num: int 29 | :rtype: List[int] 30 | """ 31 | r = [] 32 | for i in range(num + 1): 33 | r.append(bin(i).count('1')) 34 | 35 | return r 36 | -------------------------------------------------------------------------------- /QuestionBank/34.Find First and Last Position of Element in Sorted Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/21 下午5:43 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 在排序数组中查找元素的第一个和最后一个位置 6 | 7 | """ 8 | Question: 9 | 给定一个按照升序排列的整数数组 nums,和一个目标值 target。 10 | 找出给定目标值在数组中的开始位置和结束位置。 11 | 你的算法时间复杂度必须是 O(log n) 级别。 12 | 如果数组中不存在目标值,返回 [-1, -1]。 13 | 14 | Example 1: 15 | 输入: nums = [5,7,7,8,8,10], target = 8 16 | 输出: [3,4] 17 | 18 | Example 2: 19 | 输入: nums = [5,7,7,8,8,10], target = 6 20 | 输出: [-1,-1] 21 | """ 22 | 23 | 24 | class Solution: 25 | def searchRange(self, nums, target): 26 | """ 27 | :type nums: List[int] 28 | :type target: int 29 | :rtype: List[int] 30 | """ 31 | if target not in nums: 32 | return [-1, -1] 33 | 34 | start = nums.index(target) 35 | end = start + 1 36 | l = len(nums) 37 | 38 | while end < l and nums[end] == target: 39 | end += 1 40 | 41 | end -= 1 42 | 43 | return [start, end] 44 | -------------------------------------------------------------------------------- /QuestionBank/342.Power of Four/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/15 下午1:49 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 4的幂 6 | 7 | """ 8 | Question: 9 | 给定一个整数 (32位有符整数型),请写出一个函数来检验它是否是4的幂。 10 | 11 | Example: 12 | 当 num = 16 时 ,返回 true 。 当 num = 5时,返回 false。 13 | 14 | Follow up 15 | 你能不使用循环/递归来解决这个问题吗? 16 | 17 | Credits: 18 | 特别感谢 @yukuairoy 添加这个问题并创建所有测试用例。 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def isPowerOfFour(self, num): 24 | """ 25 | :type num: int 26 | :rtype: bool 27 | """ 28 | if num == 0: 29 | return False 30 | while True: 31 | if num == 1: 32 | return True 33 | if num % 4 == 0: 34 | num = num // 4 35 | else: 36 | return False 37 | -------------------------------------------------------------------------------- /QuestionBank/342.Power of Four/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/15 下午1:54 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 4的幂 6 | 7 | """ 8 | Question: 9 | 给定一个整数 (32位有符整数型),请写出一个函数来检验它是否是4的幂。 10 | 11 | Example: 12 | 当 num = 16 时 ,返回 true 。 当 num = 5时,返回 false。 13 | 14 | Follow up 15 | 你能不使用循环/递归来解决这个问题吗? 16 | 17 | Credits: 18 | 特别感谢 @yukuairoy 添加这个问题并创建所有测试用例。 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def isPowerOfFour(self, num): 24 | """ 25 | :type num: int 26 | :rtype: bool 27 | """ 28 | num_b = bin(num)[2:] 29 | return len(num_b.replace('0', '')) == 1 and len(num_b) % 2 == 1 30 | -------------------------------------------------------------------------------- /QuestionBank/344.Reverse String/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/3 9:58 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 反转字符串 7 | 8 | """ 9 | Question: 10 | 请编写一个函数,其功能是将输入的字符串反转过来。 11 | 12 | Example: 13 | 输入:s = "hello" 14 | 返回:"olleh" 15 | """ 16 | 17 | class Solution: 18 | def reverseString(self, s): 19 | """ 20 | :type s: str 21 | :rtype: str 22 | """ 23 | return s[::-1] -------------------------------------------------------------------------------- /QuestionBank/347.Top K Frequent Elements/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/7 13:58 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 前K个高频元素 7 | 8 | """ 9 | Question: 10 | 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 11 | 12 | Example 13 | 给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]。 14 | 15 | Note 16 | 1.你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。 17 | 2.你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 18 | """ 19 | 20 | 21 | class Solution: 22 | def topKFrequent(self, nums, k): 23 | """ 24 | :type nums: List[int] 25 | :type k: int 26 | :rtype: List[int] 27 | """ 28 | t = {i: 0 for i in set(nums)} 29 | 30 | for i in nums: 31 | t[i] += 1 32 | 33 | return [i[0] for i in 34 | sorted(t.items(), key=lambda x: x[1], reverse=True)[:k]] 35 | -------------------------------------------------------------------------------- /QuestionBank/347.Top K Frequent Elements/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/7 13:58 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 前K个高频元素 7 | 8 | """ 9 | Question: 10 | 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 11 | 12 | Example 13 | 给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2]。 14 | 15 | Note 16 | 1.你可以假设给定的 k 总是合理的,1 ≤ k ≤ 数组中不相同的元素的个数。 17 | 2.你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 18 | """ 19 | 20 | from collections import Counter 21 | 22 | 23 | class Solution: 24 | def topKFrequent(self, nums, k): 25 | """ 26 | :type nums: List[int] 27 | :type k: int 28 | :rtype: List[int] 29 | """ 30 | 31 | return [i[0] for i in Counter(nums).most_common()[:k]] 32 | -------------------------------------------------------------------------------- /QuestionBank/349.Intersection of Two Arrays/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/3 17:29 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 两个数组的交集 7 | 8 | """ 9 | Question: 10 | 给定两个数组,写一个函数来计算它们的交集。 11 | 12 | Example: 13 | 给定 num1= [1, 2, 2, 1], nums2 = [2, 2], 返回 [2]. 14 | 15 | Note: 16 | 1.每个在结果中的元素必定是唯一的。 17 | 2.我们可以不考虑输出结果的顺序 18 | """ 19 | 20 | 21 | class Solution(object): 22 | def intersection(self, nums1, nums2): 23 | """ 24 | :type nums1: List[int] 25 | :type nums2: List[int] 26 | :rtype: List[int] 27 | """ 28 | return list(set(nums1) & set(nums2)) 29 | -------------------------------------------------------------------------------- /QuestionBank/35.Search Insert Position/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 给定一个排序数组和一个目标值,如果找到目标,返回索引。如果没有,则返回如果插入顺序的索引。 6 | 7 | Example: 8 | [1,3,5,6], 5 → 2 9 | [1,3,5,6], 2 → 1 10 | [1,3,5,6], 7 → 4 11 | [1,3,5,6], 0 → 0 12 | """ 13 | 14 | from bisect import bisect_left 15 | 16 | 17 | class Solution(object): 18 | def searchInsert(self, nums, target): 19 | """ 20 | :type nums: List[int] 21 | :type target: int 22 | :rtype: int 23 | """ 24 | 25 | # 第一个参数必须是排序后的列表 26 | return bisect_left(nums, target) -------------------------------------------------------------------------------- /QuestionBank/35.Search Insert Position/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 给定一个排序数组和一个目标值,如果找到目标,返回索引。如果没有,则返回如果插入顺序的索引。 6 | 7 | Example: 8 | [1,3,5,6], 5 → 2 9 | [1,3,5,6], 2 → 1 10 | [1,3,5,6], 7 → 4 11 | [1,3,5,6], 0 → 0 12 | """ 13 | 14 | class Solution(object): 15 | def searchInsert(self, nums, target): 16 | """ 17 | :type nums: List[int] 18 | :type target: int 19 | :rtype: int 20 | """ 21 | 22 | l = len(nums) 23 | mid = l / 2 24 | low = 0 25 | high = l - 1 26 | while 1: 27 | if low > high: 28 | mid += 1 29 | break 30 | if target == nums[mid]: 31 | break 32 | elif target < nums[mid]: 33 | high = mid - 1 34 | mid = (low + high) / 2 35 | else: 36 | low = mid + 1 37 | mid = (low + high) / 2 38 | 39 | return mid 40 | -------------------------------------------------------------------------------- /QuestionBank/350.Intersection of Two Arrays II/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/4/10 下午10:22 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 两个数组的交集 II 6 | 7 | """ 8 | Question: 9 | 给定两个数组,写一个方法来计算它们的交集。 10 | 11 | Example: 12 | 给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2]. 13 | 14 | Note: 15 | * 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。 16 | * 我们可以不考虑输出结果的顺序。 17 | 18 | Follow up: 19 | * 如果给定的数组已经排好序呢?你将如何优化你的算法? 20 | * 如果 nums1 的大小比 nums2 小很多,哪种方法更优? 21 | * 如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办? 22 | """ 23 | 24 | 25 | class Solution: 26 | def intersect(self, nums1, nums2): 27 | """ 28 | :type nums1: List[int] 29 | :type nums2: List[int] 30 | :rtype: List[int] 31 | """ 32 | 33 | # 使用Python内置的Counter方法 34 | from collections import Counter 35 | 36 | return list((Counter(nums1)&Counter(nums2)).elements()) 37 | -------------------------------------------------------------------------------- /QuestionBank/367.Valid Perfect Square/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/5/7 10:27 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 有效的完全平方数 7 | 8 | """ 9 | 给定一个 正整数 num ,编写一个函数,如果 num 是一个完全平方数,则返回 true ,否则返回 false 。 10 | 进阶:不要 使用任何内置的库函数,如  sqrt 。 11 | 12 | Example 1: 13 | 输入:num = 16 14 | 输出:true 15 | 16 | Example 2: 17 | 输入:num = 14 18 | 输出:false 19 | 20 | Note: 21 | -1 <= num <= 2^31 - 1 22 | """ 23 | 24 | 25 | class Solution: 26 | def isPerfectSquare(self, num: int) -> bool: 27 | start = 1 28 | 29 | while start <= num: 30 | tmp = start ** 2 31 | if tmp == num: 32 | return True 33 | if tmp > num: 34 | return False 35 | start += 1 36 | 37 | return False 38 | -------------------------------------------------------------------------------- /QuestionBank/371.Sum of Two Integers/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/6/30 下午2:54 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 两整数之和 6 | 7 | """ 8 | Question: 9 | 不使用运算符 + 和-,计算两整数a 、b之和。 10 | 11 | Example: 12 | 若 a = 1 ,b = 2,返回 3。 13 | """ 14 | 15 | 16 | class Solution: 17 | def getSum(self, a, b): 18 | """ 19 | :type a: int 20 | :type b: int 21 | :rtype: int 22 | """ 23 | return sum([a, b]) 24 | -------------------------------------------------------------------------------- /QuestionBank/387.First Unique Character in a String/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/3 下午9:54 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 字符串中的第一个唯一字符 6 | 7 | """ 8 | Question: 9 | 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 10 | 11 | Example: 12 | s = "leetcode" 13 | 返回 0. 14 | s = "loveleetcode", 15 | 返回 2. 16 | 17 | Note: 18 | 您可以假定该字符串只包含小写字母。 19 | """ 20 | 21 | 22 | class Solution: 23 | def firstUniqChar(self, s): 24 | """ 25 | :type s: str 26 | :rtype: int 27 | """ 28 | for i, v in enumerate(s): 29 | if v not in s[i + 1:] + s[:i]: 30 | return i 31 | else: 32 | return -1 33 | -------------------------------------------------------------------------------- /QuestionBank/387.First Unique Character in a String/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/3 下午9:54 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 字符串中的第一个唯一字符 6 | 7 | """ 8 | Question: 9 | 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 10 | 11 | Example: 12 | s = "leetcode" 13 | 返回 0. 14 | s = "loveleetcode", 15 | 返回 2. 16 | 17 | Note: 18 | 您可以假定该字符串只包含小写字母。 19 | """ 20 | 21 | 22 | class Solution: 23 | def firstUniqChar(self, s): 24 | """ 25 | :type s: str 26 | :rtype: int 27 | """ 28 | t = [] 29 | for i, v in enumerate(s): 30 | if v in t: 31 | continue 32 | if v in s[i + 1:]: 33 | t.append(v) 34 | else: 35 | return i 36 | else: 37 | return -1 38 | -------------------------------------------------------------------------------- /QuestionBank/387.First Unique Character in a String/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/3 下午9:54 3 | # @Author : cancan 4 | # @File : method_3.py 5 | # @Function : 字符串中的第一个唯一字符 6 | 7 | """ 8 | Question: 9 | 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 10 | 11 | Example: 12 | s = "leetcode" 13 | 返回 0. 14 | s = "loveleetcode", 15 | 返回 2. 16 | 17 | Note: 18 | 您可以假定该字符串只包含小写字母。 19 | """ 20 | 21 | 22 | class Solution: 23 | def firstUniqChar(self, s): 24 | """ 25 | :type s: str 26 | :rtype: int 27 | """ 28 | l = list(set(s)) 29 | i = [s.index(t) for t in l if s.count(t) == 1] 30 | return min(i) if i else -1 31 | -------------------------------------------------------------------------------- /QuestionBank/397.Integer Replacement/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/30 19:38 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 整数替换 7 | 8 | """ 9 | Question: 10 | 给定一个正整数 n,你可以做如下操作: 11 | 1. 如果 n 是偶数,则用 n / 2替换 n。 12 | 2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。 13 | n 变为 1 所需的最小替换次数是多少? 14 | 15 | Example 1: 16 | 输入: 8 17 | 输出: 3 18 | 解释: 8 -> 4 -> 2 -> 1 19 | 20 | Example 2: 21 | 输入: 7 22 | 输出: 4 23 | 解释: 24 | 7 -> 8 -> 4 -> 2 -> 1 25 | 或 26 | 7 -> 6 -> 3 -> 2 -> 1 27 | """ 28 | 29 | 30 | class Solution(object): 31 | def integerReplacement(self, n): 32 | """ 33 | :type n: int 34 | :rtype: int 35 | """ 36 | 37 | def f(n): 38 | if n < 3: 39 | return n - 1 40 | 41 | if n % 2 == 0: 42 | return f(n // 2) + 1 43 | else: 44 | return min(f(n - 1), f(n + 1)) + 1 45 | 46 | return f(n) 47 | -------------------------------------------------------------------------------- /QuestionBank/397.Integer Replacement/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/30 19:38 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 整数替换 7 | 8 | """ 9 | Question: 10 | 给定一个正整数 n,你可以做如下操作: 11 | 1. 如果 n 是偶数,则用 n / 2替换 n。 12 | 2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。 13 | n 变为 1 所需的最小替换次数是多少? 14 | 15 | Example 1: 16 | 输入: 8 17 | 输出: 3 18 | 解释: 8 -> 4 -> 2 -> 1 19 | 20 | Example 2: 21 | 输入: 7 22 | 输出: 4 23 | 解释: 24 | 7 -> 8 -> 4 -> 2 -> 1 25 | 或 26 | 7 -> 6 -> 3 -> 2 -> 1 27 | """ 28 | 29 | 30 | class Solution(object): 31 | def integerReplacement(self, n): 32 | """ 33 | :type n: int 34 | :rtype: int 35 | """ 36 | t = {1:0} 37 | 38 | def f(n): 39 | if n in t: 40 | return t[n] 41 | 42 | if n % 2 == 0: 43 | t[n] = f(n // 2) + 1 44 | else: 45 | t[n] = min(f(n - 1), f(n + 1)) + 1 46 | 47 | return t[n] 48 | 49 | return f(n) 50 | -------------------------------------------------------------------------------- /QuestionBank/4.Median of Two Sorted Arrays/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/19 下午10:50 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 两个排序数组的中位数 6 | 7 | """ 8 | Question: 9 | 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 。 10 | 请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log (m+n)) 。 11 | 12 | Example 1: 13 | nums1 = [1, 3] 14 | nums2 = [2] 15 | 中位数是 2.0 16 | 17 | Example 2: 18 | nums1 = [1, 2] 19 | nums2 = [3, 4] 20 | 中位数是 (2 + 3)/2 = 2.5 21 | """ 22 | 23 | 24 | class Solution: 25 | def findMedianSortedArrays(self, nums1, nums2): 26 | """ 27 | :type nums1: List[int] 28 | :type nums2: List[int] 29 | :rtype: float 30 | """ 31 | n = sorted(nums1 + nums2) 32 | l = len(n) 33 | if l % 2 == 0: 34 | return (n[l // 2 - 1] + n[l // 2]) / 2 35 | else: 36 | return n[l // 2] 37 | -------------------------------------------------------------------------------- /QuestionBank/4.Median of Two Sorted Arrays/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/19 下午10:50 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 两个排序数组的中位数 6 | 7 | """ 8 | Question: 9 | 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 。 10 | 请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log (m+n)) 。 11 | 12 | Example 1: 13 | nums1 = [1, 3] 14 | nums2 = [2] 15 | 中位数是 2.0 16 | 17 | Example 2: 18 | nums1 = [1, 2] 19 | nums2 = [3, 4] 20 | 中位数是 (2 + 3)/2 = 2.5 21 | """ 22 | 23 | 24 | class Solution: 25 | def findMedianSortedArrays(self, nums1, nums2): 26 | """ 27 | :type nums1: List[int] 28 | :type nums2: List[int] 29 | :rtype: float 30 | """ 31 | nums1.extend(nums2) 32 | nums1.sort() 33 | l = len(nums1) 34 | if l % 2 == 0: 35 | return (nums1[l // 2 - 1] + nums1[l // 2]) / 2 36 | else: 37 | return nums1[l // 2] 38 | -------------------------------------------------------------------------------- /QuestionBank/414.Third Maximum Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/16 17:34 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 第三大的数 7 | 8 | """ 9 | Question: 10 | 给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。 11 | 12 | Example 1: 13 | 输入: [3, 2, 1] 14 | 输出: 1 15 | 解释: 第三大的数是 1. 16 | 17 | Example 2: 18 | 输入: [1, 2] 19 | 输出: 2 20 | 解释: 第三大的数不存在, 所以返回最大的数 2 . 21 | 22 | Example 3: 23 | 输入: [2, 2, 3, 1] 24 | 输出: 1 25 | 解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。 26 | 存在两个值为2的数,它们都排第二。 27 | """ 28 | 29 | 30 | class Solution(object): 31 | def thirdMax(self, nums): 32 | """ 33 | :type nums: List[int] 34 | :rtype: int 35 | """ 36 | 37 | nums = list(set(nums)) 38 | 39 | if len(nums) < 3: 40 | return max(nums) 41 | else: 42 | nums.sort() 43 | return nums[-3] -------------------------------------------------------------------------------- /QuestionBank/415.Add Strings/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/14 上午11:25 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 字符串相加 6 | 7 | """ 8 | Question: 9 | 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 10 | 11 | Note 12 | 1.num1 和num2 的长度都小于 5100. 13 | 2.num1 和num2 都只包含数字 0-9. 14 | 3.num1 和num2 都不包含任何前导零。 15 | 4.你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。 16 | """ 17 | 18 | 19 | class Solution(object): 20 | def addStrings(self, num1, num2): 21 | """ 22 | :type num1: str 23 | :type num2: str 24 | :rtype: str 25 | """ 26 | return str(int(num1) + int(num2)) 27 | -------------------------------------------------------------------------------- /QuestionBank/43.Multiply Strings/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018-12-16 20:51 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 字符串相乘 7 | 8 | """ 9 | Question: 10 | 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。 11 | 12 | Example 1: 13 | 输入: num1 = "2", num2 = "3" 14 | 输出: "6" 15 | 16 | Example 2: 17 | 输入: num1 = "123", num2 = "456" 18 | 输出: "56088" 19 | 20 | Note: 21 | 1.num1 和 num2 的长度小于110。 22 | 2.num1 和 num2 只包含数字 0-9。 23 | 3.num1 和 num2 均不以零开头,除非是数字 0 本身。 24 | 4.不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。 25 | """ 26 | 27 | 28 | class Solution: 29 | def multiply(self, num1, num2): 30 | """ 31 | :type num1: str 32 | :type num2: str 33 | :rtype: str 34 | """ 35 | return str(int(num1) * int(num2)) 36 | -------------------------------------------------------------------------------- /QuestionBank/434.Number of Segments in a String/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/1 下午10:01 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 字符串中的单词数 6 | 7 | """ 8 | Question: 9 | 统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 10 | 请注意,你可以假定字符串里不包括任何不可打印的字符。 11 | 12 | Example: 13 | 输入: "Hello, my name is John" 14 | 输出: 5 15 | """ 16 | 17 | 18 | class Solution: 19 | def countSegments(self, s): 20 | """ 21 | :type s: str 22 | :rtype: int 23 | """ 24 | num = 0 25 | if s and s[0] != ' ': 26 | num += 1 27 | l = len(s) 28 | for i, w in enumerate(s): 29 | if w == ' ' and i + 1 < l and s[i + 1] != ' ': 30 | num += 1 31 | 32 | return num 33 | -------------------------------------------------------------------------------- /QuestionBank/434.Number of Segments in a String/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/1 下午10:01 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 字符串中的单词数 6 | 7 | """ 8 | Question: 9 | 统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 10 | 请注意,你可以假定字符串里不包括任何不可打印的字符。 11 | 12 | Example: 13 | 输入: "Hello, my name is John" 14 | 输出: 5 15 | """ 16 | 17 | 18 | class Solution: 19 | def countSegments(self, s): 20 | """ 21 | :type s: str 22 | :rtype: int 23 | """ 24 | return len(s.split()) 25 | -------------------------------------------------------------------------------- /QuestionBank/442.Find All Duplicates in an Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 19:44 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 数组中重复的数据 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。 11 | 找到所有出现两次的元素。 12 | 你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗? 13 | 14 | Example: 15 | 输入: [4,3,2,7,8,2,3,1] 16 | 输出: [2,3] 17 | """ 18 | 19 | 20 | class Solution(object): 21 | def findDuplicates(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: List[int] 25 | """ 26 | r = {} 27 | 28 | for i in nums: 29 | if i not in r: 30 | r[i] = 1 31 | else: 32 | r[i] += 1 33 | 34 | res = [] 35 | for k, v in r.items(): 36 | if v > 1: 37 | res.append(k) 38 | 39 | return res 40 | -------------------------------------------------------------------------------- /QuestionBank/442.Find All Duplicates in an Array/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/2 19:44 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 数组中重复的数据 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。 11 | 找到所有出现两次的元素。 12 | 你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗? 13 | 14 | Example: 15 | 输入: [4,3,2,7,8,2,3,1] 16 | 输出: [2,3] 17 | """ 18 | 19 | 20 | class Solution(object): 21 | def findDuplicates(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: List[int] 25 | """ 26 | from collections import Counter 27 | 28 | c = Counter(nums) 29 | res = [] 30 | for k, v in c.items(): 31 | if v > 1: 32 | res.append(k) 33 | return res 34 | -------------------------------------------------------------------------------- /QuestionBank/448.Find All Numbers Disappeared in an Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-19 17:10 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 找到所有数组中消失的数字 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 12 | 找到所有在 [1, n] 范围之间没有出现在数组中的数字。 13 | 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。 14 | 15 | Example: 16 | 输入: 17 | [4,3,2,7,8,2,3,1] 18 | 输出: 19 | [5,6] 20 | """ 21 | 22 | 23 | class Solution: 24 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 25 | t = set() 26 | 27 | for i in nums: 28 | t.add(i) 29 | 30 | res = [] 31 | 32 | for i in range(1, len(nums) + 1): 33 | if i not in t: 34 | res.append(i) 35 | 36 | return res 37 | -------------------------------------------------------------------------------- /QuestionBank/46.Permutations/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Question: 6 | 给定一个不同的数字集合,返回所有可能的排列。 7 | 8 | Example: 9 | [1,2,3] 有如下排列: 10 | [ 11 | [1,2,3], 12 | [1,3,2], 13 | [2,1,3], 14 | [2,3,1], 15 | [3,1,2], 16 | [3,2,1] 17 | ] 18 | """ 19 | 20 | class Solution(object): 21 | def permute(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: List[List[int]] 25 | """ 26 | ans = [] 27 | if nums is None: 28 | return ans 29 | if len(nums) == 0: 30 | ans.append([]) 31 | for each in nums: 32 | temp = nums[:] # 复制nums列表 33 | temp.remove(each) 34 | for i in self.permute(temp): 35 | i.insert(0, each) 36 | ans.append(i) 37 | return ans 38 | 39 | a = [1, 2, 3] 40 | b = Solution() 41 | print(b.permute(a)) -------------------------------------------------------------------------------- /QuestionBank/476.Number Complement/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/6/24 上午12:15 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 数字的补数 6 | 7 | """ 8 | Question: 9 | 给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。 10 | 11 | Note: 12 | 1.给定的整数保证在32位带符号整数的范围内。 13 | 2.你可以假定二进制数不包含前导零位。 14 | 15 | Example 1: 16 | 输入: 5 17 | 输出: 2 18 | 解释: 5的二进制表示为101(没有前导零位),其补数为010。所以你需要输出2。 5的二进 19 | 20 | Example 2: 21 | 输入: 1 22 | 输出: 0 23 | 解释: 1的二进制表示为1(没有前导零位),其补数为0。所以你需要输出0。 24 | """ 25 | 26 | 27 | class Solution: 28 | def findComplement(self, num): 29 | """ 30 | :type num: int 31 | :rtype: int 32 | """ 33 | b = bin(num)[2:] 34 | res = '' 35 | for i in b: 36 | if i == '1': 37 | res += '0' 38 | else: 39 | res += '1' 40 | 41 | return int(res, 2) 42 | -------------------------------------------------------------------------------- /QuestionBank/485.Max Consecutive Ones/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/24 14:58 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 最大连续1的个数 7 | 8 | """ 9 | Question: 10 | 给定一个二进制数组, 计算其中最大连续1的个数。 11 | 12 | Example 1: 13 | 输入: [1,1,0,1,1,1] 14 | 输出: 3 15 | 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3. 16 | 17 | Note 18 | 1.输入的数组只包含 0 和1。 19 | 2.输入数组的长度是正整数,且不超过 10,000。 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def findMaxConsecutiveOnes(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | t = {1: 0} 30 | r = t[1] 31 | 32 | for i, v in enumerate(nums): 33 | if v == 1: 34 | t[v] += 1 35 | else: 36 | if t[1] > r: 37 | r = t[1] 38 | t[1] = 0 39 | 40 | return t[1] if t[1] > r else r 41 | -------------------------------------------------------------------------------- /QuestionBank/49.Group Anagrams/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/8/4 下午7:10 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 字母异位词分组 6 | 7 | """ 8 | Question: 9 | 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 10 | 11 | Example: 12 | 输入: ["eat", "tea", "tan", "ate", "nat", "bat"], 13 | 输出: 14 | [ 15 | ["ate","eat","tea"], 16 | ["nat","tan"], 17 | ["bat"] 18 | ] 19 | 20 | Note 21 | 1.所有输入均为小写字母。 22 | 2.不考虑答案输出的顺序。 23 | """ 24 | 25 | 26 | class Solution: 27 | def groupAnagrams(self, strs): 28 | """ 29 | :type strs: List[str] 30 | :rtype: List[List[str]] 31 | """ 32 | t = {} 33 | 34 | for i in strs: 35 | s = ''.join(sorted(i)) 36 | if s in t: 37 | t[s].append(i) 38 | else: 39 | t[s] = [i] 40 | 41 | return [i for i in t.values()] 42 | -------------------------------------------------------------------------------- /QuestionBank/50.Pow(x, n)/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/21 下午6:35 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : Pow(x, n) 6 | 7 | """ 8 | Question: 9 | 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 10 | 11 | Example 1: 12 | 输入: 2.00000, 10 13 | 输出: 1024.00000 14 | 15 | Example 2: 16 | 输入: 2.10000, 3 17 | 输出: 9.26100 18 | 19 | Example 3: 20 | 输入: 2.00000, -2 21 | 输出: 0.25000 22 | 解释: 2-2 = 1/22 = 1/4 = 0.25 23 | 24 | Note: 25 | -100.0 < x < 100.0 26 | n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 27 | """ 28 | 29 | 30 | class Solution: 31 | def myPow(self, x, n): 32 | """ 33 | :type x: float 34 | :type n: int 35 | :rtype: float 36 | """ 37 | return x ** n 38 | -------------------------------------------------------------------------------- /QuestionBank/50.Pow(x, n)/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/21 下午6:35 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : Pow(x, n) 6 | 7 | """ 8 | Question: 9 | 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 10 | 11 | Example 1: 12 | 输入: 2.00000, 10 13 | 输出: 1024.00000 14 | 15 | Example 2: 16 | 输入: 2.10000, 3 17 | 输出: 9.26100 18 | 19 | Example 3: 20 | 输入: 2.00000, -2 21 | 输出: 0.25000 22 | 解释: 2-2 = 1/22 = 1/4 = 0.25 23 | 24 | Note: 25 | -100.0 < x < 100.0 26 | n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 27 | """ 28 | 29 | 30 | class Solution: 31 | def myPow(self, x, n): 32 | """ 33 | :type x: float 34 | :type n: int 35 | :rtype: float 36 | """ 37 | 38 | if n < 0: 39 | n = -n 40 | x = 1 / x 41 | 42 | ans = 1.0 43 | 44 | while n > 0: 45 | if n % 2 == 1: 46 | ans *= x 47 | 48 | x *= x 49 | n //= 2 50 | 51 | return ans 52 | 53 | s = Solution() 54 | print(s.myPow(2.00000, 10)) 55 | -------------------------------------------------------------------------------- /QuestionBank/509.Fibonacci Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-19 17:25 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 斐波那契数 7 | 8 | 9 | """ 10 | Question: 11 | 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: 12 | 13 | F(0) = 0, F(1) = 1 14 | F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 15 | 16 | 给定 N,计算 F(N)。 17 | 18 | Example 1: 19 | 输入:2 20 | 输出:1 21 | 解释:F(2) = F(1) + F(0) = 1 + 0 = 1. 22 | 23 | Example 2: 24 | 输入:3 25 | 输出:2 26 | 解释:F(3) = F(2) + F(1) = 1 + 1 = 2. 27 | 28 | Example 3: 29 | 输入:4 30 | 输出:3 31 | 解释:F(4) = F(3) + F(2) = 2 + 1 = 3. 32 | 33 | 提示: 34 | 0 ≤ N ≤ 30 35 | """ 36 | 37 | 38 | class Solution: 39 | def fib(self, N: int) -> int: 40 | 41 | if N == 0 or N == 1: 42 | return N 43 | elif N >= 2: 44 | return self.fib(N - 1) + self.fib(N - 2) 45 | -------------------------------------------------------------------------------- /QuestionBank/509.Fibonacci Number/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-19 17:25 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 斐波那契数 7 | 8 | 9 | """ 10 | Question: 11 | 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: 12 | 13 | F(0) = 0, F(1) = 1 14 | F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 15 | 16 | 给定 N,计算 F(N)。 17 | 18 | Example 1: 19 | 输入:2 20 | 输出:1 21 | 解释:F(2) = F(1) + F(0) = 1 + 0 = 1. 22 | 23 | Example 2: 24 | 输入:3 25 | 输出:2 26 | 解释:F(3) = F(2) + F(1) = 1 + 1 = 2. 27 | 28 | Example 3: 29 | 输入:4 30 | 输出:3 31 | 解释:F(4) = F(3) + F(2) = 2 + 1 = 3. 32 | 33 | 提示: 34 | 0 ≤ N ≤ 30 35 | """ 36 | 37 | 38 | class Solution: 39 | def fib(self, N: int) -> int: 40 | prev, current = 0, 1 41 | for i in range(N): 42 | prev, current = current, prev + current 43 | return prev 44 | -------------------------------------------------------------------------------- /QuestionBank/53.Maximum Subarray/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/27 下午2:50 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 最大子序和 6 | 7 | """ 8 | Question: 9 | 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 10 | 11 | Example: 12 | 输入: [-2,1,-3,4,-1,2,1,-5,4], 13 | 输出: 6 14 | 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 15 | 16 | Follow up: 17 | 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 18 | """ 19 | 20 | 21 | class Solution: 22 | def maxSubArray(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: int 26 | """ 27 | r = nums[0] 28 | s = 0 29 | for _ in nums: 30 | s = max(s + _, _) 31 | r = max(r, s) 32 | return r 33 | -------------------------------------------------------------------------------- /QuestionBank/551.Student Attendance Record I/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/10 12:11 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 学生出勤纪录 I 7 | 8 | """ 9 | Question: 10 | 给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个字符: 11 | 'A' : Absent,缺勤 12 | 'L' : Late,迟到 13 | 'P' : Present,到场 14 | 如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。 15 | 你需要根据这个学生的出勤纪录判断他是否会被奖赏。 16 | 17 | Example 1: 18 | 输入: "PPALLP" 19 | 输出: True 20 | 21 | Example 2: 22 | 输入: "PPALLL" 23 | 输出: False 24 | """ 25 | 26 | 27 | class Solution: 28 | def checkRecord(self, s): 29 | """ 30 | :type s: str 31 | :rtype: bool 32 | """ 33 | t = {'A': 0, 'L': 0, 'P': 0} 34 | l = 0 35 | for i in s: 36 | if i == 'L': 37 | l += 1 38 | if l > 2: 39 | l = 0 40 | t['L'] += 1 41 | else: 42 | l = 0 43 | t[i] += 1 44 | 45 | return t['A'] <= 1 and t['L'] == 0 46 | -------------------------------------------------------------------------------- /QuestionBank/551.Student Attendance Record I/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/10 12:11 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 学生出勤纪录 I 7 | 8 | """ 9 | Question: 10 | 给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个字符: 11 | 'A' : Absent,缺勤 12 | 'L' : Late,迟到 13 | 'P' : Present,到场 14 | 如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。 15 | 你需要根据这个学生的出勤纪录判断他是否会被奖赏。 16 | 17 | Example 1: 18 | 输入: "PPALLP" 19 | 输出: True 20 | 21 | Example 2: 22 | 输入: "PPALLL" 23 | 输出: False 24 | """ 25 | 26 | 27 | class Solution: 28 | def checkRecord(self, s): 29 | """ 30 | :type s: str 31 | :rtype: bool 32 | """ 33 | return s.count('A') <= 1 and s.count('LLL') == 0 34 | -------------------------------------------------------------------------------- /QuestionBank/557.Reverse Words in a String III/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/1 下午6:39 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 反转字符串中的单词 III 6 | 7 | """ 8 | Question: 9 | 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 10 | 11 | Example: 12 | 输入: "Let's take LeetCode contest" 13 | 输出: "s'teL ekat edoCteeL tsetnoc" 14 | 15 | Note: 16 | 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 17 | """ 18 | 19 | 20 | class Solution: 21 | def reverseWords(self, s): 22 | """ 23 | :type s: str 24 | :rtype: str 25 | """ 26 | return ' '.join([i[::-1] for i in s.split()]) 27 | -------------------------------------------------------------------------------- /QuestionBank/560.Subarray Sum Equals K/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/5/15 16:11 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 和为K的子数组 7 | 8 | """ 9 | Question: 10 | 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。 11 | 12 | Example 1 : 13 | 输入:nums = [1,1,1], k = 2 14 | 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。 15 | 16 | Note : 17 | 1.数组的长度为 [1, 20,000]。 18 | 2.数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。 19 | """ 20 | 21 | from typing import List 22 | 23 | 24 | class Solution: 25 | def subarraySum(self, nums: List[int], k: int) -> int: 26 | count = 0 27 | tmp = {0: 1} 28 | pre = 0 29 | l = len(nums) 30 | for i in range(l): 31 | pre += nums[i] 32 | if pre - k in tmp: 33 | count += tmp[pre - k] 34 | if pre in tmp: 35 | tmp[pre] += 1 36 | else: 37 | tmp[pre] = 1 38 | return count 39 | -------------------------------------------------------------------------------- /QuestionBank/561.Array Partition I/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/23 15:05 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 数组拆分 I 7 | 8 | """ 9 | Question: 10 | 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., 11 | (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。 12 | 13 | Example 1: 14 | 输入: [1,4,3,2] 15 | 输出: 4 16 | 解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4). 17 | 18 | Note: 19 | 1.n 是正整数,范围在 [1, 10000]. 20 | 2.数组中的元素范围在 [-10000, 10000]. 21 | """ 22 | 23 | 24 | class Solution: 25 | def arrayPairSum(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | nums.sort() 31 | l = len(nums) 32 | s = 0 33 | 34 | for i in range(0, l, 2): 35 | s += nums[i] 36 | 37 | return s 38 | -------------------------------------------------------------------------------- /QuestionBank/5738.Sum of Digits in Base K/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2021/4/25 17:01 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : K 进制表示下的各位数字总和 7 | 8 | 9 | """ 10 | Question: 11 | 给你一个整数 n(10 进制)和一个基数 k ,请你将 n 从 10 进制表示转换为 k 进制表示,计算并返回转换后各位数字的 总和 。 12 | 转换后,各位数字应当视作是 10 进制数字,且它们的总和也应当按 10 进制表示返回。 13 | 14 | 示例 1: 15 | 输入:n = 34, k = 6 16 | 输出:9 17 | 解释:34 (10 进制) 在 6 进制下表示为 54 。5 + 4 = 9 。 18 | 19 | 示例 2: 20 | 输入:n = 10, k = 10 21 | 输出:1 22 | 解释:n 本身就是 10 进制。 1 + 0 = 1 。 23 | 24 | 提示: 25 | 1 <= n <= 100 26 | 2 <= k <= 10 27 | """ 28 | 29 | 30 | class Solution: 31 | def sumBase(self, n: int, k: int) -> int: 32 | ans = 0 33 | while n != 0: 34 | a, b = divmod(n, k) 35 | while b > k: 36 | n = a 37 | a, b = divmod(n, k) 38 | ans += b 39 | n = a 40 | 41 | return ans 42 | -------------------------------------------------------------------------------- /QuestionBank/575.Distribute Candies/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-19 17:42 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 分糖果 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果, 12 | 每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。 13 | 14 | Example 1: 15 | 输入: candies = [1,1,2,2,3,3] 16 | 输出: 3 17 | 解析: 一共有三种种类的糖果,每一种都有两个。 18 | 最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。 19 | 20 | Example 2 : 21 | 输入: candies = [1,1,2,3] 22 | 输出: 2 23 | 解析: 妹妹获得糖果[2,3],弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。 24 | 25 | Note: 26 | 1.数组的长度为[2, 10,000],并且确定为偶数。 27 | 2.数组中数字的大小在范围[-100,000, 100,000]内。 28 | """ 29 | 30 | 31 | class Solution: 32 | def distributeCandies(self, candies: list[int]) -> int: 33 | l = len(candies) 34 | ls = len(set(candies)) 35 | d = l // 2 36 | 37 | return ls if d >= ls else d 38 | -------------------------------------------------------------------------------- /QuestionBank/58.Length of Last Word/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/1 下午10:19 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 最后一个单词的长度 6 | 7 | """ 8 | Question: 9 | 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 10 | 如果不存在最后一个单词,请返回 0 。 11 | 12 | Note: 13 | 一个单词是指由字母组成,但不包含任何空格的字符串。 14 | 15 | Example: 16 | 输入: "Hello World" 17 | 输出: 5 18 | """ 19 | 20 | 21 | class Solution: 22 | def lengthOfLastWord(self, s): 23 | """ 24 | :type s: str 25 | :rtype: int 26 | """ 27 | t = s.split() 28 | return len(t[-1]) if t else 0 29 | -------------------------------------------------------------------------------- /QuestionBank/628.Maximum Product of Three Numbers/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2021/1/20 10:36 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 三个数的最大乘积 7 | 8 | """ 9 | 给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 10 | 11 | 示例 1: 12 | 输入: [1,2,3] 13 | 输出: 6 14 | 15 | 示例 2: 16 | 输入: [1,2,3,4] 17 | 输出: 24 18 | 19 | 注意: 20 | - 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。 21 | - 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。 22 | """ 23 | 24 | from typing import List 25 | 26 | 27 | class Solution: 28 | def maximumProduct(self, nums: List[int]) -> int: 29 | nums.sort() 30 | return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1]) 31 | -------------------------------------------------------------------------------- /QuestionBank/633.Sum of Square Numbers/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/10/14 14:15 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 平方数之和 7 | 8 | """ 9 | 给定一个非负整数你要判断是否存在两个整数 a 和 b,使得 + b2 = c 。 10 | 11 | 示例 1: 12 | 输入:c = 5 13 | 输出:true 14 | 解释:1 * 1 + 2 * 2 = 5 15 | 16 | 示例 2: 17 | 输入:c = 3 18 | 输出:false 19 | 20 | 提示: 21 | 0 <= c <= 231 - 1 22 | """ 23 | 24 | import math 25 | 26 | 27 | class Solution: 28 | def judgeSquareSum(self, c: int) -> bool: 29 | i = 0 30 | j = math.ceil(math.sqrt(c)) 31 | while (i <= j): 32 | s = i ** 2 + j ** 2 33 | if s == c: 34 | return True 35 | if (s > c): 36 | j -= 1 37 | else: 38 | i += 1 39 | return False 40 | -------------------------------------------------------------------------------- /QuestionBank/643.Maximum Average Subarray I/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2021/2/4 10:47 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 子数组最大平均数 I 7 | 8 | """ 9 | 给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数。 10 | 11 | 示例: 12 | 输入:[1,12,-5,-6,50,3], k = 4 13 | 输出:12.75 14 | 解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75 15 | 16 | 提示: 17 | - 1 <= k <= n <= 30,000。 18 | - 所给数据范围 [-10,000,10,000]。 19 | """ 20 | 21 | from typing import List 22 | 23 | 24 | class Solution: 25 | def findMaxAverage(self, nums: List[int], k: int) -> float: 26 | tmp = ans = sum(nums[:k]) 27 | for i in range(k, len(nums)): 28 | tmp = tmp - nums[i - k] + nums[i] 29 | if tmp > ans: 30 | ans = tmp 31 | return ans * 1.0 / k 32 | -------------------------------------------------------------------------------- /QuestionBank/66.Plus One/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/1 下午9:01 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 加一 6 | 7 | """ 8 | Question: 9 | 给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。 10 | 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。 11 | 你可以假设除了整数 0 之外,这个整数不会以零开头。 12 | 13 | Example 1: 14 | 输入: [1,2,3] 15 | 输出: [1,2,4] 16 | 解释: 输入数组表示数字 123。 17 | 18 | Example 2: 19 | 输入: [4,3,2,1] 20 | 输出: [4,3,2,2] 21 | 解释: 输入数组表示数字 4321。 22 | """ 23 | 24 | 25 | class Solution: 26 | def plusOne(self, digits): 27 | """ 28 | :type digits: List[int] 29 | :rtype: List[int] 30 | """ 31 | s1 = '' 32 | for i in digits: 33 | s1 += str(i) 34 | 35 | s1 = str(int(s1) + 1) 36 | 37 | r = [] 38 | 39 | for i in s1: 40 | r.append(int(i)) 41 | 42 | return r 43 | -------------------------------------------------------------------------------- /QuestionBank/66.Plus One/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/1 下午9:01 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 加一 6 | 7 | """ 8 | Question: 9 | 给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。 10 | 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。 11 | 你可以假设除了整数 0 之外,这个整数不会以零开头。 12 | 13 | Example 1: 14 | 输入: [1,2,3] 15 | 输出: [1,2,4] 16 | 解释: 输入数组表示数字 123。 17 | 18 | Example 2: 19 | 输入: [4,3,2,1] 20 | 输出: [4,3,2,2] 21 | 解释: 输入数组表示数字 4321。 22 | """ 23 | 24 | 25 | class Solution: 26 | def plusOne(self, digits): 27 | """ 28 | :type digits: List[int] 29 | :rtype: List[int] 30 | """ 31 | num = 0 32 | for i, v in enumerate(digits): 33 | num = num * 10 + digits[i] 34 | s = str(num + 1) 35 | return [int(i) for i in s] 36 | -------------------------------------------------------------------------------- /QuestionBank/67.Add Binary/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/7/14 上午11:31 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 二进制求和 6 | 7 | """ 8 | Question: 9 | 给定两个二进制字符串,返回他们的和(用二进制表示)。 10 | 输入为非空字符串且只包含数字 1 和 0。 11 | 12 | Example 1: 13 | 输入: a = "11", b = "1" 14 | 输出: "100" 15 | 16 | Example 2: 17 | 输入: a = "1010", b = "1011" 18 | 输出: "10101" 19 | """ 20 | 21 | 22 | class Solution(object): 23 | def addBinary(self, a, b): 24 | """ 25 | :type a: str 26 | :type b: str 27 | :rtype: str 28 | """ 29 | return bin(int(a, 2) + int(b, 2))[2:] 30 | -------------------------------------------------------------------------------- /QuestionBank/670.Maximum Swap/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/9/27 14:20 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 最大交换 7 | 8 | """ 9 | 给定一个非负整数,你至多可以交换一次数字中的任意两位。返回你能得到的最大值。 10 | 11 | 示例 1 : 12 | 输入: 2736 13 | 输出: 7236 14 | 解释: 交换数字2和数字7。 15 | 16 | 示例 2 : 17 | 输入: 9973 18 | 输出: 9973 19 | 解释: 不需要交换。 20 | 21 | 注意: 22 | 给定数字的范围是 [0, 108] 23 | """ 24 | 25 | class Solution: 26 | def maximumSwap(self, num: int) -> int: 27 | l = list(str(num)) 28 | for i in range(len(l)): 29 | for j in range(i): 30 | l[i], l[j] = l[j], l[i] 31 | num = max(num, int(''.join(l))) 32 | l[i], l[j] = l[j], l[i] 33 | return num -------------------------------------------------------------------------------- /QuestionBank/680.Valid Palindrome II/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/5/19 00:13 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 验证回 文字符串 Ⅱ 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个非空字符串 s,最多删除一个字符。判断是否能成为回文字符串。 12 | 13 | Example 1: 14 | 输入: "aba" 15 | 输出: True 16 | 17 | Example 2: 18 | 输入: "abca" 19 | 输出: True 20 | 解释: 你可以删除c字符。 21 | 22 | Note: 23 | 字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。 24 | """ 25 | 26 | 27 | class Solution: 28 | def validPalindrome(self, s: str) -> bool: 29 | def check(low, high): 30 | while low < high: 31 | if s[low] != s[high]: 32 | return False 33 | low += 1 34 | high -= 1 35 | return True 36 | 37 | low, high = 0, len(s) - 1 38 | while low < high: 39 | if s[low] == s[high]: 40 | low += 1 41 | high -= 1 42 | else: 43 | return check(low + 1, high) or check(low, high - 1) 44 | return True 45 | -------------------------------------------------------------------------------- /QuestionBank/69.Sqrt(x)/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/10 9:40 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : x 的平方根 7 | 8 | """ 9 | Question: 10 | 实现 int sqrt(int x) 函数。 11 | 计算并返回 x 的平方根,其中 x 是非负整数。 12 | 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 13 | 14 | Example 1: 15 | 输入: 4 16 | 输出: 2 17 | 18 | Example 2: 19 | 输入: 8 20 | 输出: 2 21 | 说明: 8 的平方根是 2.82842..., 22 | 由于返回类型是整数,小数部分将被舍去。 23 | """ 24 | 25 | 26 | class Solution: 27 | def mySqrt(self, x): 28 | """ 29 | :type x: int 30 | :rtype: int 31 | """ 32 | return int(x ** 0.5) 33 | -------------------------------------------------------------------------------- /QuestionBank/693.Binary Number with Alternating Bits/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/30 18:53 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 交替位二进制数 7 | 8 | """ 9 | Question: 10 | 给定一个正整数,检查他是否为交替位二进制数:换句话说,就是他的二进制数相邻的两个位数永不相等。 11 | 12 | Example 1: 13 | 输入: 5 14 | 输出: True 15 | 解释: 16 | 5的二进制数是: 101 17 | 18 | Example 2: 19 | 输入: 7 20 | 输出: False 21 | 解释: 22 | 7的二进制数是: 111 23 | 24 | Example 3: 25 | 输入: 11 26 | 输出: False 27 | 解释: 28 | 11的二进制数是: 1011 29 | 30 | Example 4: 31 | 输入: 10 32 | 输出: True 33 | 解释: 34 | 10的二进制数是: 1010 35 | """ 36 | 37 | 38 | class Solution(object): 39 | def hasAlternatingBits(self, n): 40 | """ 41 | :type n: int 42 | :rtype: bool 43 | """ 44 | b = bin(n)[2:] 45 | 46 | for i in range(len(b) - 1): 47 | if b[i] == b[i + 1]: 48 | return False 49 | 50 | return True 51 | -------------------------------------------------------------------------------- /QuestionBank/7.Reverse Integer/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 整数的反向数字。 6 | 7 | Example1: x = 123, return 321 8 | Example2: x = -123, return -321 9 | 10 | Note: 11 | 输入假定为一个32位的带符号整数。 12 | 当反向的整数溢出时,函数应该返回0。 13 | """ 14 | 15 | class Solution(object): 16 | def reverse(self, x): 17 | """ 18 | :type x: int 19 | :rtype: int 20 | """ 21 | 22 | x = x 23 | if x >= 0: 24 | x = reversed(str(x)) 25 | t = '' 26 | for i in x: 27 | t += i 28 | 29 | r = int(t) 30 | if r > (2 ** 31 - 1): 31 | return 0 32 | else: 33 | return r 34 | 35 | else: 36 | x = reversed(str(0 - x)) 37 | t = '' 38 | for i in x: 39 | t += i 40 | 41 | r = int(t) 42 | if r > (2 ** 31 - 1): 43 | return 0 44 | else: 45 | return 0 - r -------------------------------------------------------------------------------- /QuestionBank/7.Reverse Integer/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 整数的反向数字。 6 | 7 | Example1: x = 123, return 321 8 | Example2: x = -123, return -321 9 | 10 | Note: 11 | 输入假定为一个32位的带符号整数。 12 | 当反向的整数溢出时,函数应该返回0。 13 | """ 14 | from filecmp import cmp 15 | 16 | 17 | class Solution(object): 18 | def reverse(self, x): 19 | """ 20 | :type x: int 21 | :rtype: int 22 | """ 23 | 24 | # ` `类似repr(),repr()比str()对Python更友好 25 | 26 | s = cmp(x, 0) 27 | r = int(str(s * x)[::-1]) 28 | return s * r * (r <= (2 ** 31 - 1)) 29 | -------------------------------------------------------------------------------- /QuestionBank/7.Reverse Integer/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/3 10:07 4 | # @Author : cancan 5 | # @File : method_3.py 6 | # @Function : 颠倒整数 7 | 8 | """ 9 | Question: 10 | 给定一个 32 位有符号整数,将整数中的数字进行反转。 11 | 12 | Example 1: 13 | 输入: 123 14 | 输出: 321 15 | 16 | Example 2: 17 | 输入: -123 18 | 输出: -321 19 | 20 | Example 3: 21 | 输入: 120 22 | 输出: 21 23 | 24 | Note: 25 | 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。 26 | 根据这个假设,如果反转后的整数溢出,则返回 0。 27 | """ 28 | 29 | 30 | class Solution: 31 | def reverse(self, x): 32 | """ 33 | :type x: int 34 | :rtype: int 35 | """ 36 | f = lambda x: x if -2 ** 31 <= x <= 2 ** 31 - 1 else 0 37 | if x > 0: 38 | return f(int(str(x)[::-1])) 39 | elif x < 0: 40 | return f(int('-' + str(x)[1:][::-1])) 41 | else: 42 | return x 43 | -------------------------------------------------------------------------------- /QuestionBank/7.Reverse Integer/method_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/5/3 10:07 4 | # @Author : cancan 5 | # @File : method_4.py 6 | # @Function : 颠倒整数 7 | 8 | """ 9 | Question: 10 | 给定一个 32 位有符号整数,将整数中的数字进行反转。 11 | 12 | Example 1: 13 | 输入: 123 14 | 输出: 321 15 | 16 | Example 2: 17 | 输入: -123 18 | 输出: -321 19 | 20 | Example 3: 21 | 输入: 120 22 | 输出: 21 23 | 24 | Note: 25 | 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。 26 | 根据这个假设,如果反转后的整数溢出,则返回 0。 27 | """ 28 | 29 | 30 | class Solution: 31 | def reverse(self, x): 32 | """ 33 | :type x: int 34 | :rtype: int 35 | """ 36 | r = int(str(abs(x))[::-1]) 37 | if r > 2 ** 31: 38 | return 0 39 | 40 | if x < 0: 41 | return -r 42 | else: 43 | return r 44 | -------------------------------------------------------------------------------- /QuestionBank/70.Climbing Stairs/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/27 下午12:57 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 爬楼梯 6 | 7 | """ 8 | Question: 9 | 假设你正在爬楼梯。需要 n 步你才能到达楼顶。 10 | 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 11 | 12 | Note: 13 | 给定 n 是一个正整数。 14 | 15 | Example 1: 16 | 输入: 2 17 | 输出: 2 18 | 解释: 有两种方法可以爬到楼顶。 19 | 1. 1 步 + 1 步 20 | 2. 2 步 21 | 22 | Example 2: 23 | 输入: 3 24 | 输出: 3 25 | 解释: 有三种方法可以爬到楼顶。 26 | 1. 1 步 + 1 步 + 1 步 27 | 2. 1 步 + 2 步 28 | 3. 2 步 + 1 步 29 | """ 30 | 31 | 32 | class Solution: 33 | def climbStairs(self, n): 34 | """ 35 | :type n: int 36 | :rtype: int 37 | """ 38 | 39 | a = b = 1 40 | for _ in range(n - 1): 41 | a, b = b, a + b 42 | 43 | return b 44 | -------------------------------------------------------------------------------- /QuestionBank/704.Binary Search/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/16 17:00 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 二分查找 7 | 8 | """ 9 | Question: 10 | 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target , 11 | 写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。 12 | 13 | Example 1: 14 | 输入: nums = [-1,0,3,5,9,12], target = 9 15 | 输出: 4 16 | 解释: 9 出现在 nums 中并且下标为 4 17 | 18 | Example 2: 19 | 输入: nums = [-1,0,3,5,9,12], target = 2 20 | 输出: -1 21 | 解释: 2 不存在 nums 中因此返回 -1 22 | 23 | NOte: 24 | 1.你可以假设 nums 中的所有元素是不重复的。 25 | 2.n 将在 [1, 10000]之间。 26 | 3.nums 的每个元素都将在 [-9999, 9999]之间。 27 | """ 28 | 29 | 30 | class Solution(object): 31 | def search(self, nums, target): 32 | """ 33 | :type nums: List[int] 34 | :type target: int 35 | :rtype: int 36 | """ 37 | 38 | if target not in nums: 39 | return -1 40 | return nums.index(target) 41 | -------------------------------------------------------------------------------- /QuestionBank/709.To Lower Case/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/31 13:41 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 转换成小写字母 7 | 8 | """ 9 | Question: 10 | 实现函数 ToLowerCase(),该函数接收一个字符串参数 str, 11 | 并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。 12 | 13 | Example 1: 14 | 输入: "Hello" 15 | 输出: "hello" 16 | 17 | Example 2: 18 | 输入: "here" 19 | 输出: "here" 20 | 21 | Example 3: 22 | 输入: "LOVELY" 23 | 输出: "lovely" 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def toLowerCase(self, str): 29 | """ 30 | :type str: str 31 | :rtype: str 32 | """ 33 | return str.lower() 34 | -------------------------------------------------------------------------------- /QuestionBank/71.Simplify Path/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018-12-16 22:12 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 简化路径 7 | 8 | """ 9 | Question: 10 | 给定一个文档 (Unix-style) 的完全路径,请进行路径简化。 11 | 12 | Example: 13 | path = "/home/", => "/home" 14 | path = "/a/./b/../../c/", => "/c" 15 | 16 | Note: 17 | 1.你是否考虑了 路径 = "/../" 的情况? 18 | 在这种情况下,你需返回 "/" 。 19 | 2.此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。 20 | 在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。 21 | """ 22 | 23 | 24 | class Solution(object): 25 | def simplifyPath(self, path): 26 | """ 27 | :type path: str 28 | :rtype: str 29 | """ 30 | path_list = path.strip('/').split('/') 31 | r = [] 32 | for i in path_list: 33 | if not i or i == '.': 34 | continue 35 | elif i == '..': 36 | if r and r[-1] != i: 37 | r.pop() 38 | else: 39 | r.append(i) 40 | 41 | return '/' + '/'.join(r) 42 | -------------------------------------------------------------------------------- /QuestionBank/739.Daily Temperatures/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019/6/25 16:01 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 每日温度 7 | 8 | """ 9 | Question: 10 | 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。 11 | 例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。 12 | 提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。 13 | """ 14 | 15 | 16 | class Solution: 17 | def dailyTemperatures(self, T): 18 | ret = [0] * len(T) 19 | stack = [] 20 | 21 | for i, v in enumerate(T): 22 | while len(stack) > 0 and v > T[stack[-1]]: 23 | ret[stack[-1]] = i - stack[-1] 24 | stack.pop() 25 | 26 | stack.append(i) 27 | 28 | return ret 29 | -------------------------------------------------------------------------------- /QuestionBank/747.Largest Number At Least Twice of Others/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/23 11:58 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 至少是其他数字两倍的最大数 7 | 8 | """ 9 | Question: 10 | 在一个给定的数组nums中,总是存在一个最大元素 。 11 | 查找数组中的最大元素是否至少是数组中每个其他数字的两倍。 12 | 如果是,则返回最大元素的索引,否则返回-1。 13 | 14 | Example 1: 15 | 输入: nums = [3, 6, 1, 0] 16 | 输出: 1 17 | 解释: 6是最大的整数, 对于数组中的其他整数, 18 | 6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1. 19 | 20 | Example 2: 21 | 输入: nums = [1, 2, 3, 4] 22 | 输出: -1 23 | 解释: 4没有超过3的两倍大, 所以我们返回 -1. 24 | 25 | Note: 26 | 1.nums 的长度范围在[1, 50]. 27 | 2.每个 nums[i] 的整数范围在 [0, 99]. 28 | """ 29 | 30 | 31 | class Solution(object): 32 | def dominantIndex(self, nums): 33 | """ 34 | :type nums: List[int] 35 | :rtype: int 36 | """ 37 | m = max(nums) 38 | index = nums.index(m) 39 | del nums[index] 40 | 41 | for i in nums: 42 | if m < 2 * i: 43 | return -1 44 | 45 | return index 46 | -------------------------------------------------------------------------------- /QuestionBank/75.Sort Colors/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/8/2 16:17 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 颜色分类 7 | 8 | """ 9 | Question: 10 | 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序, 11 | 使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 12 | 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 13 | 14 | Note: 15 | 不能使用代码库中的排序函数来解决这道题。 16 | 17 | Example: 18 | 输入: [2,0,2,1,1,0] 19 | 输出: [0,0,1,1,2,2] 20 | 21 | Follow up 22 | 1.一个直观的解决方案是使用计数排序的两趟扫描算法。首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 23 | 2.你能想出一个仅使用常数空间的一趟扫描算法吗? 24 | """ 25 | 26 | 27 | class Solution: 28 | def sortColors(self, nums): 29 | """ 30 | :type nums: List[int] 31 | :rtype: void Do not return anything, modify nums in-place instead. 32 | """ 33 | return nums.sort() 34 | -------------------------------------------------------------------------------- /QuestionBank/77.Combinations/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/9/9 18:38 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 组合 7 | 8 | """ 9 | 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 10 | 11 | 示例: 12 | 输入: n = 4, k = 2 13 | 输出: 14 | [ 15 | [2,4], 16 | [3,4], 17 | [2,3], 18 | [1,2], 19 | [1,3], 20 | [1,4], 21 | ] 22 | """ 23 | 24 | from typing import List 25 | 26 | 27 | class Solution: 28 | def combine(self, n: int, k: int) -> List[List[int]]: 29 | self.ret = [] 30 | self.n = n 31 | self.k = k 32 | self.dfs(1, []) 33 | return self.ret 34 | 35 | def dfs(self, start, l): 36 | if len(l) > self.k: 37 | return 38 | 39 | if len(l) == self.k: 40 | self.ret.append(l) 41 | return 42 | 43 | for i in range(start, self.n + 1): 44 | self.dfs(i + 1, l + [i]) 45 | -------------------------------------------------------------------------------- /QuestionBank/771.Jewels and Stones/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/6/23 下午11:56 3 | # @Author : cancan 4 | # @File : method_1.py 5 | # @Function : 宝石与石头 6 | 7 | """ 8 | Question: 9 | 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 10 | S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。 11 | J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。 12 | 13 | Example 1: 14 | 输入: J = "aA", S = "aAAbbbb" 15 | 输出: 3 16 | 17 | Example 2: 18 | 输入: J = "z", S = "ZZ" 19 | 输出: 0 20 | 21 | Note: 22 | S 和 J 最多含有50个字母。 23 | J 中的字符不重复。 24 | """ 25 | 26 | 27 | class Solution: 28 | def numJewelsInStones(self, J, S): 29 | """ 30 | :type J: str 31 | :type S: str 32 | :rtype: int 33 | """ 34 | res = 0 35 | for i in S: 36 | if i in J: 37 | res += 1 38 | 39 | return res 40 | -------------------------------------------------------------------------------- /QuestionBank/796.Rotate String/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/17 21:09 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 旋转字符串 7 | 8 | """ 9 | 给定两个字符串, A 和 B。 10 | A 的旋转操作就是将 A 最左边的字符移动到最右边。 例如, 若 A = 'abcde',在移动一次之后结果就是'bcdea' 。如果在若干次旋转操作之后,A 能变成B,那么返回True。 11 | 12 | 示例 1: 13 | 输入: A = 'abcde', B = 'cdeab' 14 | 输出: true 15 | 16 | 示例 2: 17 | 输入: A = 'abcde', B = 'abced' 18 | 输出: false 19 | 20 | 注意: 21 | A 和 B 长度不超过 100。 22 | """ 23 | 24 | 25 | class Solution: 26 | def rotateString(self, A: str, B: str) -> bool: 27 | if not A and not B: 28 | return True 29 | l = len(A) 30 | if l != len(B): 31 | return False 32 | for idx in range(l): 33 | if A[idx] == B[0]: 34 | d = l - idx 35 | if A[idx:] == B[:d] and A[:idx] == B[d:]: 36 | return True 37 | return False 38 | -------------------------------------------------------------------------------- /QuestionBank/852.Peak Index in a Mountain Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/6/26 11:50 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 山脉数组的峰顶索引 7 | 8 | """ 9 | Question: 10 | 我们把符合下列属性的数组 A 称作山脉: 11 | A.length >= 3 12 | 存在 0 < i < A.length - 1 使得A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 13 | 给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 的 i 的值。 14 | 15 | Example 1: 16 | 输入:[0,1,0] 17 | 输出:1 18 | 19 | Example 2: 20 | 输入:[0,2,1,0] 21 | 输出:1 22 | 23 | Note: 24 | 1. 3 <= A.length <= 10000 25 | 2. 0 <= A[i] <= 10^6 26 | 3. A 是如上定义的山脉 27 | """ 28 | 29 | class Solution(object): 30 | def peakIndexInMountainArray(self, A): 31 | """ 32 | :type A: List[int] 33 | :rtype: int 34 | """ 35 | return A.index(max(A)) -------------------------------------------------------------------------------- /QuestionBank/867.Transpose Matrix/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/31 14:04 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 转置矩阵 7 | 8 | """ 9 | Question: 10 | 给定一个矩阵 A, 返回 A 的转置矩阵。 11 | 矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 12 | 13 | Example 1: 14 | 输入:[[1,2,3],[4,5,6],[7,8,9]] 15 | 输出:[[1,4,7],[2,5,8],[3,6,9]] 16 | 17 | Example 2: 18 | 输入:[[1,2,3],[4,5,6]] 19 | 输出:[[1,4],[2,5],[3,6]] 20 | 21 | Note 22 | 1 <= A.length <= 1000 23 | 1 <= A[0].length <= 1000 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def transpose(self, A): 29 | """ 30 | :type A: List[List[int]] 31 | :rtype: List[List[int]] 32 | """ 33 | r = [] 34 | for i in range(len(A[0])): 35 | t = [] 36 | for j in range(len(A)): 37 | t.append(A[j][i]) 38 | r.append(t) 39 | 40 | return r 41 | -------------------------------------------------------------------------------- /QuestionBank/867.Transpose Matrix/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/31 14:04 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 转置矩阵 7 | 8 | """ 9 | Question: 10 | 给定一个矩阵 A, 返回 A 的转置矩阵。 11 | 矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 12 | 13 | Example 1: 14 | 输入:[[1,2,3],[4,5,6],[7,8,9]] 15 | 输出:[[1,4,7],[2,5,8],[3,6,9]] 16 | 17 | Example 2: 18 | 输入:[[1,2,3],[4,5,6]] 19 | 输出:[[1,4],[2,5],[3,6]] 20 | 21 | Note 22 | 1 <= A.length <= 1000 23 | 1 <= A[0].length <= 1000 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def transpose(self, A): 29 | """ 30 | :type A: List[List[int]] 31 | :rtype: List[List[int]] 32 | """ 33 | return [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))] 34 | -------------------------------------------------------------------------------- /QuestionBank/867.Transpose Matrix/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/31 14:04 4 | # @Author : cancan 5 | # @File : method_3.py 6 | # @Function : 转置矩阵 7 | 8 | """ 9 | Question: 10 | 给定一个矩阵 A, 返回 A 的转置矩阵。 11 | 矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 12 | 13 | Example 1: 14 | 输入:[[1,2,3],[4,5,6],[7,8,9]] 15 | 输出:[[1,4,7],[2,5,8],[3,6,9]] 16 | 17 | Example 2: 18 | 输入:[[1,2,3],[4,5,6]] 19 | 输出:[[1,4],[2,5],[3,6]] 20 | 21 | Note 22 | 1 <= A.length <= 1000 23 | 1 <= A[0].length <= 1000 24 | """ 25 | 26 | 27 | class Solution(object): 28 | def transpose(self, A): 29 | """ 30 | :type A: List[List[int]] 31 | :rtype: List[List[int]] 32 | """ 33 | return list(zip(*A)) 34 | -------------------------------------------------------------------------------- /QuestionBank/88.Merge Sorted Array/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # @Time : 2018/5/13 下午3:04 3 | # @Author : cancan 4 | # @File : method_2.py 5 | # @Function : 合并两个有序数组 6 | 7 | """ 8 | Question: 9 | 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 10 | 11 | Note: 12 | 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 13 | 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 14 | 15 | Example: 16 | 输入: 17 | nums1 = [1,2,3,0,0,0], m = 3 18 | nums2 = [2,5,6], n = 3 19 | 输出: [1,2,2,3,5,6] 20 | """ 21 | 22 | 23 | class Solution(object): 24 | def merge(self, nums1, m, nums2, n): 25 | """ 26 | :type nums1: List[int] 27 | :type m: int 28 | :type nums2: List[int] 29 | :type n: int 30 | :rtype: void Do not return anything, modify nums1 in-place instead. 31 | """ 32 | for i in range(n): 33 | nums1[m + i] = nums2[i] 34 | nums1.sort() 35 | -------------------------------------------------------------------------------- /QuestionBank/884.Uncommon Words from Two Sentences/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 16:51 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 两句话中的不常见单词 7 | 8 | 9 | """ 10 | Question: 11 | 给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。) 12 | 如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。 13 | 返回所有不常用单词的列表。 14 | 您可以按任何顺序返回列表。 15 | 16 | Example 1: 17 | 输入:A = "this apple is sweet", B = "this apple is sour" 18 | 输出:["sweet","sour"] 19 | 20 | Example 2: 21 | 输入:A = "apple apple", B = "banana" 22 | 输出:["banana"] 23 | 24 | Note: 25 | 0 <= A.length <= 200 26 | 0 <= B.length <= 200 27 | A 和 B 都只包含空格和小写字母。 28 | """ 29 | 30 | 31 | class Solution: 32 | def uncommonFromSentences(self, A, B): 33 | A = A.split(' ') 34 | B = B.split(' ') 35 | 36 | d = {} 37 | 38 | for i in A + B: 39 | if i in d: 40 | d[i] += 1 41 | else: 42 | d[i] = 1 43 | 44 | return [k for k, v in d.items() if v < 2] 45 | -------------------------------------------------------------------------------- /QuestionBank/9.Palindrome Number/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | Question: 5 | 确定一个整数是否为回文。 6 | """ 7 | 8 | 9 | class Solution(object): 10 | def isPalindrome(self, x): 11 | """ 12 | :type x: int 13 | :rtype: bool 14 | """ 15 | a = 0 - x 16 | 17 | if a < 0: 18 | q = str(x) 19 | elif a == 0: 20 | return True 21 | else: 22 | return False 23 | 24 | if len(str(x)) == 1: 25 | return True 26 | 27 | l = len(q) / 2 28 | 29 | if q[:l] == q[(0 - l):][::-1]: 30 | return True 31 | else: 32 | return False -------------------------------------------------------------------------------- /QuestionBank/9.Palindrome Number/method_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | Question: 6 | 确定一个整数是否为回文。 7 | """ 8 | 9 | 10 | class Solution(object): 11 | def isPalindrome(self, x): 12 | """ 13 | :type x: int 14 | :rtype: bool 15 | """ 16 | return str(x) == str(x)[::-1] -------------------------------------------------------------------------------- /QuestionBank/905.Sort Array By Parity/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 16:29 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 按奇偶排序数组 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。 12 | 你可以返回满足此条件的任何数组作为答案。 13 | 14 | Example: 15 | 输入:[3,1,2,4] 16 | 输出:[2,4,3,1] 17 | 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 18 | 19 | Note: 20 | 1 <= A.length <= 5000 21 | 0 <= A[i] <= 5000 22 | """ 23 | 24 | 25 | class Solution: 26 | def sortArrayByParity(self, A): 27 | ans = [] 28 | 29 | for i in A: 30 | 31 | if i % 2 == 0: 32 | ans.insert(0, i) 33 | else: 34 | ans.append(i) 35 | 36 | return ans 37 | -------------------------------------------------------------------------------- /QuestionBank/922.Sort Array By Parity II/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 15:03 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 按奇偶排序数组 II 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 12 | 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。 13 | 你可以返回任何满足上述条件的数组作为答案。 14 | 15 | Example: 16 | 输入:[4,2,5,7] 17 | 输出:[4,5,2,7] 18 | 解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。 19 | 20 | Note: 21 | 1. 2 <= A.length <= 20000 22 | 2. A.length % 2 == 0 23 | 3. 0 <= A[i] <= 1000 24 | """ 25 | 26 | 27 | class Solution: 28 | def sortArrayByParityII(self, A): 29 | ans = [0] * len(A) 30 | 31 | s1 = 0 32 | s2 = 1 33 | 34 | for i in A: 35 | 36 | if i % 2 == 0: 37 | ans[s1] = i 38 | s1 += 2 39 | else: 40 | ans[s2] = i 41 | s2 += 2 42 | 43 | return ans 44 | -------------------------------------------------------------------------------- /QuestionBank/94.Binary Tree Inorder Traversal/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 14:18 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 二叉树的中序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的中序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [1,3,2] 20 | """ 21 | 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.left = None 28 | # self.right = None 29 | 30 | class Solution: 31 | def inorderTraversal(self, root): 32 | """ 33 | :type root: TreeNode 34 | :rtype: List[int] 35 | """ 36 | self.r = [] 37 | self.traverse(root) 38 | return self.r 39 | 40 | def traverse(self, node): 41 | if not node: 42 | return 43 | self.traverse(node.left) 44 | self.r.append(node.val) 45 | self.traverse(node.right) -------------------------------------------------------------------------------- /QuestionBank/94.Binary Tree Inorder Traversal/method_3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2018/7/20 14:18 4 | # @Author : cancan 5 | # @File : method_2.py 6 | # @Function : 二叉树的中序遍历 7 | 8 | """ 9 | Question: 10 | 给定一个二叉树,返回它的中序 遍历。 11 | 12 | Example: 13 | 输入: [1,null,2,3] 14 | 1 15 | \ 16 | 2 17 | / 18 | 3 19 | 输出: [1,3,2] 20 | """ 21 | 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode: 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.left = None 28 | # self.right = None 29 | 30 | class Solution: 31 | def inorderTraversal(self, root): 32 | """ 33 | :type root: TreeNode 34 | :rtype: List[int] 35 | """ 36 | if root is None: 37 | return [] 38 | r = [] 39 | r.extend(self.inorderTraversal(root.left)) 40 | r.append(root.val) 41 | r.extend(self.inorderTraversal(root.right)) 42 | return r 43 | -------------------------------------------------------------------------------- /QuestionBank/942.DI String Match/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 14:41 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 增减字符串匹配 7 | 8 | 9 | """ 10 | Question: 11 | 给定只含 "I"(增大)或 "D"(减小)的字符串 S ,令 N = S.length。 12 | 返回 [0, 1, ..., N] 的任意排列 A 使得对于所有 i = 0, ..., N-1,都有: 13 | 如果 S[i] == "I",那么 A[i] < A[i+1] 14 | 如果 S[i] == "D",那么 A[i] > A[i+1] 15 | 16 | Example 1: 17 | 输出:"IDID" 18 | 输出:[0,4,1,3,2] 19 | 20 | Exmaple 2: 21 | 输出:"III" 22 | 输出:[0,1,2,3] 23 | 24 | Example 3: 25 | 输出:"DDI" 26 | 输出:[3,2,0,1] 27 | 28 | Note: 29 | 1. 1 <= S.length <= 1000 30 | 2. S 只包含字符 "I" 或 "D"。 31 | """ 32 | 33 | 34 | class Solution: 35 | def diStringMatch(self, S): 36 | N = len(S) 37 | 38 | ans = [i for i in range(N + 1)] 39 | 40 | for i, v in enumerate(S): 41 | 42 | if v == 'D': 43 | ans.insert(i, ans.pop()) 44 | 45 | return ans 46 | -------------------------------------------------------------------------------- /QuestionBank/961.N-Repeated Element in Size 2N Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 14:33 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 重复 N 次的元素 7 | 8 | 9 | """ 10 | Question: 11 | 在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。 12 | 返回重复了 N 次的那个元素。 13 | 14 | Example 1: 15 | 输入:[1,2,3,3] 16 | 输出:3 17 | 18 | Example 2: 19 | 输入:[2,1,2,5,3,2] 20 | 输出:2 21 | 22 | Example 3: 23 | 输入:[5,1,5,2,5,3,5,4] 24 | 输出:5 25 | 26 | Note: 27 | 1. 4 <= A.length <= 10000 28 | 2. 0 <= A[i] < 10000 29 | 3. A.length 为偶数 30 | """ 31 | 32 | 33 | class Solution: 34 | def repeatedNTimes(self, A): 35 | N = len(A) / 2 36 | 37 | d = {} 38 | 39 | for i in A: 40 | if i in d: 41 | d[i] += 1 42 | if d[i] == N: 43 | return i 44 | else: 45 | d[i] = 1 46 | -------------------------------------------------------------------------------- /QuestionBank/973.K Closest Points to Origin/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 10:40 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 最接近原点的 K 个点 7 | 8 | 9 | """ 10 | Question: 11 | 我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。 12 | (这里,平面上两点之间的距离是欧几里德距离。) 13 | 你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。 14 | 15 | Example 1: 16 | 输入:points = [[1,3],[-2,2]], K = 1 17 | 输出:[[-2,2]] 18 | 19 | 解释: 20 | (1, 3) 和原点之间的距离为 sqrt(10), 21 | (-2, 2) 和原点之间的距离为 sqrt(8), 22 | 由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。 23 | 我们只需要距离原点最近的 K = 1 个点,所以答案就是 [[-2,2]]。 24 | 25 | Example 2: 26 | 输入:points = [[3,3],[5,-1],[-2,4]], K = 2 27 | 输出:[[3,3],[-2,4]] 28 | (答案 [[-2,4],[3,3]] 也会被接受。) 29 | 30 | Note: 31 | 1. 1 <= K <= points.length <= 10000 32 | 2. -10000 < points[i][0] < 10000 33 | 3. -10000 < points[i][1] < 10000 34 | """ 35 | 36 | 37 | class Solution: 38 | def kClosest(self, points, K): 39 | return sorted(points, key=lambda x: x[0] ** 2 + x[1] ** 2)[:K] 40 | -------------------------------------------------------------------------------- /QuestionBank/976.Largest Perimeter Triangle/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 14:19 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 三角形的最大周长 7 | 8 | 9 | """ 10 | Question: 11 | 给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。 12 | 如果不能形成任何面积不为零的三角形,返回 0。 13 | 14 | Example 1: 15 | 输入:[2,1,2] 16 | 输出:5 17 | 18 | Example 2: 19 | 输入:[1,2,1] 20 | 输出:0 21 | 22 | Example 3: 23 | 输入:[3,2,3,4] 24 | 输出:10 25 | 26 | Example 4: 27 | 输入:[3,6,2,3] 28 | 输出:8 29 | 30 | Note: 31 | * 3 <= A.length <= 10000 32 | * 1 <= A[i] <= 10^6 33 | """ 34 | 35 | 36 | class Solution: 37 | def largestPerimeter(self, A): 38 | 39 | l = len(A) 40 | 41 | if l <= 2: 42 | return 0 43 | 44 | ans = 0 45 | 46 | A.sort(reverse=True) 47 | 48 | for i in range(l - 2): 49 | d = A[i] - A[i + 1] 50 | 51 | if A[i + 2] > d: 52 | return A[i] + A[i + 1] + A[i + 2] 53 | 54 | return ans 55 | -------------------------------------------------------------------------------- /QuestionBank/977.Squares of a Sorted Array/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 10:20 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 有序数组的平方 7 | 8 | 9 | """ 10 | Question: 11 | 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。 12 | 13 | Example 1: 14 | 输入:[-4,-1,0,3,10] 15 | 输出:[0,1,9,16,100] 16 | 17 | Example 2: 18 | 输入:[-7,-3,2,3,11] 19 | 输出:[4,9,9,49,121] 20 | 21 | Note: 22 | * 1 <= A.length <= 10000 23 | * -10000 <= A[i] <= 10000 24 | * A 已按非递减顺序排序。 25 | """ 26 | 27 | 28 | class Solution(object): 29 | def sortedSquares(self, A): 30 | """ 31 | :type A: List[int] 32 | :rtype: List[int] 33 | """ 34 | res = [i ** 2 for i in A] 35 | res.sort() 36 | return res 37 | -------------------------------------------------------------------------------- /QuestionBank/989.Add to Array-Form of Integer/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2019-03-21 11:57 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 数组形式的整数加法 7 | 8 | 9 | """ 10 | Question: 11 | 对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。 12 | 例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]。 13 | 给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。 14 | 15 | Example 1: 16 | 输入:A = [1,2,0,0], K = 34 17 | 输出:[1,2,3,4] 18 | 解释:1200 + 34 = 1234 19 | 20 | Example 2: 21 | 输入:A = [2,7,4], K = 181 22 | 输出:[4,5,5] 23 | 解释:274 + 181 = 455 24 | 25 | Example 3: 26 | 输入:A = [2,1,5], K = 806 27 | 输出:[1,0,2,1] 28 | 解释:215 + 806 = 1021 29 | 30 | Example 4: 31 | 输入:A = [9,9,9,9,9,9,9,9,9,9], K = 1 32 | 输出:[1,0,0,0,0,0,0,0,0,0,0] 33 | 解释:9999999999 + 1 = 10000000000 34 | 35 | 提示: 36 | * 1 <= A.length <= 10000 37 | * 0 <= A[i] <= 9 38 | * 0 <= K <= 10000 39 | * 如果 A.length > 1,那么 A[0] != 0 40 | """ 41 | 42 | 43 | class Solution: 44 | def addToArrayForm(self, A, K): 45 | s = ''.join(str(i) for i in A) 46 | 47 | return [int(i) for i in str(int(s) + K)] 48 | -------------------------------------------------------------------------------- /interviewQuestion/01.01.Is Unique LCCI/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/2/21 11:33 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 判定字符是否唯一 7 | 8 | ''' 9 | Question: 10 | 实现一个算法,确定一个字符串 s 的所有字符是否全都不同。 11 | 12 | Example 1: 13 | 输入: s = "leetcode" 14 | 输出: false 15 | 16 | Example 2: 17 | 输入: s = "abc" 18 | 输出: true 19 | 20 | Note: 21 | 1. 0 <= len(s) <= 100 22 | 2. 如果你不使用额外的数据结构,会很加分。 23 | ''' 24 | 25 | class Solution: 26 | def isUnique(self, astr: str) -> bool: 27 | return len(set(astr)) == len(list(astr)) 28 | -------------------------------------------------------------------------------- /interviewQuestion/16.01.Swap Numbers LCCI/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/7/15 21:34 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 交换数字 7 | 8 | """ 9 | Question: 10 | 编写一个函数,不用临时变量,直接交换numbers = [a, b]中a与b的值。 11 | 12 | Example: 13 | 输入: numbers = [1,2] 14 | 输出: [2,1] 15 | 16 | Note: 17 | numbers.length == 2 18 | """ 19 | 20 | from typing import List 21 | 22 | 23 | class Solution: 24 | def swapNumbers(self, numbers: List[int]) -> List[int]: 25 | numbers[0], numbers[1] = numbers[1], numbers[0] 26 | return numbers 27 | -------------------------------------------------------------------------------- /interviewQuestion/17.04.Missing Number LCCI/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2021/5/8 10:15 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 消失的数字 7 | 8 | """ 9 | 数组nums包含从0到n的所有整数,但其中缺了一个。请编写代码找出那个缺失的整数。你有办法在O(n)时间内完成吗? 10 | 注意:本题相对书上原题稍作改动 11 | 12 | 示例 1: 13 | 输入:[3,0,1] 14 | 输出:2 15 | 16 | 示例 2: 17 | 输入:[9,6,4,2,3,5,7,0,1] 18 | 输出:8 19 | """ 20 | 21 | from typing import List 22 | 23 | 24 | class Solution: 25 | def missingNumber(self, nums: List[int]) -> int: 26 | n = len(nums) 27 | s = n * (n + 1) // 2 28 | for v in nums: 29 | s -= v 30 | return s 31 | -------------------------------------------------------------------------------- /interviewQuestion/17.10.Find Majority Element LCCI/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2021/5/8 10:34 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 主要元素 7 | 8 | """ 9 | 数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。 10 | 11 | 示例 1: 12 | 输入:[1,2,5,9,5,9,5,5,5] 13 | 输出:5 14 | 15 | 示例 2: 16 | 输入:[3,2] 17 | 输出:-1 18 | 19 | 示例 3: 20 | 输入:[2,2,1,1,1,2,2] 21 | 输出:2 22 | """ 23 | 24 | from typing import List 25 | 26 | 27 | class Solution: 28 | def majorityElement(self, nums: List[int]) -> int: 29 | n = len(nums) // 2 30 | tmp = {} 31 | for v in nums: 32 | tmp[v] = tmp.get(v, 0) + 1 33 | if tmp[v] > n: 34 | return v 35 | 36 | return -1 37 | -------------------------------------------------------------------------------- /interviewQuestion/17.11.Find Closest LCCI/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/5/29 23:08 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 单词距离 7 | 8 | """ 9 | 有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗? 10 | 11 | Example: 12 | 输入:words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student" 13 | 输出:1 14 | 15 | Note: 16 | words.length <= 100000 17 | """ 18 | 19 | from typing import List 20 | 21 | 22 | class Solution: 23 | def findClosest(self, words: List[str], word1: str, word2: str) -> int: 24 | pre = -1 25 | ans = float('inf') 26 | for idx, v in enumerate(words): 27 | if v == word1 or v == word2: 28 | if pre != -1 and words[pre] != v: 29 | ans = min(ans, idx - pre) 30 | pre = idx 31 | return ans 32 | -------------------------------------------------------------------------------- /interviewQuestion/17.14.Smallest K LCCI/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2021/5/8 10:54 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 最小K个数 7 | 8 | """ 9 | 设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。 10 | 11 | 示例: 12 | 输入: arr = [1,3,5,7,2,4,6,8], k = 4 13 | 输出: [1,2,3,4] 14 | 15 | 提示: 16 | 0 <= len(arr) <= 100000 17 | 0 <= k <= min(100000, len(arr)) 18 | """ 19 | 20 | from typing import List 21 | 22 | 23 | class Solution: 24 | def smallestK(self, arr: List[int], k: int) -> List[int]: 25 | arr.sort() 26 | return arr[:k] 27 | -------------------------------------------------------------------------------- /interviewQuestion/剑指 Offer 64.求1+2+…+n/method_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2020/6/2 11:39 4 | # @Author : cancan 5 | # @File : method_1.py 6 | # @Function : 求1+2+…+n 7 | 8 | """ 9 | Question: 10 | 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 11 | 12 | Example 1: 13 | 输入: n = 3 14 | 输出: 6 15 | 16 | Example 2: 17 | 输入: n = 9 18 | 输出: 45 19 | 20 | Note: 21 | 1 <= n <= 10000 22 | """ 23 | 24 | class Solution: 25 | def sumNums(self, n: int) -> int: 26 | return int((1 + n) * n / 2) 27 | 28 | --------------------------------------------------------------------------------