├── .gitignore ├── Algorithms ├── 1.Two-Sum │ └── solution.cpp ├── 10.Regular-Expression-Matching │ └── solution.cpp ├── 100.Same-Tree │ └── solution.cpp ├── 101.Symmetric-Tree │ └── solution.cpp ├── 102.Binary-Tree-Level-Order-Traversal │ └── solution.cpp ├── 103.Binary-Tree-Zigzag-Level-Order-Traversal │ └── solution.cpp ├── 104.Maximum-Depth-of-Binary-Tree │ └── solution.cpp ├── 105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal │ └── solution.cpp ├── 106.Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal │ └── solution.cpp ├── 107.Binary-Tree-Level-Order-Traversal-II │ └── solution.cpp ├── 108.Convert-Sorted-Array-to-Binary-Search-Tree │ └── solution.cpp ├── 109.Convert-Sorted-List-to-Binary-Search-Tree │ └── solution.cpp ├── 11.Container-With-Most-Water │ └── solution.cpp ├── 110.Balanced-Binary-Tree │ └── solution.cpp ├── 111.Minimum-Depth-of-Binary-Tree │ └── solution.cpp ├── 112.Path-Sum │ └── solution.cpp ├── 113.Path-Sum-II │ └── solution.cpp ├── 114.Flatten-Binary-Tree-to-Linked-List │ └── solution.cpp ├── 115.Distinct-Subsequences │ └── solution.cpp ├── 116.Populating-Next-Right-Pointers-in-Each-Node │ └── solution.cpp ├── 117.Populating-Next-Right-Pointers-in-Each-Node-II │ └── solution.cpp ├── 118.Pascal's-Triangle │ └── solution.cpp ├── 119.Pascal's-Triangle-II │ └── solution.cpp ├── 12.Integer-to-Roman │ └── solution.cpp ├── 120.Triangle │ └── solution.cpp ├── 121.Best-Time-to-Buy-and-Sell-Stock │ └── solution.cpp ├── 122.Best-Time-to-Buy-and-Sell-Stock-II │ └── solution.cpp ├── 123.Best-Time-to-Buy-and-Sell-Stock-III │ └── solution.cpp ├── 124.Binary-Tree-Maximum-Path-Sum │ └── solution.cpp ├── 125.Valid-Palindrome │ └── solution.cpp ├── 126.Word-Ladder-II │ └── solution.cpp ├── 127.Word-Ladder │ └── solution.cpp ├── 128.Longest-Consecutive-Sequence │ └── solution.cpp ├── 129.Sum-Root-to-Leaf-Numbers │ └── solution.cpp ├── 13.Roman-to-Integer │ └── solution.cpp ├── 130.Surrounded-Regions │ └── solution.cpp ├── 131.Palindrome-Partitioning │ └── solution.cpp ├── 132.Palindrome-Partitioning-II │ └── solution.cpp ├── 133.Clone-Graph │ └── solution.cpp ├── 134.Gas-Station │ └── solution.cpp ├── 135.Candy │ └── solution.cpp ├── 136.Single-Number │ └── solution.cpp ├── 137.Single-Number-II │ └── solution.cpp ├── 138.Copy-List-with-Random-Pointer │ └── solution.cpp ├── 139.Word-Break │ └── solution.cpp ├── 14.Longest-Common-Prefix │ └── solution.cpp ├── 140.Word-Break-II │ └── solution.cpp ├── 141.Linked-List-Cycle │ └── solution.cpp ├── 142.Linked-List-Cycle-II │ └── solution.cpp ├── 143.Reorder-List │ └── solution.cpp ├── 144.Binary-Tree-Preorder-Traversal │ └── solution.cpp ├── 145.Binary-Tree-Postorder-Traversal │ └── solution.cpp ├── 146.LRU-Cache │ └── solution.cpp ├── 147.Insertion-Sort-List │ └── solution.cpp ├── 148.Sort-List │ └── solution.cpp ├── 149.Max-Points-on-a-Line │ └── solution.cpp ├── 15.3Sum │ └── solution.cpp ├── 150.Evaluate-Reverse-Polish-Notation │ └── solution.cpp ├── 151.Reverse-Words-in-a-String │ └── solution.cpp ├── 152.Maximum-Product-Subarray │ └── solution.cpp ├── 153.Find-Minimum-in-Rotated-Sorted-Array │ └── solution.cpp ├── 154.Find-Minimum-in-Rotated-Sorted-Array-II │ └── solution.cpp ├── 155.Min-Stack │ └── solution.cpp ├── 16.3Sum-Closest │ └── solution.cpp ├── 160.Intersection-of-Two-Linked-Lists │ └── solution.cpp ├── 162.Find-Peak-Element │ └── solution.cpp ├── 164.Maximum-Gap │ └── solution.cpp ├── 165.Compare-Version-Numbers │ └── solution.cpp ├── 166.Fraction-to-Recurring-Decimal │ └── solution.cpp ├── 167.Two-Sum-II---Input-array-is-sorted │ └── solution.cpp ├── 168.Excel-Sheet-Column-Title │ └── solution.cpp ├── 169.Majority-Element │ └── solution.cpp ├── 17.Letter-Combinations-of-a-Phone-Number │ └── solution.cpp ├── 171.Excel-Sheet-Column-Number │ └── solution.cpp ├── 172.Factorial-Trailing-Zeroes │ └── solution.cpp ├── 173.Binary-Search-Tree-Iterator │ └── solution.cpp ├── 174.Dungeon-Game │ └── solution.cpp ├── 179.Largest-Number │ └── solution.cpp ├── 18.4Sum │ └── solution.cpp ├── 187.Repeated-DNA-Sequences │ └── solution.cpp ├── 188.Best-Time-to-Buy-and-Sell-Stock-IV │ └── solution.cpp ├── 189.Rotate-Array │ └── solution.cpp ├── 19.Remove-Nth-Node-From-End-of-List │ └── solution.cpp ├── 190.Reverse-Bits │ └── solution.cpp ├── 191.Number-of-1-Bits │ └── solution.cpp ├── 198.House-Robber │ └── solution.cpp ├── 199.Binary-Tree-Right-Side-View │ └── solution.cpp ├── 2.Add-Two-Numbers │ └── solution.cpp ├── 20.Valid-Parentheses │ └── solution.cpp ├── 200.Number-of-Islands │ └── solution.cpp ├── 201.Bitwise-AND-of-Numbers-Range │ └── solution.cpp ├── 202.Happy-Number │ └── solution.cpp ├── 203.Remove-Linked-List-Elements │ └── solution.cpp ├── 204.Count-Primes │ └── solution.cpp ├── 205.Isomorphic-Strings │ └── solution.cpp ├── 206.Reverse-Linked-List │ └── solution.cpp ├── 207.Course-Schedule │ └── solution.cpp ├── 208.Implement-Trie-(Prefix-Tree) │ └── solution.cpp ├── 209.Minimum-Size-Subarray-Sum │ └── solution.cpp ├── 21.Merge-Two-Sorted-Lists │ └── solution.cpp ├── 210.Course-Schedule-II │ └── solution.cpp ├── 211.Add-and-Search-Word---Data-structure-design │ └── solution.cpp ├── 213.House-Robber-II │ └── solution.cpp ├── 214.Shortest-Palindrome │ └── solution.cpp ├── 215.Kth-Largest-Element-in-an-Array │ └── solution.cpp ├── 217.Contains-Duplicate │ └── solution.cpp ├── 219.Contains-Duplicate-II │ └── solution.cpp ├── 22.Generate-Parentheses │ └── solution.cpp ├── 220.Contains-Duplicate-III │ └── solution.cpp ├── 223.Rectangle-Area │ └── solution.cpp ├── 224.Basic-Calculator │ └── solution.cpp ├── 225.Implement-Stack-using-Queues │ └── solution.cpp ├── 226.Invert-Binary-Tree │ └── solution.cpp ├── 23.Merge-k-Sorted-Lists │ └── solution.cpp ├── 230.Kth-Smallest-Element-in-a-BST │ └── solution.cpp ├── 231.Power-of-Two │ └── solution.cpp ├── 232.Implement-Queue-using-Stacks │ └── solution.cpp ├── 234.Palindrome-Linked-List │ └── solution.cpp ├── 235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree │ └── solution.cpp ├── 237.Delete-Node-in-a-Linked-List │ └── solution.cpp ├── 238.Product-of-Array-Except-Self │ └── solution.cpp ├── 24.Swap-Nodes-in-Pairs │ └── solution.cpp ├── 241.Different-Ways-to-Add-Parentheses │ └── solution.cpp ├── 242.Valid-Anagram │ └── solution.cpp ├── 25.Reverse-Nodes-in-k-Group │ └── solution.cpp ├── 257.Binary-Tree-Paths │ └── solution.cpp ├── 258.Add-Digits │ └── solution.cpp ├── 26.Remove-Duplicates-from-Sorted-Array │ └── solution.cpp ├── 260.Single-Number-III │ └── solution.cpp ├── 263.Ugly-Number │ └── solution.cpp ├── 264.Ugly-Number-II │ └── solution.cpp ├── 27.Remove-Element │ └── solution.cpp ├── 273.Integer-to-English-Words │ └── solution.cpp ├── 274.H-Index │ └── solution.cpp ├── 278.First-Bad-Version │ └── solution.cpp ├── 28.Implement-strStr() │ └── solution.cpp ├── 283.Move-Zeroes │ └── solution.cpp ├── 287.Find-the-Duplicate-Number │ └── solution.cpp ├── 29.Divide-Two-Integers │ └── solution.cpp ├── 290.Word-Pattern │ └── solution.cpp ├── 292.Nim-Game │ └── solution.cpp ├── 299.Bulls-and-Cows │ └── solution.cpp ├── 3.Longest-Substring-Without-Repeating-Characters │ └── solution.cpp ├── 30.Substring-with-Concatenation-of-All-Words │ └── solution.cpp ├── 300.Longest-Increasing-Subsequence │ └── solution.cpp ├── 303.Range-Sum-Query---Immutable │ └── solution.cpp ├── 304.Range-Sum-Query-2D---Immutable │ └── solution.cpp ├── 309.Best-Time-to-Buy-and-Sell-Stock-with-Cooldown │ └── solution.cpp ├── 31.Next-Permutation │ └── solution.cpp ├── 318.Maximum-Product-of-Word-Lengths │ └── solution.cpp ├── 319.Bulb-Switcher │ └── solution.cpp ├── 32.Longest-Valid-Parentheses │ └── solution.cpp ├── 324.Wiggle-Sort-II │ └── solution.cpp ├── 326.Power-of-Three │ └── solution.cpp ├── 328.Odd-Even-Linked-List │ └── solution.cpp ├── 33.Search-in-Rotated-Sorted-Array │ └── solution.cpp ├── 338.Counting-Bits │ └── solution.cpp ├── 34.Find-First-and-Last-Position-of-Element-in-Sorted-Array │ └── solution.cpp ├── 342.Power-of-Four │ └── solution.cpp ├── 343.Integer-Break │ └── solution.cpp ├── 344.Reverse-String │ └── solution.cpp ├── 345.Reverse-Vowels-of-a-String │ └── solution.cpp ├── 347.Top-K-Frequent-Elements │ └── solution.cpp ├── 349.Intersection-of-Two-Arrays │ └── solution.cpp ├── 35.Search-Insert-Position │ └── solution.cpp ├── 350.Intersection-of-Two-Arrays-II │ └── solution.cpp ├── 357.Count-Numbers-with-Unique-Digits │ └── solution.cpp ├── 36.Valid-Sudoku │ └── solution.cpp ├── 367.Valid-Perfect-Square │ └── solution.cpp ├── 37.Sudoku-Solver │ └── solution.cpp ├── 371.Sum-of-Two-Integers │ └── solution.cpp ├── 374.Guess-Number-Higher-or-Lower │ └── solution.cpp ├── 378.Kth-Smallest-Element-in-a-Sorted-Matrix │ └── solution.cpp ├── 38.Count-and-Say │ └── solution.cpp ├── 382.Linked-List-Random-Node │ └── solution.cpp ├── 383.Ransom-Note │ └── solution.cpp ├── 384.Shuffle-an-Array │ └── solution.cpp ├── 387.First-Unique-Character-in-a-String │ └── solution.cpp ├── 389.Find-the-Difference │ └── solution.cpp ├── 39.Combination-Sum │ └── solution.cpp ├── 391.Perfect-Rectangle │ └── solution.cpp ├── 392.Is-Subsequence │ └── solution.cpp ├── 394.Decode-String │ └── solution.cpp ├── 396.Rotate-Function │ └── solution.cpp ├── 399.Evaluate-Division │ └── solution.cpp ├── 4.Median-of-Two-Sorted-Arrays │ └── solution.cpp ├── 40.Combination-Sum-II │ └── solution.cpp ├── 400.Nth-Digit │ └── solution.cpp ├── 401.Binary-Watch │ └── solution.cpp ├── 404.Sum-of-Left-Leaves │ └── solution.cpp ├── 405.Convert-a-Number-to-Hexadecimal │ └── solution.cpp ├── 406.Queue-Reconstruction-by-Height │ └── solution.cpp ├── 409.Longest-Palindrome │ └── solution.cpp ├── 41.First-Missing-Positive │ └── solution.cpp ├── 412.Fizz-Buzz │ └── solution.cpp ├── 413.Arithmetic-Slices │ └── solution.cpp ├── 414.Third-Maximum-Number │ └── solution.cpp ├── 415.Add-Strings │ └── solution.cpp ├── 419.Battleships-in-a-Board │ └── solution.cpp ├── 42.Trapping-Rain-Water │ └── solution.cpp ├── 423.Reconstruct-Original-Digits-from-English │ └── solution.cpp ├── 424.Longest-Repeating-Character-Replacement │ └── solution.cpp ├── 43.Multiply-Strings │ └── solution.cpp ├── 434.Number-of-Segments-in-a-String │ └── solution.cpp ├── 435.Non-overlapping-Intervals │ └── solution.cpp ├── 436.Find-Right-Interval │ └── solution.cpp ├── 437.Path-Sum-III │ └── solution.cpp ├── 438.Find-All-Anagrams-in-a-String │ └── solution.cpp ├── 44.Wildcard-Matching │ └── solution.cpp ├── 441.Arranging-Coins │ └── solution.cpp ├── 447.Number-of-Boomerangs │ └── solution.cpp ├── 448.Find-All-Numbers-Disappeared-in-an-Array │ └── solution.cpp ├── 45.Jump-Game-II │ └── solution.cpp ├── 452.Minimum-Number-of-Arrows-to-Burst-Balloons │ └── solution.cpp ├── 453.Minimum-Moves-to-Equal-Array-Elements │ └── solution.cpp ├── 455.Assign-Cookies │ └── solution.cpp ├── 459.Repeated-Substring-Pattern │ └── solution.cpp ├── 46.Permutations │ └── solution.cpp ├── 461.Hamming-Distance │ └── solution.cpp ├── 462.Minimum-Moves-to-Equal-Array-Elements-II │ └── solution.cpp ├── 463.Island-Perimeter │ └── solution.cpp ├── 47.Permutations-II │ └── solution.cpp ├── 471.Simplify-Path │ └── solution.cpp ├── 476.Number-Complement │ └── solution.cpp ├── 48.Rotate-Image │ └── solution.cpp ├── 485.Max-Consecutive-Ones │ └── solution.cpp ├── 49.Group-Anagrams │ └── solution.cpp ├── 496.Next-Greater-Element-I │ └── solution.cpp ├── 498.Diagonal-Traverse │ └── solution.cpp ├── 5.Longest-Palindromic-Substring │ └── solution.cpp ├── 50.Pow(x,-n) │ └── solution.cpp ├── 503.Next-Greater-Element-II │ └── solution.cpp ├── 506.Relative-Ranks │ └── solution.cpp ├── 51.N-Queens │ └── solution.cpp ├── 52.N-Queens-II │ └── solution.cpp ├── 523.Continuous-Subarray-Sum │ └── solution.cpp ├── 53.Maximum-Subarray │ └── solution.cpp ├── 54.Spiral-Matrix │ └── solution.cpp ├── 55.Jump-Game │ └── solution.cpp ├── 56.Merge-Intervals │ └── solution.cpp ├── 57.Insert-Interval │ └── solution.cpp ├── 58.Length-of-Last-Word │ └── solution.cpp ├── 59.Spiral-Matrix-II │ └── solution.cpp ├── 6.ZigZag-Conversion │ └── solution.cpp ├── 60.Permutation-Sequence │ └── solution.cpp ├── 61.Rotate-List │ └── solution.cpp ├── 62.Unique-Paths │ └── solution.cpp ├── 63.Unique-Paths-II │ └── solution.cpp ├── 64.Minimum-Path-Sum │ └── solution.cpp ├── 645.Set-Mismatch │ └── solution.cpp ├── 65.Valid-Number │ └── solution.cpp ├── 66.Plus-One │ └── solution.cpp ├── 67.Add-Binary │ └── solution.cpp ├── 674.Longest-Continuous-Increasing-Subsequence │ └── solution.cpp ├── 68.Text-Justification │ └── solution.cpp ├── 680.Valid-Palindrome-II │ └── solution.cpp ├── 69.Sqrt(x) │ └── solution.cpp ├── 7.Reverse-Integer │ └── solution.cpp ├── 70.Climbing-Stairs │ └── solution.cpp ├── 72.Edit-Distance │ └── solution.cpp ├── 73.Set-Matrix-Zeroes │ └── solution.cpp ├── 74.Search-a-2D-Matrix │ └── solution.cpp ├── 746.Min-Cost-Climbing-Stairs │ └── solution.cpp ├── 75.Sort-Colors │ └── solution.cpp ├── 76.Minimum-Window-Substring │ └── solution.cpp ├── 762.Prime-Number-of-Set-Bits-in-Binary-Representation │ └── solution.cpp ├── 77.Combinations │ └── solution.cpp ├── 78.Subsets │ └── solution.cpp ├── 79.Word-Search │ └── solution.cpp ├── 8.String-to-Integer-(atoi) │ └── solution.cpp ├── 80.Remove-Duplicates-from-Sorted-Array-II │ └── solution.cpp ├── 81.Search-in-Rotated-Sorted-Array-II │ └── solution.cpp ├── 82.Remove-Duplicates-from-Sorted-List-II │ └── solution.cpp ├── 824.Goat-Latin │ └── solution.cpp ├── 825.Friends-Of-Appropriate-Ages │ └── solution.cpp ├── 826.Most-Profit-Assigning-Work │ └── solution.cpp ├── 83.Remove-Duplicates-from-Sorted-List │ └── solution.cpp ├── 84.Largest-Rectangle-in-Histogram │ └── solution.cpp ├── 85.Maximal-Rectangle │ └── solution.cpp ├── 86.Partition-List │ └── solution.cpp ├── 87.Scramble-String │ └── solution.cpp ├── 88.Merge-Sorted-Array │ └── solution.cpp ├── 89.Gray-Code │ └── solution.cpp ├── 897.Increasing-Order-Search-Tree │ └── solution.cpp ├── 9.Palindrome-Number │ └── solution.cpp ├── 90.Subsets-II │ └── solution.cpp ├── 906.Super-Palindromes │ └── solution.cpp ├── 91.Decode-Ways │ └── solution.cpp ├── 914.X-of-a-Kind-in-a-Deck-of-Cards │ └── solution.cpp ├── 915.Partition-Array-into-Disjoint-Intervals │ └── solution.cpp ├── 917.Reverse-Only-Letters │ └── solution.cpp ├── 918.Maximum-Sum-Circular-Subarray │ └── solution.cpp ├── 919.Complete-Binary-Tree-Inserter │ └── solution.cpp ├── 92.Reverse-Linked-List-II │ └── solution.cpp ├── 925.Long-Pressed-Name │ └── solution.cpp ├── 926.Flip-String-to-Monotone-Increasing │ └── solution.cpp ├── 929.Unique-Email-Addresses │ └── solution.cpp ├── 93.Restore-IP-Addresses │ └── solution.cpp ├── 930.Binary-Subarrays-With-Sum │ └── solution.cpp ├── 933.Number-of-Recent-Calls │ └── solution.cpp ├── 934.Shortest-Bridge │ └── solution.cpp ├── 937.Reorder-Log-Files │ └── solution.cpp ├── 938.Range-Sum-of-BST │ └── solution.cpp ├── 939.Minimum-Area-Rectangle │ └── solution.cpp ├── 94.Binary-Tree-Inorder-Traversal │ └── solution.cpp ├── 940.Distinct-Subsequences-II │ └── solution.cpp ├── 941.Valid-Mountain-Array │ └── solution.cpp ├── 942.DI-String-Match │ └── solution.cpp ├── 943.Find-the-Shortest-Superstring │ └── solution.cpp ├── 944.Delete-Columns-to-Make-Sorted │ └── solution.cpp ├── 945.Minimum-Increment-to-Make-Array-Unique │ └── solution.cpp ├── 946.Validate-Stack-Sequences │ └── solution.cpp ├── 947.Most-Stones-Removed-with-Same-Row-or-Column │ └── solution.cpp ├── 948.Bag-of-Tokens │ └── solution.cpp ├── 949.Largest-Time-for-Given-Digits │ └── solution.cpp ├── 95.Unique-Binary-Search-Trees-II │ └── solution.cpp ├── 950.Reveal-Cards-In-Increasing-Order │ └── solution.cpp ├── 951.Flip-Equivalent-Binary-Trees │ └── solution.cpp ├── 952.Largest-Component-Size-by-Common-Factor │ └── solution.cpp ├── 953.Verifying-an-Alien-Dictionary │ └── solution.cpp ├── 954.Array-of-Doubled-Pairs │ └── solution.cpp ├── 955.Delete-Columns-to-Make-Sorted-II │ └── solution.cpp ├── 957.Prison-Cells-After-N-Days │ └── solution.cpp ├── 958.Check-Completeness-of-a-Binary-Tree │ └── solution.cpp ├── 959.Regions-Cut-By-Slashes │ └── solution.cpp ├── 96.Unique-Binary-Search-Trees │ └── solution.cpp ├── 97.Interleaving-String │ └── solution.cpp ├── 973.K-Closest-Points-to-Origin │ └── solution.cpp ├── 974.Subarray-Sums-Divisible-by-K │ └── solution.cpp ├── 976.Largest-Perimeter-Triangle │ └── solution.cpp ├── 98.Validate-Binary-Search-Tree │ └── solution.cpp └── 99.Recover-Binary-Search-Tree │ └── solution.cpp ├── LICENSE ├── README.md └── update.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /Algorithms/1.Two-Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector twoSum(vector &numbers, int target) 5 | { 6 | // 使用哈希表存储数组中的数值,key为数组中的数值,value为数组中数值对应下标 7 | unordered_map hash; 8 | vector result; 9 | for (int i = 0; i < numbers.size(); i++) 10 | { 11 | int numberToFind = target - numbers[i]; 12 | 13 | // 查找,若找到,则返回下标 14 | if (hash.find(numberToFind) != hash.end()) 15 | { 16 | result.push_back(hash[numberToFind]); 17 | result.push_back(i); 18 | return result; 19 | } 20 | 21 | //若没有找到,则将该值加入哈希表 22 | hash[numbers[i]] = i; 23 | } 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/10.Regular-Expression-Matching/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool match(string &s,string &p,int i,int j) 5 | { 6 | // pattern已匹配完,检查字符串是否匹配完 7 | if(j == p.size()) 8 | return i == s.size(); 9 | 10 | // pattern中,当前待匹配字符的后一个字符为'*'的情况 11 | if(p[j+1] == '*') 12 | { 13 | // 如果能匹配,则可以让'*'号重复0次或多重复1次;不能匹配,则让'*'号重复0次 14 | if((s[i] == p[j] || p[j] == '.') && ival == q->val) 22 | return dfs(p->left,q->left) && dfs(p->right,q->right); 23 | } 24 | return false; 25 | } 26 | 27 | bool isSameTree(TreeNode *p, TreeNode *q) 28 | { 29 | return dfs(p,q); 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/101.Symmetric-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | bool dfs(TreeNode *left,TreeNode *right) 14 | { 15 | if(!left && !right) 16 | return true; 17 | if((left && !right) || (!left && right) || (left->val!=right->val)) 18 | return false; 19 | return dfs(left->left,right->right) && dfs(left->right,right->left); 20 | } 21 | 22 | bool isSymmetric(TreeNode *root) 23 | { 24 | if(root==NULL || (!root->left && !root->right)) 25 | return true; 26 | return dfs(root->left,root->right); 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/104.Maximum-Depth-of-Binary-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | int maxDepth(TreeNode *root) 14 | { 15 | if(root == NULL) 16 | return 0; 17 | else 18 | return max(maxDepth(root->left),maxDepth(root->right))+1; 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/108.Convert-Sorted-Array-to-Binary-Search-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | TreeNode* createTree(vector &num,int left, int right) 14 | { 15 | if(left > right) 16 | return NULL; 17 | int mid = (left+right)/2; 18 | 19 | TreeNode *leftNode = createTree(num, left, mid - 1); 20 | TreeNode *rightNode = createTree(num, mid + 1, right); 21 | 22 | TreeNode *node = new TreeNode(num[mid]); 23 | 24 | node->left = leftNode; 25 | node->right = rightNode; 26 | 27 | return node; 28 | } 29 | 30 | TreeNode *sortedArrayToBST(vector &num) 31 | { 32 | return createTree(num,0,num.size()-1); 33 | } 34 | }; -------------------------------------------------------------------------------- /Algorithms/11.Container-With-Most-Water/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxArea(vector &height) 5 | { 6 | int left = 0; 7 | int right = height.size() -1; 8 | 9 | int maxArea = 0; 10 | while(left < right) 11 | { 12 | int area = (right - left)*min(height[left],height[right]); 13 | maxArea = max(maxArea,area); 14 | 15 | if(height[left] < height[right]) 16 | left++; 17 | else 18 | right--; 19 | } 20 | return maxArea; 21 | } 22 | }; -------------------------------------------------------------------------------- /Algorithms/110.Balanced-Binary-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | int isBalancedUtil(TreeNode* root, bool& isValid) 14 | { 15 | if(root == NULL) return 0; 16 | if(!isValid) return -1; 17 | int leftHeight = isBalancedUtil(root->left, isValid); 18 | int rightHeight = isBalancedUtil(root->right, isValid); 19 | if(abs(leftHeight-rightHeight) > 1) isValid = false; 20 | return max(leftHeight, rightHeight)+1; 21 | } 22 | bool isBalanced(TreeNode *root) 23 | { 24 | bool ans = true; 25 | isBalancedUtil(root, ans); 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/111.Minimum-Depth-of-Binary-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | int minDepth(TreeNode *root) 14 | { 15 | if(root == NULL) 16 | return 0; 17 | 18 | if(root->left == NULL) 19 | return minDepth(root->right)+1; 20 | else if(root->right == NULL) 21 | return minDepth(root->left)+1; 22 | else 23 | return min(minDepth(root->left), minDepth(root->right))+1; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/112.Path-Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool dfs(TreeNode *node, int sum, int curSum) 13 | { 14 | if (node == NULL) 15 | return false; 16 | 17 | if (node->left == NULL && node->right == NULL) 18 | return curSum + node->val == sum; 19 | 20 | return dfs(node->left, sum, curSum + node->val) 21 | || dfs(node->right, sum, curSum + node->val); 22 | } 23 | 24 | bool hasPathSum(TreeNode *root, int sum) 25 | { 26 | return dfs(root, sum, 0); 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/113.Path-Sum-II/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | vector > result; 14 | void dfs(TreeNode *node, int sum, vector curPath, int curSum) 15 | { 16 | if (node == NULL) 17 | return; 18 | 19 | curPath.push_back(node->val); 20 | 21 | if (node->left == NULL && node->right == NULL) 22 | { 23 | if(curSum + node->val == sum) 24 | result.push_back(curPath); 25 | return; 26 | } 27 | 28 | dfs(node->left, sum, curPath, curSum + node->val); 29 | dfs(node->right, sum, curPath, curSum + node->val); 30 | } 31 | 32 | vector > pathSum(TreeNode *root, int sum) 33 | { 34 | vector curPath; 35 | dfs(root,sum,curPath,0); 36 | return result; 37 | } 38 | }; -------------------------------------------------------------------------------- /Algorithms/114.Flatten-Binary-Tree-to-Linked-List/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | TreeNode *pre; 14 | Solution() 15 | { 16 | pre = NULL; 17 | } 18 | 19 | void flatten(TreeNode *root) 20 | { 21 | if(root==NULL) 22 | return; 23 | TreeNode *lastright=root->right; 24 | if(pre) 25 | { 26 | pre->left=NULL; 27 | pre->right=root; 28 | } 29 | pre=root; 30 | flatten(root->left); 31 | flatten(lastright); 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/115.Distinct-Subsequences/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numDistinct(string S, string T) 5 | { 6 | vector > cnt(T.length()+1,vector(S.length()+1)); 7 | for(int j=0; jleft == NULL) 15 | return; 16 | TreeLinkNode *p = root; 17 | while(p != NULL) 18 | { 19 | p->left->next = p->right; 20 | if(p->next) 21 | p->right->next = p->next->left; 22 | p = p->next; 23 | } 24 | connect(root->left); 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/118.Pascal's-Triangle/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > generate(int numRows) 5 | { 6 | vector > result; 7 | 8 | if(numRows == 0) 9 | return result; 10 | 11 | vector temp; 12 | temp.push_back(1); 13 | result.push_back(temp); 14 | if(numRows == 1) 15 | return result; 16 | 17 | temp.push_back(1); 18 | result.push_back(temp); 19 | if(numRows == 2) 20 | return result; 21 | 22 | for(int i=2;i temp; 25 | temp.push_back(1); 26 | for(int j=0;j getRow(int rowIndex) 5 | { 6 | vector > result; 7 | vector temp; 8 | 9 | temp.push_back(1); 10 | result.push_back(temp); 11 | if(rowIndex == 0) 12 | return result[0]; 13 | 14 | temp.push_back(1); 15 | result.push_back(temp); 16 | if(rowIndex == 1) 17 | return result[1]; 18 | 19 | for(int i=2;i temp; 22 | temp.push_back(1); 23 | for(int j=0;j& prices) 5 | { 6 | if(prices.size() == 0) 7 | return 0; 8 | int low = prices[0]; 9 | int ans = 0; 10 | for(int i=1; i ans) 15 | ans = prices[i] - low; 16 | } 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /Algorithms/122.Best-Time-to-Buy-and-Sell-Stock-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProfit(vector &prices) 5 | { 6 | int m = prices.size(); 7 | if(m == 0) 8 | return 0; 9 | 10 | int ret = 0; 11 | int buy = prices[0]; 12 | int last = prices[0]; 13 | for(int i = 1; i < m; i ++) 14 | { 15 | if(prices[i] < last) 16 | { 17 | ret += (last - buy); 18 | buy = prices[i]; 19 | } 20 | last = prices[i]; 21 | } 22 | ret += (last - buy); 23 | return ret; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/123.Best-Time-to-Buy-and-Sell-Stock-III/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProfit(vector &prices) 5 | { 6 | int size = prices.size(); 7 | if (size == 0) 8 | return 0; 9 | 10 | vector f1(size); 11 | vector f2(size); 12 | 13 | int minV = prices[0]; 14 | for (int i = 1; i < size; i++) 15 | { 16 | minV = std::min(minV, prices[i]); 17 | f1[i] = std::max(f1[i-1], prices[i] - minV); 18 | } 19 | 20 | int maxV = prices[size-1]; 21 | f2[size-1] = 0; 22 | for (int i = size-2; i >= 0; i--) 23 | { 24 | maxV = std::max(maxV, prices[i]); 25 | f2[i] = std::max(f2[i+1], maxV - prices[i]); 26 | } 27 | 28 | int sum = 0; 29 | for (int i = 0; i < size; i++) 30 | sum = std::max(sum, f1[i] + f2[i]); 31 | 32 | return sum; 33 | } 34 | }; -------------------------------------------------------------------------------- /Algorithms/124.Binary-Tree-Maximum-Path-Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | #define INT_MAX ((int)(~0U>>1)) 12 | #define INT_MIN (-INT_MAX - 1) 13 | 14 | class Solution 15 | { 16 | public: 17 | int max_sum; 18 | int max_path_sum(TreeNode*root) 19 | { 20 | if (!root) 21 | return 0; 22 | int i_left = max_path_sum(root->left); 23 | int i_right = max_path_sum(root->right); 24 | int sum = root->val; 25 | if (i_left > 0) 26 | sum += i_left; 27 | if (i_right > 0) 28 | sum += i_right; 29 | max_sum = max(sum,max_sum); 30 | return (max(i_left, i_right) > 0) ? (max(i_left, i_right) + root->val) : root->val; 31 | } 32 | 33 | int maxPathSum(TreeNode *root) 34 | { 35 | max_sum = INT_MIN; 36 | 37 | if (!root) 38 | return 0; 39 | max_path_sum(root); 40 | return max_sum; 41 | } 42 | }; -------------------------------------------------------------------------------- /Algorithms/125.Valid-Palindrome/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isPalindrome(string s) 5 | { 6 | if(s.length() == 0) 7 | return true; 8 | 9 | for(int i=0,j=s.length()-1;i'9' && s[i]<'A') 13 | || (s[i]>'Z' && s[i]<'a') 14 | || (s[i]>'z') ) 15 | && i'9' && s[j]<'A') 19 | || (s[j]>'Z' && s[j]<'a') 20 | || (s[j]>'z') ) 21 | && i &dict) 5 | { 6 | if(start.size() != end.size()) return 0; 7 | if(start.empty() || end.empty())return 0; 8 | 9 | queue path; 10 | path.push(start); 11 | int level = 1; 12 | int count = 1; 13 | dict.erase(start); 14 | while(dict.size() > 0 && !path.empty()) 15 | { 16 | string curword = path.front(); 17 | path.pop();count--; 18 | for(int i = 0; i < curword.size(); i++) 19 | { 20 | string tmp = curword; 21 | for(char j='a'; j<='z'; j++) 22 | { 23 | if(tmp[i]==j)continue; 24 | tmp[i] = j; 25 | if(tmp==end)return level+1; 26 | if(dict.find(tmp) != dict.end()) path.push(tmp); 27 | dict.erase(tmp); 28 | } 29 | } 30 | if(count==0) 31 | { 32 | count = path.size(); 33 | level++; 34 | } 35 | } 36 | return 0; 37 | } 38 | }; -------------------------------------------------------------------------------- /Algorithms/129.Sum-Root-to-Leaf-Numbers/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int result; 5 | void dfs(TreeNode *node,int tempVal) 6 | { 7 | tempVal = tempVal*10 + node->val; 8 | if(node->left || node->right) 9 | { 10 | if(node->left) 11 | dfs(node->left,tempVal); 12 | if(node->right) 13 | dfs(node->right,tempVal); 14 | } 15 | else 16 | result += tempVal; 17 | } 18 | 19 | int sumNumbers(TreeNode *root) 20 | { 21 | result = 0; 22 | if(root) 23 | dfs(root,0); 24 | else 25 | return 0; 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/13.Roman-to-Integer/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int romanToInt(string s) 5 | { 6 | int map[26]; 7 | map['I'-'A'] = 1; 8 | map['V'-'A'] = 5; 9 | map['X'-'A'] = 10; 10 | map['L'-'A'] = 50; 11 | map['C'-'A'] = 100; 12 | map['D'-'A'] = 500; 13 | map['M'-'A'] = 1000; 14 | 15 | int result = 0, n = s.size(); 16 | s.push_back(s[n-1]); 17 | for(int i = 0; i < n; i++) 18 | { 19 | if(map[s[i]-'A'] >= map[s[i+1]-'A']) 20 | result += map[s[i]-'A']; 21 | else result -= map[s[i]-'A']; 22 | } 23 | return result; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/132.Palindrome-Partitioning-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minCut(string s) 5 | { 6 | int n = s.size(); 7 | vector res(n+1); 8 | for(int i = 0 ; i< n + 1 ; ++i) 9 | { 10 | res[i] = i - 1; 11 | } 12 | vector > p(n, vector(n, false)); 13 | for(int i = 0; i< n; ++i) 14 | { 15 | for(int j = 0; j <= i ; ++j) 16 | { 17 | if(s[i] == s[j] && (i - j < 2 || p[j + 1][i - 1])) 18 | { 19 | p[j][i] = true; 20 | res[i + 1] = min(res[i + 1], res[j] + 1); 21 | } 22 | } 23 | } 24 | return res[n]; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/134.Gas-Station/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int canCompleteCircuit(vector &gas, vector &cost) 5 | { 6 | vector remainder; 7 | int sum =0; 8 | for(int i = 0; i < gas.size(); i++) 9 | { 10 | remainder.push_back(gas[i]-cost[i]); 11 | sum += gas[i]-cost[i]; 12 | } 13 | if(sum < 0) 14 | { 15 | return -1; 16 | } 17 | else 18 | { 19 | int start; 20 | int cur = 0; 21 | do 22 | { 23 | start = cur; 24 | int tmp = remainder[cur++]; 25 | while(tmp >= 0 && cur= 0 && cur == gas.size()) 34 | { 35 | return start; 36 | } 37 | } 38 | while(cur& nums) 5 | { 6 | set S; 7 | for(int i=0;i0) 10 | S.erase(nums[i]); 11 | else 12 | S.insert(nums[i]); 13 | } 14 | return *S.begin(); 15 | } 16 | }; -------------------------------------------------------------------------------- /Algorithms/137.Single-Number-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int singleNumber(vector& nums) 5 | { 6 | multiset S; 7 | for(int i=0;i1) 10 | S.erase(nums[i]); 11 | else 12 | S.insert(nums[i]); 13 | } 14 | return *S.begin(); 15 | } 16 | }; -------------------------------------------------------------------------------- /Algorithms/139.Word-Break/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool wordBreak(string s, unordered_set &dict) 5 | { 6 | int n = s.size(); 7 | vector dp(n + 1, false); 8 | dp[0] = true; 9 | for (int i = 0; i < n; i++) 10 | { 11 | if (dp[i]) 12 | { 13 | for (int len = 1; i + len - 1 < n; len++) 14 | { 15 | if (dict.count(s.substr(i, len)) > 0) 16 | dp[i + len] = true; 17 | } 18 | } 19 | } 20 | return dp[n]; 21 | } 22 | }; -------------------------------------------------------------------------------- /Algorithms/14.Longest-Common-Prefix/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string longestCommonPrefix(vector &strs) 5 | { 6 | if( strs.size() == 0) 7 | return ""; 8 | string prefix = strs[0]; 9 | for(int i = 0;inext; 19 | while(fast!=NULL && fast->next!=NULL) 20 | { 21 | if(slow==fast) 22 | return true; 23 | slow=slow->next; 24 | fast=fast->next->next; 25 | } 26 | return false; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/142.Linked-List-Cycle-II/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | ListNode *detectCycle(ListNode *head) 13 | { 14 | if(head == NULL) 15 | return NULL; 16 | ListNode* fast = head->next; 17 | ListNode* slow = head; 18 | while(fast != NULL && fast->next != NULL) 19 | { 20 | if(fast == slow) 21 | break; 22 | slow=slow->next; 23 | fast=fast->next->next; 24 | } 25 | if(fast == NULL || fast->next == NULL) 26 | return NULL; 27 | 28 | fast = head; 29 | slow = slow->next; 30 | while(fast != slow) 31 | { 32 | fast = fast->next; 33 | slow = slow->next; 34 | } 35 | return slow; 36 | } 37 | }; -------------------------------------------------------------------------------- /Algorithms/144.Binary-Tree-Preorder-Traversal/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | vector result; 14 | 15 | void dst(TreeNode *node) 16 | { 17 | if(node == NULL) 18 | return; 19 | else 20 | { 21 | result.push_back(node->val); 22 | dst(node->left); 23 | dst(node->right); 24 | } 25 | } 26 | 27 | vector preorderTraversal(TreeNode *root) 28 | { 29 | dst(root); 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /Algorithms/145.Binary-Tree-Postorder-Traversal/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | vector result; 14 | 15 | void dst(TreeNode *node) 16 | { 17 | if(node == NULL) 18 | return; 19 | else 20 | { 21 | dst(node->left); 22 | dst(node->right); 23 | result.push_back(node->val); 24 | } 25 | } 26 | 27 | vector postorderTraversal(TreeNode *root) 28 | { 29 | dst(root); 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /Algorithms/150.Evaluate-Reverse-Polish-Notation/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int evalRPN(vector& tokens) 5 | { 6 | stack fuckYou; 7 | for(int i=0;i> temp; 14 | fuckYou.push(temp); 15 | } 16 | else 17 | { 18 | int b = fuckYou.empty()? 0:fuckYou.top(); 19 | fuckYou.pop(); 20 | int a = fuckYou.empty()? 0:fuckYou.top(); 21 | fuckYou.pop(); 22 | if(tokens[i] == "+") 23 | fuckYou.push(a+b); 24 | if(tokens[i] == "-") 25 | fuckYou.push(a-b); 26 | if(tokens[i] == "*") 27 | fuckYou.push(a*b); 28 | if(tokens[i] == "/") 29 | fuckYou.push(a/b); 30 | } 31 | } 32 | return fuckYou.top(); 33 | } 34 | }; -------------------------------------------------------------------------------- /Algorithms/151.Reverse-Words-in-a-String/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void reverseWords(string & s) 5 | { 6 | string ss; 7 | int i = s.length()-1; 8 | while(i>=0) 9 | { 10 | while(i>=0&&s[i] == ' ') 11 | { 12 | i --; 13 | } 14 | if(i<0) break; 15 | if(ss.length()!=0) 16 | ss.push_back(' '); 17 | string temp ; 18 | for(;i>=0&&s[i]!=' ';i--) 19 | temp.push_back(s[i]); 20 | reverse(temp.begin(),temp.end()); 21 | ss.append(temp); 22 | } 23 | s=ss; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/152.Maximum-Product-Subarray/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProduct(int A[], int n) 5 | { 6 | if(n==0) 7 | return 0; 8 | if(n==1) 9 | return A[0]; 10 | int curMax = A[0]; 11 | int curMin = A[0]; 12 | int ans = A[0]; 13 | for(int i=1;i &num) 5 | { 6 | if(num.size() == 1) 7 | return num[0]; 8 | 9 | int midPos = num.size()/2; 10 | int left = 0; 11 | int right = num.size()-1; 12 | 13 | int minEle = num[0]; 14 | while(left < midPos && midPos < right) 15 | { 16 | if(num[left] > num[midPos]) 17 | { 18 | right = midPos; 19 | midPos = (left+right)/2; 20 | } 21 | else if(num[midPos] > num[right]) 22 | { 23 | left = midPos; 24 | midPos = (left+right)/2; 25 | } 26 | else 27 | { 28 | minEle = num[left]; 29 | break; 30 | } 31 | } 32 | 33 | if(num[left] < num[right]) 34 | minEle = num[left]; 35 | else 36 | minEle = num[right]; 37 | 38 | return minEle; 39 | } 40 | }; -------------------------------------------------------------------------------- /Algorithms/154.Find-Minimum-in-Rotated-Sorted-Array-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findMin(vector &num) 5 | { 6 | if(num.empty()) 7 | return 0; 8 | else if(num.size() == 1) 9 | return num[0]; 10 | else 11 | { 12 | for(vector::size_type st = 1; st < num.size(); st ++) 13 | { 14 | if(num[st-1] > num[st]) 15 | return num[st]; 16 | } 17 | return num[0]; 18 | } 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/155.Min-Stack/solution.cpp: -------------------------------------------------------------------------------- 1 | class MinStack 2 | { 3 | private: 4 | std::stack stack; 5 | std::stack min_stack; 6 | public: 7 | void push(int x) 8 | { 9 | stack.push(x); 10 | if (min_stack.empty() || ((!min_stack.empty()) && x <= min_stack.top())) 11 | { 12 | min_stack.push(x); 13 | } 14 | } 15 | 16 | void pop() 17 | { 18 | if (!stack.empty()) 19 | { 20 | if (stack.top() == min_stack.top()) 21 | min_stack.pop(); 22 | stack.pop(); 23 | } 24 | } 25 | 26 | int top() 27 | { 28 | if (!stack.empty()) 29 | return stack.top(); 30 | } 31 | 32 | int getMin() 33 | { 34 | if (!min_stack.empty()) 35 | return min_stack.top(); 36 | } 37 | }; -------------------------------------------------------------------------------- /Algorithms/16.3Sum-Closest/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int threeSumClosest(vector &num, int target) 5 | { 6 | int closestSum = num[0]+num[1]+num[2]; 7 | sort(num.begin(),num.end()); 8 | 9 | for( int num1pos = 0; num1pos &num) 5 | { 6 | int left=0,right=num.size()-1; 7 | while(left<=right){ 8 | if(left==right) 9 | return left; 10 | int mid=(left+right)/2; 11 | if(num[mid]lev2){ 30 | return 1; 31 | }else if(lev1 twoSum(vector& numbers, int target) 5 | { 6 | int left=0,right=numbers.size()-1; 7 | while(numbers[left]+numbers[right] != target) 8 | { 9 | if(numbers[left]+numbers[right] < target) 10 | left++; 11 | else 12 | right--; 13 | } 14 | vector result; 15 | result.push_back(left+1); 16 | result.push_back(right+1); 17 | return result; 18 | } 19 | }; 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Algorithms/168.Excel-Sheet-Column-Title/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string convertToTitle(int n) 5 | { 6 | if(n < 1) 7 | return ""; 8 | else 9 | { 10 | string result = ""; 11 | while(n) 12 | { 13 | n --; 14 | char c = n%26 + 'A'; 15 | result += c; 16 | n /= 26; 17 | } 18 | reverse(result.begin(), result.end()); 19 | return result; 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Algorithms/169.Majority-Element/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int majorityElement(vector &num) 5 | { 6 | int n = num.size(); 7 | sort(num.begin(),num.end()); 8 | return num[n/2]; 9 | } 10 | }; -------------------------------------------------------------------------------- /Algorithms/17.Letter-Combinations-of-a-Phone-Number/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector letterCombinations(string digits) 5 | { 6 | vector result; 7 | if(digits == "") 8 | return result; 9 | 10 | result.push_back(""); 11 | 12 | vector dict(10); 13 | dict[2] = "abc"; 14 | dict[3] = "def"; 15 | dict[4] = "ghi"; 16 | dict[5] = "jkl"; 17 | dict[6] = "mno"; 18 | dict[7] = "pqrs"; 19 | dict[8] = "tuv"; 20 | dict[9] = "wxyz"; 21 | 22 | for(int i = 0; i < digits.size(); i ++) 23 | { 24 | int size = result.size(); 25 | for(int j = 0; j < size; j ++) 26 | { 27 | string current = result[0]; 28 | result.erase(result.begin()); 29 | for(int k = 0; k < dict[digits[i]-'0'].size(); k ++) 30 | result.push_back(current + dict[digits[i]-'0'][k]); 31 | } 32 | } 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /Algorithms/171.Excel-Sheet-Column-Number/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int titleToNumber(string s) 5 | { 6 | if(!s.length()) 7 | return 0; 8 | 9 | int result = 0; 10 | for(int i=0;i sta; 14 | public: 15 | BSTIterator(TreeNode *root) 16 | { 17 | while(!sta.empty()) 18 | sta.pop(); 19 | while(root) 20 | { 21 | sta.push(root); 22 | root = root->left; 23 | } 24 | } 25 | 26 | /** @return whether we have a next smallest number */ 27 | bool hasNext() { 28 | return !sta.empty(); 29 | } 30 | 31 | /** @return the next smallest number */ 32 | int next() 33 | { 34 | TreeNode *tmp=sta.top(); 35 | sta.pop(); 36 | int ret = tmp->val; 37 | tmp = tmp->right; 38 | while(tmp) 39 | { 40 | sta.push(tmp); 41 | tmp = tmp->left; 42 | } 43 | return ret; 44 | } 45 | }; 46 | 47 | /** 48 | * Your BSTIterator will be called like this: 49 | * BSTIterator i = BSTIterator(root); 50 | * while (i.hasNext()) cout << i.next(); 51 | */ -------------------------------------------------------------------------------- /Algorithms/174.Dungeon-Game/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int calculateMinimumHP(vector > &dungeon) 5 | { 6 | int m = dungeon.size(); 7 | int n = dungeon[0].size(); 8 | dungeon[m-1][n-1] = max(0-dungeon[m-1][n-1], 0); 9 | for (int i = m - 2; i >= 0; --i) 10 | { 11 | dungeon[i][n-1] = max(dungeon[i+1][n-1]-dungeon[i][n-1], 0); 12 | } 13 | for (int j = n - 2; j >= 0; --j) 14 | { 15 | dungeon[m-1][j] = max(dungeon[m-1][j+1]-dungeon[m-1][j], 0); 16 | } 17 | for (int i = m - 2; i >= 0; --i) 18 | { 19 | for (int j = n - 2; j >= 0; --j) 20 | { 21 | dungeon[i][j] = max(min(dungeon[i][j+1], dungeon[i+1][j])-dungeon[i][j], 0); 22 | } 23 | } 24 | return dungeon[0][0] + 1; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/179.Largest-Number/solution.cpp: -------------------------------------------------------------------------------- 1 | bool cmp(const string s1, const string s2) 2 | { 3 | return (s1 + s2) > (s2 + s1); 4 | } 5 | 6 | class Solution 7 | { 8 | public: 9 | string largestNumber(vector &num) 10 | { 11 | vector s_num(num.size()); 12 | stringstream stream; 13 | for (int i = 0; i < num.size(); ++i) 14 | { 15 | stream << num[i]; 16 | stream >> s_num[i]; 17 | stream.clear(); 18 | } 19 | sort(s_num.begin(), s_num.end(), cmp); 20 | string tmp_res; 21 | for (int i = 0; i < s_num.size(); ++i) 22 | { 23 | tmp_res += s_num[i]; 24 | } 25 | string res; 26 | bool flag = false; 27 | for (int i = 0; i < tmp_res.size(); ++i) 28 | { 29 | if (tmp_res[i] != '0') 30 | { 31 | res.push_back(tmp_res[i]); 32 | flag = true; 33 | } 34 | else if (flag) 35 | { 36 | res.push_back(tmp_res[i]); 37 | } 38 | } 39 | if (!flag) 40 | res.push_back('0'); 41 | return res; 42 | } 43 | }; -------------------------------------------------------------------------------- /Algorithms/187.Repeated-DNA-Sequences/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int getVal(char ch) 5 | { 6 | if (ch == 'A') return 0; 7 | if (ch == 'C') return 1; 8 | if (ch == 'G') return 2; 9 | if (ch == 'T') return 3; 10 | return 0; 11 | } 12 | 13 | vector findRepeatedDnaSequences(string s) 14 | { 15 | set st; 16 | vector res; 17 | string str; 18 | if (s.length() < 10 || s == "") 19 | return res; 20 | int mp[1024*1024] = {0}; 21 | unsigned int val = 0; 22 | for (int i = 0; i < 9; ++i) 23 | { 24 | val <<= 2; 25 | val |= getVal(s[i]); 26 | } 27 | for (int i = 9; i < s.length(); ++i) 28 | { 29 | val <<= 14; 30 | val >>= 12; 31 | val |= getVal(s[i]); 32 | ++mp[val]; 33 | if (mp[val] > 1) 34 | { 35 | str = s.substr(i-9, 10); 36 | st.insert(str); 37 | } 38 | } 39 | for (set::iterator i = st.begin(); i != st.end(); ++i) 40 | { 41 | res.push_back(*i); 42 | } 43 | return res; 44 | } 45 | }; -------------------------------------------------------------------------------- /Algorithms/188.Best-Time-to-Buy-and-Sell-Stock-IV/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProfit(int k, vector &prices) 5 | { 6 | if(prices.empty() || k == 0) 7 | return 0; 8 | 9 | if(k >= prices.size()) 10 | return solveMaxProfit(prices); 11 | 12 | vector global(k + 1, 0); 13 | vector local(k + 1, 0); 14 | 15 | for(int i = 1; i < prices.size(); i++) 16 | { 17 | int diff = prices[i] - prices[i - 1]; 18 | for(int j = k; j >= 1; j--) 19 | { 20 | local[j] = max(local[j] + diff, global[j - 1] + max(diff, 0)); 21 | global[j] = max(global[j], local[j]); 22 | } 23 | } 24 | 25 | return global[k]; 26 | } 27 | private: 28 | int solveMaxProfit(vector &prices) 29 | { 30 | int res = 0; 31 | for(int i = 1; i < prices.size(); i++) 32 | { 33 | int diff = prices[i] - prices[i - 1]; 34 | if(diff > 0) 35 | res += diff; 36 | } 37 | return res; 38 | } 39 | }; -------------------------------------------------------------------------------- /Algorithms/189.Rotate-Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void rotate(int nums[], int n, int k) 5 | { 6 | k = k % n; 7 | if (k == 0) return; 8 | int *temp = new int[n]; 9 | memcpy(temp, nums+(n-k), sizeof(int)*k); 10 | memcpy(temp+k, nums, sizeof(int)*(n-k)); 11 | memcpy(nums, temp, sizeof(int)*n); 12 | delete[] temp; 13 | } 14 | }; -------------------------------------------------------------------------------- /Algorithms/19.Remove-Nth-Node-From-End-of-List/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | ListNode *removeNthFromEnd(ListNode *head, int n) 13 | { 14 | ListNode *tempHead = new ListNode(0); 15 | tempHead->next = head; 16 | ListNode *first = tempHead, *second = tempHead; 17 | 18 | for(int i = 0; i < n+1; i++) 19 | first = first -> next; 20 | 21 | while(first) 22 | { 23 | first = first -> next; 24 | second = second -> next; 25 | } 26 | 27 | second->next = second->next->next; 28 | return tempHead->next; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/190.Reverse-Bits/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | uint32_t reverseBits(uint32_t n) 5 | { 6 | int result = 0; 7 | for(int i=0;i<32;i++) 8 | { 9 | result <<= 1; 10 | result += n & 1; 11 | n >>= 1; 12 | } 13 | return result; 14 | } 15 | }; -------------------------------------------------------------------------------- /Algorithms/191.Number-of-1-Bits/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int result = 0; 5 | while(n) 6 | { 7 | result += n & 0b1? 1:0; 8 | n >>= 1; 9 | } 10 | return result; 11 | 12 | } 13 | }; -------------------------------------------------------------------------------- /Algorithms/198.House-Robber/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int rob(vector& nums) 5 | { 6 | vector DP(nums.size()); 7 | 8 | if(nums.size()==0) 9 | return 0; 10 | if(nums.size()==1) 11 | return nums[0]; 12 | 13 | DP[0] = nums[0]; 14 | DP[1] = max(nums[0],nums[1]); 15 | for(int i=2;i rightSideView(TreeNode *root) 14 | { 15 | vector ans; 16 | if (root == NULL) 17 | return ans; 18 | queue que; 19 | que.push(root); 20 | TreeNode* curr; 21 | while(!que.empty()) 22 | { 23 | int cnt = que.size(); 24 | for (int i = 0; i < cnt; i++) 25 | { 26 | curr = que.front(); que.pop(); 27 | if (curr->left) 28 | { 29 | que.push(curr->left); 30 | } 31 | if (curr->right) 32 | { 33 | que.push(curr->right); 34 | } 35 | } 36 | ans.push_back(curr->val); 37 | } 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /Algorithms/20.Valid-Parentheses/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValid(string s) 5 | { 6 | stack stk; 7 | for(int i=0;i> &grid, int x, int y) 5 | { 6 | if (x < 0 || x >= grid.size()) 7 | return; 8 | if (y < 0 || y >= grid[0].size()) 9 | return; 10 | if (grid[x][y] != '1') 11 | return; 12 | grid[x][y] = 'X'; 13 | dfs(grid, x + 1, y); 14 | dfs(grid, x - 1, y); 15 | dfs(grid, x, y + 1); 16 | dfs(grid, x, y - 1); 17 | } 18 | 19 | int numIslands(vector> &grid) 20 | { 21 | if (grid.empty() || grid[0].empty()) 22 | return 0; 23 | int N = grid.size(), M = grid[0].size(); 24 | int cnt = 0; 25 | for (int i = 0; i < N; ++i) 26 | { 27 | for (int j = 0; j < M; ++j) 28 | { 29 | if (grid[i][j] == '1') 30 | { 31 | dfs(grid, i, j); 32 | ++cnt; 33 | } 34 | } 35 | } 36 | return cnt; 37 | } 38 | }; -------------------------------------------------------------------------------- /Algorithms/201.Bitwise-AND-of-Numbers-Range/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int rangeBitwiseAnd(int m, int n) 5 | { 6 | int offset = 0; 7 | while (m && n) 8 | { 9 | if (m == n) 10 | { 11 | return m << offset; 12 | } 13 | m >>= 1; 14 | n >>= 1; 15 | offset++; 16 | } 17 | return 0; 18 | } 19 | }; -------------------------------------------------------------------------------- /Algorithms/202.Happy-Number/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isHappy(int n) 5 | { 6 | while(n>6) 7 | { 8 | int sum=0; 9 | while(n) 10 | { 11 | sum+=(n%10)*(n%10); 12 | n/=10; 13 | } 14 | n=sum; 15 | } 16 | return n==1; 17 | } 18 | }; -------------------------------------------------------------------------------- /Algorithms/203.Remove-Linked-List-Elements/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | ListNode* removeElements(ListNode* head, int val) 13 | { 14 | ListNode *temp = NULL; 15 | while(head != NULL && head->val == val) 16 | { 17 | temp = head; 18 | head = head->next; 19 | delete(temp); 20 | } 21 | 22 | if(head == NULL) 23 | return NULL; 24 | 25 | ListNode *cur = head->next ,*last = head; 26 | while(cur != NULL) 27 | { 28 | if(cur->val == val) 29 | { 30 | temp = cur; 31 | last->next = cur->next; 32 | cur = cur->next; 33 | delete temp; 34 | } 35 | else 36 | { 37 | last = cur; 38 | cur = cur->next; 39 | } 40 | } 41 | return head; 42 | } 43 | }; -------------------------------------------------------------------------------- /Algorithms/204.Count-Primes/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int countPrimes(int n) 5 | { 6 | vector flag(n,true); 7 | flag[0]=false; 8 | if(n<2) 9 | return 0; 10 | flag[1]=false; 11 | int count = 0; 12 | for(int i=2;i m1; 8 | map m2; 9 | bool flag = true; 10 | for(int i=0; inext == NULL) 15 | return head; 16 | ListNode Result(0); 17 | ListNode *p = head; 18 | while (p) 19 | { 20 | ListNode *q = p->next; 21 | p->next = Result.next; 22 | Result.next = p; 23 | p = q; 24 | } 25 | return Result.next; 26 | } 27 | }; -------------------------------------------------------------------------------- /Algorithms/209.Minimum-Size-Subarray-Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minSubArrayLen(int s, vector& nums) 5 | { 6 | int length = nums.size()+1; 7 | int startIndex = 0, endIndex = 0; 8 | int sum = 0; 9 | while(endIndex < nums.size()) 10 | { 11 | while(endIndex < nums.size() && sum < s) 12 | { 13 | sum += nums[endIndex]; 14 | endIndex += 1; 15 | } 16 | while(startIndex < endIndex && sum >= s) 17 | { 18 | if( sum >= s) 19 | length = min(length,endIndex - startIndex); 20 | sum -= nums[startIndex]; 21 | startIndex += 1; 22 | } 23 | } 24 | return length <= nums.size()? length:0; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/21.Merge-Two-Sorted-Lists/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 13 | { 14 | ListNode *head = new ListNode(0); 15 | ListNode *point = head; 16 | while(l1 && l2) 17 | { 18 | if(l1->val < l2-> val) 19 | { 20 | point->next = l1; 21 | l1 = l1->next; 22 | } 23 | else 24 | { 25 | point->next = l2; 26 | l2 = l2->next; 27 | } 28 | point = point->next; 29 | } 30 | if(!l1) 31 | point->next = l2; 32 | else 33 | point->next = l1; 34 | return head->next; 35 | } 36 | }; -------------------------------------------------------------------------------- /Algorithms/213.House-Robber-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | if(nums.size() == 0) 5 | return 0; 6 | if(nums.size() == 1) 7 | return nums[0]; 8 | if(nums.size() == 2) 9 | return max(nums[0], nums[1]); 10 | 11 | vector dp(nums.size(),0); 12 | dp[0] = nums[0]; 13 | dp[1] = max(nums[0],nums[1]); 14 | 15 | for(int i=2;i vec(len2, 0); 9 | for(int i = 1; i < len2; i++) 10 | { 11 | int k = vec[i-1]; 12 | while(k > 0 && str[k] != str[i]) k = vec[k-1]; 13 | vec[i] = (k += str[i] == str[k]); 14 | } 15 | return str.substr(len1+1, len1-vec[len2-1]) + s; 16 | } 17 | }; -------------------------------------------------------------------------------- /Algorithms/215.Kth-Largest-Element-in-an-Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findKthLargest(vector& nums, int k) 5 | { 6 | int L = 0, R = nums.size()-1; 7 | while(L < R) 8 | { 9 | int left = L, right = R; 10 | int key = nums[left]; 11 | while(left < right) 12 | { 13 | while(left < right && nums[right] < key) 14 | right--; 15 | nums[left] = nums[right]; 16 | while(left < right && nums[left] >= key) 17 | left++; 18 | nums[right] = nums[left]; 19 | } 20 | nums[left] = key; 21 | if(left == k -1) 22 | return nums[k-1]; 23 | else if (left > k-1) 24 | R = left - 1; 25 | else 26 | L = left + 1; 27 | } 28 | return nums[k-1]; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/217.Contains-Duplicate/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool containsDuplicate(vector& nums) 5 | { 6 | return nums.size() > set(nums.begin(), nums.end()).size(); 7 | } 8 | }; -------------------------------------------------------------------------------- /Algorithms/219.Contains-Duplicate-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool containsNearbyDuplicate(vector& nums, int k) 5 | { 6 | set s; 7 | int start = 0, end = 0; 8 | 9 | for(int i=0;i k) 22 | { 23 | s.erase(nums[start]); 24 | start++; 25 | } 26 | } 27 | return false; 28 | } 29 | }; -------------------------------------------------------------------------------- /Algorithms/22.Generate-Parentheses/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void generate(vector &strList, string str, int k, int length) 5 | { 6 | if(str.size() == length) 7 | { 8 | if(k==0) strList.push_back(str); 9 | return; 10 | } 11 | if(k>0) 12 | { 13 | generate(strList, str+')', k-1, length); 14 | } 15 | generate(strList, str+'(', k+1, length); 16 | } 17 | 18 | vector generateParenthesis(int n) 19 | { 20 | vector strList; 21 | string str; 22 | generate(strList, str, 0, n*2); 23 | return strList; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/220.Contains-Duplicate-III/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) 5 | { 6 | if(t < 0 | k <1) 7 | return false; 8 | 9 | int i,key; 10 | unordered_map dict; 11 | 12 | for(i =0; i < nums.size(); i++) 13 | { 14 | key = nums[i]/max(1,t); 15 | //map::iterator it; 16 | if( (dict.find(key) != dict.end() && abs(nums[i] - dict[key]) <= t) || 17 | (dict.find(key-1) != dict.end() && abs((long)nums[i] - (long)dict[key-1]) <= t) || 18 | (dict.find(key+1) !=dict.end() && abs(nums[i] - dict[key+1]) <= t)) 19 | { 20 | return true; 21 | } 22 | 23 | dict.insert(pair(key,nums[i])); 24 | 25 | if(i >= k) 26 | { 27 | dict.erase(nums[i-k]/max(1,t)); //删除窗口大小之外的键值 28 | } 29 | 30 | } 31 | return false; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/226.Invert-Binary-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | TreeNode* invertTree(TreeNode* root) 14 | { 15 | if(root == NULL) 16 | return NULL; 17 | else 18 | { 19 | TreeNode* left = invertTree(root->right); 20 | TreeNode* right = invertTree(root->left); 21 | root->left = left; 22 | root->right = right; 23 | return root; 24 | } 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/230.Kth-Smallest-Element-in-a-BST/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | int kthSmallest(TreeNode* root, int k) 14 | { 15 | return InOrder(root,k); 16 | } 17 | int InOrder(TreeNode* root,int &k) 18 | { 19 | if(root) 20 | { 21 | int r1 = InOrder(root->left,k); 22 | k--; 23 | if(k==0) 24 | return root->val; 25 | int r2 = InOrder(root->right,k); 26 | return r1+r2; 27 | } 28 | return 0; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/231.Power-of-Two/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) 4 | { 5 | if(n <= 0) return false; 6 | return (n & (n-1)) == 0; 7 | } 8 | }; -------------------------------------------------------------------------------- /Algorithms/232.Implement-Queue-using-Stacks/solution.cpp: -------------------------------------------------------------------------------- 1 | class Queue 2 | { 3 | public: 4 | stack stack1; 5 | stack stack2; 6 | 7 | // Push element x to the back of queue. 8 | void push(int x) 9 | { 10 | while(!stack2.empty()) 11 | { 12 | stack1.push(stack2.top()); 13 | stack2.pop(); 14 | } 15 | stack1.push(x); 16 | } 17 | 18 | // Removes the element from in front of queue. 19 | void pop(void) 20 | { 21 | while(!stack1.empty()) 22 | { 23 | stack2.push(stack1.top()); 24 | stack1.pop(); 25 | } 26 | stack2.pop(); 27 | } 28 | 29 | // Get the front element. 30 | int peek(void) 31 | { 32 | while(!stack1.empty()) 33 | { 34 | stack2.push(stack1.top()); 35 | stack1.pop(); 36 | } 37 | return stack2.top(); 38 | } 39 | 40 | // Return whether the queue is empty. 41 | bool empty(void) 42 | { 43 | return stack1.empty() && stack2.empty(); 44 | } 45 | }; -------------------------------------------------------------------------------- /Algorithms/235.Lowest-Common-Ancestor-of-a-Binary-Search-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 14 | { 15 | if(root == NULL || p == NULL || q == NULL) 16 | return NULL; 17 | if(p->val > q->val) 18 | swap(p,q); 19 | if( root->val >= p->val && root->val <= q->val ) 20 | return root; 21 | else if( root->val < p->val && root->val < q->val ) 22 | return lowestCommonAncestor(root->right,p,q); 23 | else if( root->val > p->val && root->val > q->val ) 24 | return lowestCommonAncestor(root->left,p,q); 25 | return NULL; 26 | } 27 | }; -------------------------------------------------------------------------------- /Algorithms/237.Delete-Node-in-a-Linked-List/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | void deleteNode(ListNode* node) 13 | { 14 | ListNode* temp = node->next; 15 | node->val = node->next->val; 16 | node->next = node->next->next; 17 | delete temp; 18 | } 19 | }; -------------------------------------------------------------------------------- /Algorithms/238.Product-of-Array-Except-Self/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector productExceptSelf(vector& nums) 5 | { 6 | vector result(nums.size(),0); 7 | result[nums.size()-1] = 1; 8 | for(int i=nums.size()-2;i>=0;i--) 9 | result[i] = result[i+1]*nums[i+1]; 10 | int left=1; 11 | for(int i=1;inext)) 16 | { 17 | a->next = b->next; 18 | b->next = a; 19 | *pp = b; 20 | pp = &(a->next); 21 | } 22 | return head; 23 | } 24 | }; -------------------------------------------------------------------------------- /Algorithms/242.Valid-Anagram/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | vector count(256,0); 5 | for(int i=0;inext = head; 19 | ListNode *current = preheader, *forward, *precede = preheader; 20 | while(current = current->next) 21 | sum++; 22 | while(sum>=k) 23 | { 24 | current = precede->next; 25 | forward = current->next; 26 | for(int i=1;inext=forward->next; 29 | forward->next=precede->next; 30 | precede->next=forward; 31 | forward=current->next; 32 | } 33 | precede = current; 34 | sum-=k; 35 | } 36 | return preheader->next; 37 | } 38 | }; -------------------------------------------------------------------------------- /Algorithms/257.Binary-Tree-Paths/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | int dfs(TreeNode *root, vector &result, string temp) 14 | { 15 | temp += to_string(root->val); 16 | if(!root->right && !root->left) 17 | { 18 | result.push_back(temp); 19 | return 0; 20 | } 21 | if(root->left) 22 | dfs(root->left,result,temp+"->"); 23 | if(root->right) 24 | dfs(root->right,result,temp+"->"); 25 | return 0; 26 | } 27 | 28 | vector binaryTreePaths(TreeNode* root) 29 | { 30 | vector result; 31 | string temp; 32 | if(root) 33 | dfs(root,result,temp); 34 | return result; 35 | } 36 | }; -------------------------------------------------------------------------------- /Algorithms/258.Add-Digits/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | int ans = num % 9; 5 | if(ans == 0 && num > 0) 6 | ans = 9; 7 | return ans; 8 | } 9 | }; -------------------------------------------------------------------------------- /Algorithms/26.Remove-Duplicates-from-Sorted-Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int removeDuplicates(vector& nums) 5 | { 6 | int length = nums.size(); 7 | for(int i=0,j=1;j singleNumber(vector& nums) 5 | { 6 | int XOR = 0; 7 | for(int i=0;i result(2,0); 15 | for(int i=0;i res(1, 1); 5 | int i2 = 0, i3 = 0, i5 = 0; 6 | while (res.size() < n) { 7 | int m2 = res[i2] * 2; 8 | int m3 = res[i3] * 3; 9 | int m5 = res[i5] * 5; 10 | int mn = min(m2, min(m3, m5)); 11 | if (mn == m2) ++i2; 12 | if (mn == m3) ++i3; 13 | if (mn == m5) ++i5; 14 | res.push_back(mn); 15 | } 16 | return res.back(); 17 | } 18 | }; -------------------------------------------------------------------------------- /Algorithms/27.Remove-Element/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int removeElement(vector& nums, int val) 5 | { 6 | int length = 0; 7 | for(int i=0,j=0;jj; 3 | } 4 | 5 | class Solution { 6 | public: 7 | int hIndex(vector& citations) { 8 | sort(citations.begin(),citations.end(),cmp); 9 | int i; 10 | for(i=0;i& nums) 4 | { 5 | int count = 0; 6 | for(int i=0;i& nums) 5 | { 6 | int min = 0, max = nums.size() - 1; 7 | while(min <= max) 8 | { 9 | // 找到中间那个数 10 | int mid = min + (max - min) / 2; 11 | int cnt = 0; 12 | // 计算总数组中有多少个数小于等于中间数 13 | for(int i = 0; i < nums.size(); i++) 14 | { 15 | if(nums[i] <= mid) 16 | { 17 | cnt++; 18 | } 19 | } 20 | // 如果小于等于中间数的数量大于中间数,说明前半部分必有重复 21 | if(cnt > mid) 22 | { 23 | max = mid - 1; 24 | // 否则后半部分必有重复 25 | } 26 | else 27 | { 28 | min = mid + 1; 29 | } 30 | } 31 | return min; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/29.Divide-Two-Integers/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int divide(int dividend, int divisor) 5 | { 6 | if(!divisor || (dividend == INT_MIN && divisor == -1)) 7 | return INT_MAX; 8 | int sign = ((dividend > 0) ^ (divisor > 0))? -1:1; 9 | long long dvd = labs(dividend); 10 | long long dvs = labs(divisor); 11 | long long result = 0; 12 | long long tempDivisor; 13 | int base; 14 | while(dvd >= dvs) 15 | { 16 | tempDivisor = dvs; 17 | base = 1; 18 | while( (dvd>>1) >= tempDivisor ) 19 | { 20 | tempDivisor <<= 1; 21 | base <<= 1; 22 | } 23 | dvd -= tempDivisor; 24 | result += base; 25 | } 26 | return sign>0? result:-result; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/292.Nim-Game/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool canWinNim(int n) 5 | { 6 | return n % 4 != 0; 7 | } 8 | }; -------------------------------------------------------------------------------- /Algorithms/299.Bulls-and-Cows/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string getHint(string secret, string guess) 5 | { 6 | string result; 7 | int c = 0; 8 | for(int i=0;i tableS(10),tableG(10); 16 | for(int i=0;i tableG[i]) 25 | t += tableG[i]; 26 | else 27 | t += tableS[i]; 28 | } 29 | result += to_string(t-c) + "B"; 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /Algorithms/3.Longest-Substring-Without-Repeating-Characters/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int lengthOfLongestSubstring(string s) 5 | { 6 | int left=0, right=0; 7 | int maxLength=0, length=0; 8 | vector flag(255,false); 9 | for(;right maxLength) 25 | maxLength = length; 26 | } 27 | } 28 | return maxLength; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/300.Longest-Increasing-Subsequence/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | int maxlen = 0; 5 | 6 | vector dp(nums.size()); 7 | for(int i=0;i nums[j]) 11 | max_dp = max(dp[j], max_dp); 12 | } 13 | dp[i] = max_dp + 1; 14 | maxlen = max(dp[i], maxlen); 15 | } 16 | return maxlen; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Algorithms/303.Range-Sum-Query---Immutable/solution.cpp: -------------------------------------------------------------------------------- 1 | class NumArray 2 | { 3 | public: 4 | vector sums; 5 | NumArray(vector &nums) 6 | { 7 | int sum = 0; 8 | for(int i=0;i0) 18 | return sums[j] - sums[i-1]; 19 | return sums[j]; 20 | } 21 | }; 22 | 23 | 24 | // Your NumArray object will be instantiated and called as such: 25 | // NumArray numArray(nums); 26 | // numArray.sumRange(0, 1); 27 | // numArray.sumRange(1, 2); -------------------------------------------------------------------------------- /Algorithms/304.Range-Sum-Query-2D---Immutable/solution.cpp: -------------------------------------------------------------------------------- 1 | class NumMatrix { 2 | public: 3 | vector> dp; 4 | int row; 5 | int col; 6 | NumMatrix(vector> matrix) { 7 | row = matrix.size(); 8 | col = row>0?matrix[0].size():0; 9 | dp = vector>(row+1, vector(col+1,0)); 10 | 11 | // 12 | for(int i=1;i& prices){ 4 | if (prices.size() <= 1) return 0; 5 | vector s0(prices.size(), 0); 6 | vector s1(prices.size(), 0); 7 | vector s2(prices.size(), 0); 8 | s1[0] = -prices[0]; 9 | s0[0] = 0; 10 | s2[0] = INT_MIN; 11 | for (int i = 1; i < prices.size(); i++) { 12 | s0[i] = max(s0[i - 1], s2[i - 1]); 13 | s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); 14 | s2[i] = s1[i - 1] + prices[i]; 15 | } 16 | return max(s0[prices.size() - 1], s2[prices.size() - 1]); 17 | } 18 | }; -------------------------------------------------------------------------------- /Algorithms/31.Next-Permutation/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void nextPermutation(vector &num) 5 | { 6 | if(num.size() < 2) return; 7 | int curMax = num[num.size() - 1]; 8 | for(int i = num.size() - 1; i >= 0;i--) 9 | { 10 | if(num[i] < curMax) 11 | { 12 | int tmp = num[i]; 13 | int j = 0; 14 | for(j = i + 1; j < num.size();j++) 15 | { 16 | if(tmp < num[j]) 17 | { 18 | num[i] = num[j]; 19 | num[j] = tmp; 20 | return; 21 | } 22 | } 23 | if(j == num.size()) 24 | { 25 | num[j - 1] = tmp; 26 | return; 27 | } 28 | } 29 | else 30 | { 31 | curMax = num[i]; 32 | for(int j = i + 1; j < num.size();j++) 33 | num[j - 1] = num[j]; 34 | num[num.size() - 1] = curMax; 35 | } 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /Algorithms/318.Maximum-Product-of-Word-Lengths/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxProduct(vector& words) 5 | { 6 | vector bitmap(words.size(),0); 7 | for(int i=0;imax?temp:max; 24 | } 25 | } 26 | } 27 | return max; 28 | } 29 | }; -------------------------------------------------------------------------------- /Algorithms/319.Bulb-Switcher/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int bulbSwitch(int n) 5 | { 6 | return sqrt(n); 7 | } 8 | }; -------------------------------------------------------------------------------- /Algorithms/32.Longest-Valid-Parentheses/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int longestValidParentheses(string s) 5 | { 6 | stackS; 7 | S.push(-1); 8 | int ans=0; 9 | for(string::size_type i=0;i1) 19 | { 20 | S.pop(); 21 | int tmp=S.top(); 22 | ans=max(ans,(int)i-tmp); 23 | } 24 | else 25 | { 26 | S.pop(); 27 | S.push(i); 28 | } 29 | } 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/324.Wiggle-Sort-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void wiggleSort(vector& nums) { 4 | int n = nums.size(); 5 | 6 | // Find a median. 7 | auto midptr = nums.begin() + n / 2; 8 | nth_element(nums.begin(), midptr, nums.end()); 9 | int mid = *midptr; 10 | 11 | // Index-rewiring. 12 | #define A(i) nums[(1+2*(i)) % (n|1)] 13 | 14 | // 3-way-partition-to-wiggly in O(n) time with O(1) space. 15 | int i = 0, j = 0, k = n - 1; 16 | while (j <= k) { 17 | if (A(j) > mid) 18 | swap(A(i++), A(j++)); 19 | else if (A(j) < mid) 20 | swap(A(j), A(k--)); 21 | else 22 | j++; 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/326.Power-of-Three/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isPowerOfThree(int n) 5 | { 6 | while (n && (n % 3 == 0)) n /= 3; 7 | return n == 1; 8 | } 9 | }; -------------------------------------------------------------------------------- /Algorithms/338.Counting-Bits/solution.cpp: -------------------------------------------------------------------------------- 1 | /* 每个数向右移1位(除以2)后, 2 | 二进制表示里的'1'的个数要么与原来相等(偶数,末位是'0'), 3 | 要么少了一个(奇数,末位是'1')。 4 | 5 | 所以在程序循环中,若计算array[i]的'1'的个数,因为之前已经计算过array[i/2], 6 | 此时只需判断array[i]的奇偶性,就可以计算array[i]的'1'的个了。 7 | */ 8 | 9 | class Solution { 10 | public: 11 | vector countBits(int num) 12 | { 13 | vector results = vector(num+1, 0); 14 | for(int i=1;i<=num;i++) 15 | { 16 | results[i] = results[ i >> 1 ] + (i & 1); 17 | } 18 | return results; 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/34.Find-First-and-Last-Position-of-Element-in-Sorted-Array/solution.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | vector searchRange(int A[], int n, int target) 6 | { 7 | begin = end = -1; 8 | find(A, 0, n - 1, target); 9 | vector ans; 10 | ans.push_back(begin); 11 | ans.push_back(end); 12 | return ans; 13 | } 14 | 15 | private: 16 | int begin; 17 | int end; 18 | 19 | void find(int A[], int l, int r, int target) 20 | { 21 | if (l > r) 22 | { 23 | return; 24 | } 25 | int mid = (l + r) >> 1; 26 | if (A[mid] == target) 27 | { 28 | if (mid < begin || begin == -1) 29 | { 30 | begin = mid; 31 | } 32 | if (mid > end) 33 | { 34 | end = mid; 35 | } 36 | find(A, l, mid - 1, target); 37 | find(A, mid + 1, r, target); 38 | } 39 | else if (A[mid] < target) 40 | { 41 | find(A, mid + 1, r, target); 42 | } 43 | else 44 | { 45 | find(A, l, mid - 1, target); 46 | } 47 | } 48 | }; -------------------------------------------------------------------------------- /Algorithms/342.Power-of-Four/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isPowerOfFour(int num) 5 | { 6 | return num>0 && !(num&(num-1)) && (num & 0x55555555); 7 | } 8 | }; -------------------------------------------------------------------------------- /Algorithms/343.Integer-Break/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int integerBreak(int n) { 4 | if(n == 2) 5 | return 1; 6 | else if(n == 3) 7 | return 2; 8 | else if(n%3 == 0) 9 | return pow(3, n/3); 10 | else if(n%3 == 1) 11 | return 2 * 2 * pow(3, (n - 4) / 3); 12 | else 13 | return 2 * pow(3, n/3); 14 | } 15 | }; -------------------------------------------------------------------------------- /Algorithms/344.Reverse-String/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string reverseString(string s) 5 | { 6 | string result(s); 7 | for(int i=0;i seting(base,base+10); 15 | int startpos=0,endpos=s.size()-1; 16 | while(startpos < endpos ) 17 | { 18 | while( startpos < endpos && seting.find(s[startpos]) == seting.end()) 19 | startpos++; 20 | while( startpos < endpos && seting.find(s[endpos]) == seting.end()) 21 | endpos--; 22 | if(startpos < endpos) 23 | swap(s,startpos++,endpos--); 24 | } 25 | return s; 26 | }; 27 | }; -------------------------------------------------------------------------------- /Algorithms/347.Top-K-Frequent-Elements/solution.cpp: -------------------------------------------------------------------------------- 1 | bool cmp(pair p1 , pair p2) 2 | { 3 | return p1.first > p2.first; 4 | } 5 | class Solution 6 | { 7 | public: 8 | vector topKFrequent(vector& nums, int k) 9 | { 10 | map count; 11 | for(auto i:nums) 12 | count[i]++; 13 | 14 | vector > table; 15 | for(auto i:count) 16 | table.push_back(pair(i.second, i.first)); 17 | sort(table.begin(), table.end(), cmp); 18 | 19 | vector result; 20 | for(int i=0;i intersection(vector& nums1, vector& nums2) 5 | { 6 | sort(nums1.begin(),nums1.end()); 7 | sort(nums2.begin(),nums2.end()); 8 | vector result; 9 | int i=0,j=0; 10 | while(i& nums, int target) 5 | { 6 | int mid,left = 0, right = nums.size(); 7 | while(left < right) 8 | { 9 | mid = left+(right-left)/2; 10 | if(nums[mid] > target) 11 | right = mid; 12 | else if (nums[mid] < target) 13 | left = mid + 1; 14 | else 15 | return mid; 16 | } 17 | return nums[mid]>target?mid:mid+1; 18 | } 19 | }; -------------------------------------------------------------------------------- /Algorithms/350.Intersection-of-Two-Arrays-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector intersect(vector& nums1, vector& nums2) 5 | { 6 | sort(nums1.begin(),nums1.end()); 7 | sort(nums2.begin(),nums2.end()); 8 | vector result; 9 | int i=0,j=0; 10 | while(i > &board) 5 | { 6 | vector > rows(9, vector(9,false)); 7 | vector > cols(9, vector(9,false)); 8 | vector > blocks(9, vector(9,false)); 9 | 10 | for(int i = 0; i < 9; i++) 11 | for(int j = 0; j < 9; j++) 12 | { 13 | if(board[i][j] == '.')continue; 14 | int num = board[i][j] - '1'; 15 | if(rows[i][num] || cols[j][num] || blocks[i - i%3 + j/3][num]) 16 | return false; 17 | rows[i][num] = cols[j][num] = blocks[i - i%3 + j/3][num] = true; 18 | } 19 | return true; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/367.Valid-Perfect-Square/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPerfectSquare(int num) { 4 | if(num < 1) return false; 5 | if(num == 1) return true; 6 | int left = 0, right = num/2; 7 | while(left <= right) 8 | { 9 | long mid = (left+right)/2; 10 | long val = mid*mid; 11 | if(val == num) return true; 12 | else if(val > num) right = mid-1; 13 | else left = mid+1; 14 | } 15 | return false; 16 | } 17 | }; -------------------------------------------------------------------------------- /Algorithms/371.Sum-of-Two-Integers/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getSum(int a, int b) { 4 | return a+b; 5 | } 6 | }; -------------------------------------------------------------------------------- /Algorithms/374.Guess-Number-Higher-or-Lower/solution.cpp: -------------------------------------------------------------------------------- 1 | // Forward declaration of guess API. 2 | // @param num, your guess 3 | // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 | int guess(int num); 5 | 6 | class Solution 7 | { 8 | public: 9 | int guessNumber(int n) 10 | { 11 | int low = 1, high = n; 12 | while(low <= high) 13 | { 14 | int mid = (high-low)/2+low, val = guess(mid); 15 | if(val == 0) return mid; 16 | else val==-1?high=mid-1:low=mid+1; 17 | } 18 | return -1; 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/378.Kth-Smallest-Element-in-a-Sorted-Matrix/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int kthSmallest(vector>& matrix, int k) 5 | { 6 | vector vec(matrix.size()*matrix[0].size()); 7 | for(int i=0;ihead = head; 17 | this->len = 1; 18 | ListNode* temp = head; 19 | while(temp->next) 20 | { 21 | len++; 22 | temp = temp->next; 23 | } 24 | } 25 | 26 | /** Returns a random node's value. */ 27 | int getRandom() 28 | { 29 | int step = rand()%len; 30 | ListNode* temp = this->head;; 31 | for(int i=0;inext; 33 | return temp->val; 34 | } 35 | int len; 36 | ListNode* head; 37 | }; 38 | 39 | /** 40 | * Your Solution object will be instantiated and called as such: 41 | * Solution obj = new Solution(head); 42 | * int param_1 = obj.getRandom(); 43 | */ -------------------------------------------------------------------------------- /Algorithms/383.Ransom-Note/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string ransomNote, string magazine) 4 | { 5 | int table[256]; 6 | for(int i=0;i<256;i++) 7 | table[i] = 0; 8 | for(int i=0;i nums; 5 | Solution(vector nums):nums(nums) 6 | { 7 | 8 | } 9 | 10 | /** Resets the array to its original configuration and return it. */ 11 | vector reset() 12 | { 13 | return this->nums; 14 | } 15 | 16 | /** Returns a random shuffling of the array. */ 17 | vector shuffle() 18 | { 19 | vector shuffle(nums); 20 | int pos; 21 | for(int i=0;i param_1 = obj.reset(); 34 | * vector param_2 = obj.shuffle(); 35 | */ -------------------------------------------------------------------------------- /Algorithms/387.First-Unique-Character-in-a-String/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int firstUniqChar(string s) 5 | { 6 | int table[26]; 7 | memset(table,0,sizeof(table)); 8 | 9 | for(int i=0;i > combinationSum(vector &candidates, int target) 5 | { 6 | vector vecTmp; 7 | 8 | m_vecRet.clear(); 9 | sort(candidates.begin(), candidates.end()); 10 | combination(candidates, 0, vecTmp, target); 11 | 12 | return m_vecRet; 13 | } 14 | 15 | private: 16 | void combination(const vector &candidates, size_t idx, vector &curr, int target) 17 | { 18 | if (target == 0) 19 | { 20 | m_vecRet.push_back(curr); 21 | } 22 | else 23 | { 24 | for (size_t i = idx; i < candidates.size(); ++i) 25 | { 26 | if (target >= candidates[i]) 27 | { 28 | curr.push_back(candidates[i]); 29 | combination(candidates, i, curr, target - candidates[i]); 30 | curr.pop_back(); 31 | } 32 | } 33 | } 34 | } 35 | 36 | private: 37 | vector > m_vecRet; 38 | }; -------------------------------------------------------------------------------- /Algorithms/392.Is-Subsequence/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isSubsequence(string s, string t) 5 | { 6 | int i=0,j=0; 7 | while(i& A) 5 | { 6 | int n = A.size(); 7 | if(n<=0) 8 | return 0; 9 | vector F(n,0); 10 | int sum = 0; 11 | for(int i=0;i max) 21 | max = F[i]; 22 | } 23 | return max; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/4.Median-of-Two-Sorted-Arrays/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) 4 | { 5 | vector res; 6 | int medianPos = 0; 7 | int p1,p2; 8 | for(p1=0,p2=0;p1 > combinationSum2(vector &num, int target) 5 | { 6 | vector vecTmp; 7 | 8 | m_vecRet.clear(); 9 | sort(num.begin(), num.end()); 10 | combination(num, 0, vecTmp, target); 11 | 12 | return m_vecRet; 13 | } 14 | 15 | private: 16 | void combination(const vector &num, size_t idx, vector &curr, int target) 17 | { 18 | if (target == 0) 19 | { 20 | m_vecRet.push_back(curr); 21 | } 22 | else 23 | { 24 | for (size_t i = idx; i < num.size(); ++i) 25 | { 26 | if (i != idx && num[i] == num[i - 1]) 27 | { 28 | continue; 29 | } 30 | 31 | if (target >= num[i]) 32 | { 33 | curr.push_back(num[i]); 34 | combination(num, i + 1, curr, target - num[i]); 35 | curr.pop_back(); 36 | } 37 | } 38 | } 39 | } 40 | 41 | private: 42 | vector > m_vecRet; 43 | }; -------------------------------------------------------------------------------- /Algorithms/400.Nth-Digit/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNthDigit(int n) { 4 | long digit = 1, ith = 1, base = 9; 5 | while(n > base*digit) 6 | { 7 | n -= base*(digit++); 8 | ith += base; 9 | base *= 10; 10 | } 11 | return to_string(ith+(n-1)/digit)[(n-1)%digit]-'0'; 12 | } 13 | }; -------------------------------------------------------------------------------- /Algorithms/404.Sum-of-Left-Leaves/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | int sum; 14 | 15 | int traversal(TreeNode* root, bool isLeft) 16 | { 17 | if(root) 18 | { 19 | if( !root->left && !root->right && isLeft) 20 | return root->val; 21 | return traversal(root->left, true) + traversal(root->right, false); 22 | } 23 | else 24 | return 0; 25 | } 26 | 27 | int sumOfLeftLeaves(TreeNode* root) 28 | { 29 | return traversal(root,false); 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/405.Convert-a-Number-to-Hexadecimal/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string toHex(int num) 5 | { 6 | char *str = new char[8]; 7 | sprintf(str, "%x", num); 8 | return string(str); 9 | } 10 | }; -------------------------------------------------------------------------------- /Algorithms/406.Queue-Reconstruction-by-Height/solution.cpp: -------------------------------------------------------------------------------- 1 | bool cmp(pair p1,pair p2) 2 | { 3 | if(p1.first > p2.first) 4 | return true; 5 | if(p1.first == p2.first && p1.second < p2.second) 6 | return true; 7 | return false; 8 | } 9 | 10 | class Solution 11 | { 12 | public: 13 | vector> reconstructQueue(vector>& people) 14 | { 15 | sort(people.begin(),people.end(),cmp); 16 | vector> result; 17 | for(int i=0;i= result.size()) 20 | result.push_back(people[i]); 21 | else 22 | result.insert(result.begin()+people[i].second, people[i]); 23 | } 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/409.Longest-Palindrome/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int longestPalindrome(string s) 5 | { 6 | bool table[256]; 7 | memset(table,0,sizeof(table)); 8 | 9 | int result = 0; 10 | 11 | for(int i=0;i result) 22 | result++; 23 | return result; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/41.First-Missing-Positive/solution.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | void swap(int &a,int &b) 6 | { 7 | int temp = a; 8 | a = b; 9 | b = temp; 10 | } 11 | 12 | int firstMissingPositive(int A[], int n) 13 | { 14 | for(int i=0;i=n||A[i]<=0||A[i]==A[A[i]-1]) 19 | break; 20 | swap(A[i],A[A[i]-1]); 21 | } 22 | } 23 | for(int i=0;i fizzBuzz(int n) 5 | { 6 | vector result; 7 | 8 | for(int i=1;i<=n;i++) 9 | { 10 | if( i % 15 == 0 ) 11 | { 12 | result.push_back("FizzBuzz"); 13 | } 14 | else if( i % 3 == 0) 15 | { 16 | result.push_back("Fizz"); 17 | } 18 | else if( i % 5 == 0) 19 | { 20 | result.push_back("Buzz"); 21 | } 22 | else 23 | { 24 | result.push_back(to_string(i)); 25 | } 26 | } 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /Algorithms/413.Arithmetic-Slices/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numberOfArithmeticSlices(vector& A) 5 | { 6 | if(A.size() < 3) 7 | return 0; 8 | vector diff; 9 | for(int i=0;i& nums) 5 | { 6 | set num; 7 | for(int i=0;i::reverse_iterator it=num.rbegin(); 12 | if(num.size()<3) 13 | return *it; 14 | 15 | it++; 16 | it++; 17 | return *it; 18 | } 19 | }; -------------------------------------------------------------------------------- /Algorithms/419.Battleships-in-a-Board/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int countBattleships(vector>& board) 5 | { 6 | int count = 0; 7 | for(int i=0;i leftMax) 12 | leftMax = A[i]; 13 | } 14 | 15 | int rightMax = 0; 16 | int right[n]; 17 | for(int i=n-1;i>=0;i--) 18 | { 19 | right[i] = rightMax; 20 | if(A[i] > rightMax) 21 | rightMax = A[i]; 22 | } 23 | 24 | int result = 0; 25 | int temp; 26 | for(int i=0;i A[i]) 30 | result += temp-A[i]; 31 | } 32 | return result; 33 | } 34 | }; -------------------------------------------------------------------------------- /Algorithms/423.Reconstruct-Original-Digits-from-English/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string originalDigits(string s) 5 | { 6 | vector countLetter(26,0); 7 | for(int i=0;i countNum(10,0); 10 | countNum[0] = countLetter['z'-'a']; 11 | countNum[2] = countLetter['w'-'a']; 12 | countNum[4] = countLetter['u'-'a']; 13 | countNum[6] = countLetter['x'-'a']; 14 | countNum[8] = countLetter['g'-'a']; 15 | countNum[1] = countLetter['o'-'a']-countNum[0]-countNum[2]-countNum[4]; 16 | countNum[3] = countLetter['h'-'a']-countNum[8]; 17 | countNum[5] = countLetter['f'-'a']-countNum[4]; 18 | countNum[7] = countLetter['v'-'a']-countNum[5]; 19 | countNum[9] = (countLetter['n'-'a']-countNum[1]-countNum[7])/2; 20 | 21 | string result; 22 | for(int i=0;i 0 && s[i] == s[i-1]) 11 | continue; 12 | char cur_letter = s[i]; 13 | int count = k; 14 | int j; 15 | for (j = i+1; j < len; ++j) 16 | { 17 | if (s[j] != cur_letter) 18 | count--; 19 | if (count < 0) 20 | break; 21 | } 22 | if(j==len&&count>0) 23 | tl=j-i+min(count,i); 24 | else 25 | tl=j-i; 26 | maxlen = max(maxlen, tl); 27 | } 28 | return maxlen; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/43.Multiply-Strings/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string multiply(string num1, string num2) 5 | { 6 | int len1 = num1.size(), 7 | len2 = num2.size(), 8 | len = len1 + len2; 9 | string str(len, '0'); 10 | for (int i = len1 - 1; i >= 0; i--) 11 | { 12 | int a = num1[i] - '0'; 13 | for (int j = len2 - 1, k = len2 + i; j >= 0; j--, k--) 14 | { 15 | int b = num2[j] - '0'; 16 | int c = str[k] - '0'; 17 | int t = b * a + c; 18 | str[k] = t % 10 + '0'; 19 | int d = (str[k-1] - '0') + t / 10; 20 | if (d >= 10) 21 | str[k-2] = str[k-2] - '0' + d / 10 + '0'; 22 | str[k-1] = d % 10 + '0'; 23 | } 24 | } 25 | int x = 0; 26 | while (str[x] == '0') 27 | x++; 28 | if (str.substr(x, len - x) == "") 29 | return "0"; 30 | return str.substr(x, len - x); 31 | } 32 | }; -------------------------------------------------------------------------------- /Algorithms/434.Number-of-Segments-in-a-String/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int countSegments(string s) 5 | { 6 | bool flag = false; 7 | int count = 0; 8 | for(int i=0;i& intervals) { 13 | 14 | } 15 | }; -------------------------------------------------------------------------------- /Algorithms/436.Find-Right-Interval/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | 11 | bool cmp(pair a,pair b) 12 | { 13 | return a.first.start <= b.first.start || (a.first.start==b.first.start&&a.first.end<=b.first.end); 14 | } 15 | 16 | class Solution 17 | { 18 | public: 19 | vector findRightInterval(vector& intervals) 20 | { 21 | int n=intervals.size(); 22 | vector ans(n,-1); 23 | vector> h; 24 | for(int i=0;i(intervals[i],i)); 26 | sort(h.begin(),h.end(),cmp); 27 | int i,j; 28 | for(i=0;i=h[i].first.end) 33 | { 34 | ans[h[i].second]=h[j].second; 35 | break; 36 | } 37 | } 38 | } 39 | return ans; 40 | } 41 | }; -------------------------------------------------------------------------------- /Algorithms/437.Path-Sum-III/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | int dfs(TreeNode* root, int &sum, int tempSum) 14 | { 15 | if(!root) 16 | return 0; 17 | tempSum += root->val; 18 | int flag = 0; 19 | if(tempSum == sum) 20 | flag = 1; 21 | return flag + dfs(root->left,sum,tempSum) + dfs(root->right,sum,tempSum); 22 | } 23 | 24 | int pathSum(TreeNode* root, int sum) 25 | { 26 | if(!root) 27 | return 0; 28 | return dfs(root, sum, 0) + pathSum(root->left, sum) + pathSum(root->right, sum); 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/438.Find-All-Anagrams-in-a-String/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector findAnagrams(string s, string p) 5 | { 6 | vector hash1(256), hash2(256); 7 | for(auto ch: p) 8 | hash1[ch]++; 9 | int lenp = p.size(), lens = s.size(); 10 | vector ans; 11 | for(int i = 0; i < lens; i++) 12 | { 13 | hash2[s[i]]++; 14 | if(i >= lenp) 15 | hash2[s[i-lenp]]--; 16 | if(hash1 == hash2) 17 | ans.push_back(i-lenp+1); 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/441.Arranging-Coins/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int arrangeCoins(int n) 5 | { 6 | for(long long i=sqrt(2*(long long)n);i>0;i--) 7 | { 8 | if((1+i)*i/2 <= n) 9 | return i; 10 | } 11 | return 0; 12 | } 13 | }; -------------------------------------------------------------------------------- /Algorithms/448.Find-All-Numbers-Disappeared-in-an-Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector findDisappearedNumbers(vector& nums) 5 | { 6 | vector result(nums.size(),-1); 7 | for(int i=0;i p1, pair p2) 2 | { 3 | if(p1.secondp2.second) 6 | return false; 7 | return p1.first>& points) 14 | { 15 | if(points.size()==0) 16 | return 0; 17 | sort(points.begin(), points.end(), cmp); 18 | int shots=1; 19 | int x = points[0].second; 20 | for(auto i:points) 21 | { 22 | if(x& nums) 5 | { 6 | int min = nums[0]; 7 | for(int i=0;i& g, vector& s) 5 | { 6 | int n = g.size(),m = s.size(); 7 | sort(g.begin(),g.end()); 8 | sort(s.begin(),s.end()); 9 | 10 | int i=0,j=0; 11 | while(i>=1; 12 | y>>=1; 13 | } 14 | return distance; 15 | } 16 | }; -------------------------------------------------------------------------------- /Algorithms/462.Minimum-Moves-to-Equal-Array-Elements-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minMoves2(vector& nums) 5 | { 6 | sort(nums.begin(),nums.end()); 7 | int m = nums[nums.size()/2]; 8 | int moves = 0; 9 | for(int i=0;i>& grid) 5 | { 6 | int result = 0; 7 | 8 | for(int i=0;i > permuteUnique(vector &num) 4 | { 5 | int len = num.size(); 6 | vector > res; 7 | sort(num.begin(), num.end()); 8 | gen(res, num, 0, len); 9 | return res; 10 | } 11 | 12 | bool isSwap(vector& num, int s, int e) 13 | { 14 | int i = s; 15 | while (num[i] != num[e] && i < e) i++; 16 | if (i == e) return true; 17 | else return false; 18 | } 19 | 20 | void gen(vector > &res, vector& num, int cur, int len) 21 | { 22 | if (cur == len) { 23 | res.push_back(num); 24 | return; 25 | } 26 | 27 | for (int i = cur; i < len; i++) { 28 | if (!isSwap(num, cur, i)) continue; 29 | swap(num[cur], num[i]); 30 | gen(res, num, cur+1, len); 31 | swap(num[cur], num[i]); 32 | } 33 | } 34 | }; -------------------------------------------------------------------------------- /Algorithms/471.Simplify-Path/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string simplifyPath(string path) 5 | { 6 | stack s; 7 | string str; 8 | for(int i = 0; i < path.size(); i++) 9 | { 10 | if (path[i] == '/') 11 | { 12 | if (str == "..") 13 | { 14 | if (!s.empty()) 15 | s.pop(); 16 | } 17 | else if (str != "." && str != "") 18 | { 19 | s.push(str); 20 | } 21 | 22 | str = ""; 23 | } 24 | else 25 | { 26 | str += path[i]; 27 | } 28 | } 29 | 30 | if (str == "..") 31 | { 32 | if (!s.empty()) 33 | s.pop(); 34 | } 35 | else if (str != "." && str != "") 36 | s.push(str); 37 | 38 | if (s.empty()) 39 | return "/"; 40 | 41 | string ret; 42 | while(!s.empty()) 43 | { 44 | ret = "/" + s.top() + ret; 45 | s.pop(); 46 | } 47 | 48 | return ret; 49 | } 50 | }; -------------------------------------------------------------------------------- /Algorithms/476.Number-Complement/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findComplement(int num) 5 | { 6 | int result = ~num; 7 | int count = 0; 8 | while(num>0) 9 | { 10 | num>>=1; 11 | count++; 12 | } 13 | return result ^ (INT_MAX< > &matrix) 5 | { 6 | int n=matrix.size(); 7 | int temp = 0; 8 | for(int i=0;i& nums) 5 | { 6 | int max = 0,temp=0;; 7 | for(int i=0;imax) 14 | max = temp; 15 | temp = 0; 16 | } 17 | } 18 | if(temp>max) 19 | max = temp; 20 | return max; 21 | } 22 | }; -------------------------------------------------------------------------------- /Algorithms/49.Group-Anagrams/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector anagrams(vector &strs) 5 | { 6 | string s; 7 | map anagram; 8 | vector result; 9 | for (int i = 0; i < strs.size(); ++i) 10 | { 11 | s = strs[i]; 12 | sort(s.begin(), s.end()); 13 | if (anagram.find(s) == anagram.end()) 14 | { 15 | anagram[s] = i; 16 | } 17 | else 18 | { 19 | if (anagram[s] >= 0) 20 | { 21 | result.push_back(strs[anagram[s]]); 22 | anagram[s] = -1; 23 | } 24 | result.push_back(strs[i]); 25 | } 26 | } 27 | return result; 28 | } 29 | }; -------------------------------------------------------------------------------- /Algorithms/496.Next-Greater-Element-I/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElement(vector& findNums, vector& nums) { 4 | map max; 5 | for(int i=0;i nums[i]){ 8 | max[nums[i]] = nums[j]; 9 | break; 10 | } 11 | } 12 | } 13 | 14 | vector result(findNums.size(),0); 15 | for(int i=0;i findDiagonalOrder(vector>& matrix) { 4 | int row = matrix.size(); 5 | int col = row>0?matrix[0].size():0; 6 | vector result(row*col,0); 7 | int cur = 0; 8 | bool right = false; 9 | int i,j,minn,start; 10 | for(int sum = 0;sum=0;j++) 11 | { 12 | if(s[i-j] == s[i+j]) 13 | length += 2; 14 | else 15 | break; 16 | } 17 | if(length > maxLength) 18 | { 19 | maxLength = length; 20 | position = i-length/2; 21 | } 22 | } 23 | 24 | for(int i=0;i+1=0;j++) 28 | { 29 | if(s[i-j] == s[i+1+j]) 30 | length += 2; 31 | else 32 | break; 33 | } 34 | if(length > maxLength) 35 | { 36 | maxLength = length; 37 | position = i-length/2+1; 38 | } 39 | } 40 | return s.substr(position,maxLength); 41 | } 42 | }; -------------------------------------------------------------------------------- /Algorithms/50.Pow(x,-n)/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | double pow(double x, int n) 5 | { 6 | long long index = n; 7 | double result = 0; 8 | int flag = 1; 9 | if (x<0 && n%2!=0) 10 | x = -x, flag = -1; 11 | if (index < 0) 12 | result = powI(x, -index); 13 | else 14 | result = powI(x, index); 15 | 16 | if (index < 0) return 1/result*flag; 17 | else return result*flag; 18 | } 19 | 20 | double powI(double x, long long n) // x>0, n>=0 21 | { 22 | if (n == 0) 23 | return 1; 24 | else if (n == 1) 25 | return x; 26 | else if (n == 2) 27 | return x*x; 28 | else 29 | { 30 | if (n%2==0) 31 | { 32 | double mid = powI(x, n/2); 33 | return mid*mid; 34 | } 35 | else { 36 | double mid = powI(x, (n-1)/2); 37 | return mid*mid*x; 38 | } 39 | } 40 | } 41 | }; -------------------------------------------------------------------------------- /Algorithms/503.Next-Greater-Element-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElements(vector& nums) { 4 | vector max; 5 | for(int i=0;i nums[i]){ 9 | max.push_back(nums[j]); 10 | find = true; 11 | break; 12 | } 13 | } 14 | if(!find) 15 | max.push_back( -1); 16 | } 17 | return max; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Algorithms/506.Relative-Ranks/solution.cpp: -------------------------------------------------------------------------------- 1 | bool cmp(pair i, pair j){ 2 | return j.first < i.first; 3 | } 4 | 5 | class Solution { 6 | public: 7 | vector findRelativeRanks(vector& nums) { 8 | vector > mapp; 9 | for(int i=0;i(nums[i],i)); 11 | } 12 | sort(mapp.begin(), mapp.end(), cmp); 13 | 14 | vector str(nums.size()); 15 | for(int i=0;i 0) 19 | str[mapp[0].second] = "Gold Medal"; 20 | if(mapp.size() > 1) 21 | str[mapp[1].second] = "Silver Medal"; 22 | if(mapp.size() > 2) 23 | str[mapp[2].second] = "Bronze Medal"; 24 | return str; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Algorithms/523.Continuous-Subarray-Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkSubarraySum(vector& nums, int k) { 4 | bool flag = false; 5 | if(k==0) 6 | flag = true; 7 | vector dp(nums.size(),0); 8 | for(int i=0;i MaxSum) 15 | MaxSum = ThisSum; 16 | if(ThisSum < 0) 17 | ThisSum = 0; 18 | } 19 | return MaxSum; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/55.Jump-Game/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution2 { 2 | public: 3 | bool canJump(vector& nums) { 4 | vectortable(nums.size(), false); 5 | table[0] = true; 6 | 7 | for(auto i = 1; i < nums.size(); ++i) 8 | { 9 | for(auto j = 0; j < i; ++j) 10 | { 11 | if (table[j] && nums[j] >= i - j) 12 | { 13 | table[i] = true; 14 | break; 15 | } 16 | } 17 | } 18 | 19 | return table[nums.size() - 1]; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Algorithms/56.Merge-Intervals/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | 11 | bool cmp(struct Interval in1,struct Interval in2) 12 | { 13 | return in1.start < in2.start; 14 | } 15 | 16 | class Solution 17 | { 18 | public: 19 | vector merge(vector &intervals) 20 | { 21 | sort(intervals.begin(),intervals.end(),cmp); 22 | vector result; 23 | if(intervals.size()==0) 24 | return result; 25 | int pend=intervals[0].end; 26 | Interval s(intervals[0].start,pend); 27 | for(int i=1;ipend) 30 | { 31 | s.end=pend; 32 | result.push_back(s); 33 | s.start=intervals[i].start; 34 | pend=intervals[i].end; 35 | } 36 | else pend=max(intervals[i].end,pend); 37 | } 38 | s.end=pend; 39 | result.push_back(s); 40 | return result; 41 | } 42 | }; -------------------------------------------------------------------------------- /Algorithms/58.Length-of-Last-Word/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int lengthOfLastWord(const char *s) 5 | { 6 | int result = 0; 7 | bool flag = false; 8 | while(*s != '\0') 9 | { 10 | if(*s == ' ') 11 | flag = true; 12 | else if(flag == true) 13 | { 14 | flag = false; 15 | result = 1; 16 | } 17 | else 18 | result++; 19 | s++; 20 | } 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /Algorithms/59.Spiral-Matrix-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > matrix; 5 | 6 | void solve(int startPos, int startNum, int n) 7 | { 8 | if(n <= 0) 9 | return ; 10 | else 11 | { 12 | for(int i=startPos;i startPos-1;i--) 23 | { 24 | matrix[startPos+n-1][i] = startNum; 25 | startNum++; 26 | } 27 | for(int i=startPos+n -2;i>startPos;i--) 28 | { 29 | matrix[i][startPos] = startNum; 30 | startNum++; 31 | } 32 | solve(startPos+1,startNum,n-2); 33 | } 34 | } 35 | 36 | vector > generateMatrix(int n) 37 | { 38 | matrix.resize(n,vector(n)); 39 | solve(0,1,n); 40 | return matrix; 41 | } 42 | }; -------------------------------------------------------------------------------- /Algorithms/6.ZigZag-Conversion/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string convert(string s, int nRows) 5 | { 6 | int strLength = s.length(); 7 | int flag = 0; 8 | string result(s); 9 | 10 | if(nRows == 1) 11 | return result; 12 | 13 | for(int i = 0;i < strLength ; i += 2*nRows-2) 14 | { 15 | result[flag] = s[i]; 16 | flag++; 17 | } 18 | 19 | for (int i = 1; i < nRows -1 ; i ++ ) 20 | { 21 | int flagM = flag; 22 | int flagN = flag+1; 23 | for(int m = i; m < strLength; m += 2*nRows-2) 24 | { 25 | result[flagM] = s[m]; 26 | flagM+=2; 27 | flag++; 28 | } 29 | for(int n = i + 2*(nRows - i - 1);n < strLength;n += 2*nRows-2) 30 | { 31 | result[flagN] = s[n]; 32 | flagN+=2; 33 | flag++; 34 | } 35 | } 36 | 37 | for(int i = nRows - 1;i < strLength ; i += 2*nRows-2) 38 | { 39 | result[flag] = s[i]; 40 | flag++; 41 | } 42 | return result; 43 | } 44 | }; -------------------------------------------------------------------------------- /Algorithms/60.Permutation-Sequence/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string getPermutation(int n, int k) 5 | { 6 | vector nums(n); 7 | int pCount = 1; 8 | for(int i = 0 ; i < n; ++i) 9 | { 10 | nums[i] = i + 1; 11 | pCount *= (i + 1); 12 | } 13 | 14 | k--; 15 | string res = ""; 16 | for(int i = 0 ; i < n; i++) 17 | { 18 | pCount = pCount/(n-i); 19 | int selected = k / pCount; 20 | res += ('0' + nums[selected]); 21 | 22 | for(int j = selected; j < n-i-1; j++) 23 | nums[j] = nums[j+1]; 24 | k = k % pCount; 25 | } 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/61.Rotate-List/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | ListNode *rotateRight(ListNode *head, int k) 13 | { 14 | if(k == 0 || head == NULL) 15 | return head; 16 | 17 | int length = 0; 18 | for(ListNode *temp = head;temp != NULL;temp = temp->next) 19 | length++; 20 | 21 | ListNode* left = head, *right = head; 22 | k %= length; 23 | while(k--) 24 | right = right->next; 25 | 26 | 27 | while(right->next != NULL) 28 | { 29 | right = right->next; 30 | left = left->next; 31 | } 32 | 33 | right->next = head; 34 | ListNode *result = left->next; 35 | left->next = NULL; 36 | 37 | return result; 38 | } 39 | }; -------------------------------------------------------------------------------- /Algorithms/62.Unique-Paths/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int uniquePaths(int m, int n) 5 | { 6 | vector > f(m, vector(n)); 7 | 8 | for(int i = 0; i < n; i++) 9 | f[0][i] = 1; 10 | 11 | for(int i = 0; i < m; i++) 12 | f[i][0] = 1; 13 | 14 | for(int i = 1; i < m; i++) 15 | for(int j = 1; j < n; j++) 16 | f[i][j] = f[i-1][j] + f[i][j-1]; 17 | 18 | return f[m-1][n-1]; 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/63.Unique-Paths-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int uniquePathsWithObstacles(vector > &obstacleGrid) 5 | { 6 | int m = obstacleGrid.size(); 7 | int n = obstacleGrid[0].size(); 8 | vector > f(m, vector(n)); 9 | 10 | if(obstacleGrid[0][0] == 1) 11 | return 0; 12 | 13 | f[0][0] = 1; 14 | for(int i = 1; i < n; i++) 15 | { 16 | if(obstacleGrid[0][i] == 1) 17 | f[0][i] = 0; 18 | else 19 | f[0][i] = f[0][i-1]; 20 | } 21 | 22 | for(int i = 1; i < m; i++) 23 | { 24 | if(obstacleGrid[i][0] == 1) 25 | f[i][0] = 0; 26 | else 27 | f[i][0] = f[i-1][0]; 28 | } 29 | 30 | for(int i = 1; i < m; i++) 31 | for(int j = 1; j < n; j++) 32 | { 33 | if(obstacleGrid[i][j] == 1) 34 | f[i][j] = 0; 35 | else 36 | f[i][j] = f[i-1][j] + f[i][j-1]; 37 | } 38 | 39 | return f[m-1][n-1]; 40 | } 41 | }; -------------------------------------------------------------------------------- /Algorithms/64.Minimum-Path-Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minPathSum(vector > &grid) 5 | { 6 | int m = grid.size(); 7 | int n = grid[0].size(); 8 | vector > DP(m, vector(n)); 9 | 10 | DP[0][0] = grid[0][0]; 11 | for(int i = 1; i < n; i++) 12 | DP[0][i] = DP[0][i-1] + grid[0][i]; 13 | 14 | for(int i = 1; i < m; i++) 15 | DP[i][0] = DP[i-1][0] + grid[i][0]; 16 | 17 | for(int i = 1; i < m; i++) 18 | for(int j = 1; j < n; j++) 19 | DP[i-1][j] < DP[i][j-1] ? DP[i][j] = DP[i-1][j] + grid[i][j] : DP[i][j] = DP[i][j-1] + grid[i][j]; 20 | 21 | return DP[m-1][n-1]; 22 | } 23 | }; -------------------------------------------------------------------------------- /Algorithms/645.Set-Mismatch/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findErrorNums(vector& nums) { 4 | vector ans; 5 | for (int i = 0; i < nums.size(); i++) { 6 | int index = abs(nums[i]) - 1; 7 | if (nums[index] > 0) { 8 | nums[index] *= -1; 9 | } 10 | else { 11 | ans.push_back(index + 1); 12 | } 13 | } 14 | for (int i = 0; i < nums.size(); i++) { 15 | if (nums[i] > 0) { 16 | ans.push_back(i + 1); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/66.Plus-One/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector plusOne(vector &digits) 5 | { 6 | vector answer; 7 | 8 | int c = 1; 9 | for (int i = digits.size() - 1; i >= 0; i--) 10 | { 11 | c += digits[i]; 12 | answer.insert(answer.begin(), c % 10); 13 | c = c / 10; 14 | } 15 | if (c > 0) 16 | { 17 | answer.insert(answer.begin(), c); 18 | } 19 | return answer; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/67.Add-Binary/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string addBinary(string a, string b) 5 | { 6 | string c; 7 | int flag=0; 8 | int lena = a.size(); 9 | int lenb = b.size(); 10 | int len = abs(lena-lenb); 11 | string append(len,'0'); 12 | if(lena>lenb) 13 | { 14 | b = append + b; 15 | c.resize(lena,'0'); 16 | } 17 | else 18 | { 19 | a = append + a; 20 | c.resize(lenb,'0'); 21 | } 22 | for(int j=c.size()-1;j>=0;j--) 23 | { 24 | int current = (a[j]-'0') ^(b[j]-'0') ^flag; 25 | if((a[j]-'0') +(b[j]-'0') +flag >1) 26 | flag = 1; 27 | else 28 | flag = 0; 29 | c[j] = current+'0'; 30 | } 31 | if(flag == 1) 32 | c = '1'+ c; 33 | return c; 34 | } 35 | }; -------------------------------------------------------------------------------- /Algorithms/674.Longest-Continuous-Increasing-Subsequence/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLengthOfLCIS(vector& nums) { 4 | if(nums.size() == 0) 5 | return 0; 6 | 7 | int max = 1; 8 | 9 | for(int i=0;i nums[j]) 15 | temp += 1; 16 | else 17 | break; 18 | } 19 | if(temp > max) 20 | max = temp; 21 | } 22 | return max; 23 | } 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /Algorithms/680.Valid-Palindrome-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validPalindrome(string s) { 4 | bool skipFlag = true; 5 | bool result = true; 6 | for(int cur1=0, cur2=s.size()-1; cur1 < cur2; cur1++,cur2--){ 7 | if(s[cur1] != s[cur2]){ 8 | if(skipFlag && s[cur1+1] == s[cur2]){ 9 | cur1 ++; 10 | skipFlag = false; 11 | } 12 | else{ 13 | result = false; 14 | break; 15 | } 16 | } 17 | } 18 | if(result) 19 | return result; 20 | 21 | skipFlag = true; 22 | result = true; 23 | for(int cur1=0, cur2=s.size()-1; cur1 < cur2; cur1++,cur2--){ 24 | if(s[cur1] != s[cur2]){ 25 | if(skipFlag && s[cur1] == s[cur2-1]){ 26 | cur2 --; 27 | skipFlag = false; 28 | } 29 | else{ 30 | result = false; 31 | break; 32 | } 33 | } 34 | } 35 | return result; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Algorithms/69.Sqrt(x)/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int sqrt(int x) 5 | { 6 | double ans = x; 7 | while(abs(ans * ans - x) > 0.0001) 8 | ans = (ans + x / ans) / 2; 9 | return (int)ans; 10 | } 11 | }; -------------------------------------------------------------------------------- /Algorithms/7.Reverse-Integer/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int reverse(int x) 5 | { 6 | int flag = x > 0? 1:-1; 7 | x = abs(x); 8 | 9 | long int result = 0; 10 | int digit = 0; 11 | while(x) 12 | { 13 | digit = x % 10; 14 | result = result * 10 + digit; 15 | x /= 10; 16 | } 17 | 18 | result *= flag; 19 | 20 | if(result > 2147483647 || result < -2147483648) 21 | return 0; 22 | 23 | return (int)result; 24 | } 25 | }; -------------------------------------------------------------------------------- /Algorithms/70.Climbing-Stairs/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int climbStairs(int n) 5 | { 6 | if(n == 0) 7 | return 0; 8 | if(n == 1) 9 | return 1; 10 | if(n == 2) 11 | return 2; 12 | 13 | int sum[n]; 14 | sum[0] = 1; 15 | sum[1] = 2; 16 | for(int i=2;i > f(row, vector(col)); 10 | 11 | for (int i = 0; i < row; i++) 12 | f[i][0] = i; 13 | 14 | for (int i = 0; i < col; i++) 15 | f[0][i] = i; 16 | 17 | for (int i = 1; i < row; i++) 18 | for (int j = 1; j < col; j++) 19 | { 20 | if (word1[i-1] == word2[j-1]) 21 | f[i][j] = f[i-1][j-1]; 22 | else 23 | f[i][j] = f[i-1][j-1] + 1; 24 | f[i][j] = min(f[i][j], min(f[i-1][j]+1, f[i][j-1]+1)); 25 | } 26 | 27 | return f[row-1][col-1]; 28 | } 29 | }; -------------------------------------------------------------------------------- /Algorithms/74.Search-a-2D-Matrix/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int transform(vector > &matrix, int index) 5 | { 6 | return matrix[index/matrix[0].size()][index%matrix[0].size()]; 7 | } 8 | 9 | int bSearch(vector > &matrix, int begin, int end, int target) 10 | { 11 | if(begin <= end) 12 | { 13 | int mid = (begin+end)/2; 14 | int temp = transform(matrix,mid); 15 | if(target == temp) 16 | return mid; 17 | else if(target < temp) 18 | return bSearch(matrix,begin,mid-1,target); 19 | else 20 | return bSearch(matrix,mid+1,end,target); 21 | } 22 | else 23 | return -1; 24 | } 25 | 26 | bool searchMatrix(vector > &matrix, int target) 27 | { 28 | if (bSearch(matrix,0,matrix.size()*matrix[0].size()-1,target) >= 0) 29 | return true; 30 | else 31 | return false; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/746.Min-Cost-Climbing-Stairs/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | vector dp(cost.size(),0); 5 | int dp1 = cost[0]; 6 | int dp2 = cost[1]; 7 | int cur; 8 | for(int i=2;i primeSet(arr,arr+11); 6 | int prime = 0; 7 | for(int i=L;i<=R;i++){ 8 | int temp=0; 9 | int num = i; 10 | while(num>0){ 11 | if(num & 1) 12 | temp += 1; 13 | num = num >> 1; 14 | } 15 | if(primeSet.find(temp) != primeSet.end()) 16 | prime += 1; 17 | } 18 | return prime; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Algorithms/77.Combinations/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > result; 5 | vector flag; 6 | 7 | void solve(vector temp, int k) 8 | { 9 | if(k == 0) 10 | { 11 | result.push_back(temp); 12 | } 13 | else 14 | { 15 | for(int i=temp.empty()?1:temp.back()+1;i > combine(int n, int k) 30 | { 31 | flag.resize(n+1,false); 32 | solve(vector(),k); 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /Algorithms/78.Subsets/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > result; 5 | vector Str; 6 | vector flag; 7 | 8 | void solve(vector temp, int f, int k) 9 | { 10 | if(k == 0) 11 | { 12 | result.push_back(temp); 13 | } 14 | else 15 | { 16 | for(int i=f;i > subsets(vector &S) 31 | { 32 | flag.resize(S.size()); 33 | sort(S.begin(),S.end()); 34 | Str = S; 35 | for(int i=0;i(),0,i); 37 | return result; 38 | } 39 | }; -------------------------------------------------------------------------------- /Algorithms/8.String-to-Integer-(atoi)/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int myAtoi(string str) 5 | { 6 | int tempResult,result=0; 7 | int sign = 1; 8 | int i=0; 9 | 10 | while(i='0' && str[i]<='9') 19 | { 20 | tempResult = result*10 + str[i]-'0'; 21 | if(tempResult/10 != result) 22 | return sign>0 ? INT_MAX:INT_MIN; 23 | result = tempResult; 24 | } 25 | else 26 | break; 27 | } 28 | return result * sign; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/80.Remove-Duplicates-from-Sorted-Array-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int removeDuplicates(int A[], int n) 5 | { 6 | if(n <= 0) 7 | return 0; 8 | int firstIndex = 0, secondIndex = 0; 9 | int curVal = A[0] , curCount = 0; 10 | for(int i=0;i A[mid]) 17 | { 18 | isLeft = false; 19 | break; 20 | } 21 | if(isLeft)//left 22 | { 23 | if(A[left] <= target && target < A[mid]) 24 | right = mid - 1; 25 | else 26 | left = mid + 1; 27 | 28 | } 29 | else//right 30 | { 31 | if(A[mid] < target && target <= A[right]) 32 | left = mid + 1; 33 | else 34 | right = mid - 1; 35 | } 36 | } 37 | 38 | return false; 39 | } 40 | }; -------------------------------------------------------------------------------- /Algorithms/82.Remove-Duplicates-from-Sorted-List-II/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *deleteDuplicates(ListNode *head) 12 | { 13 | ListNode** curNext = &head; 14 | ListNode* cur = head; 15 | while(NULL != cur) 16 | { 17 | ListNode* temp = cur; 18 | while(NULL != cur->next && cur->next->val == cur->val) 19 | cur = cur->next; 20 | if(cur == temp) 21 | { 22 | *curNext = temp; 23 | curNext = &(*curNext)->next; 24 | } 25 | cur = cur->next; 26 | } 27 | *curNext = NULL; 28 | return head; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/825.Friends-Of-Appropriate-Ages/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numFriendRequests(vector& ages) { 4 | sort(ages.begin(),ages.end()); 5 | int count = 0; 6 | int edge; 7 | for(int i=0;i=0;j--) 11 | if(ages[j] > edge) 12 | count ++; 13 | else 14 | break; 15 | 16 | for(j=i+1;j edge) 18 | count ++; 19 | else 20 | break; 21 | } 22 | 23 | return count; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/826.Most-Profit-Assigning-Work/solution.cpp: -------------------------------------------------------------------------------- 1 | bool cmp(pair i, pair j){ 2 | return i.first < j.first; 3 | } 4 | 5 | class Solution { 6 | public: 7 | int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { 8 | vector > prolist(difficulty.size()); 9 | for(int i=0;i pro(profit.size()); 17 | int maxpro = 0; 18 | for(int i=0;i= prolist[j].first) 28 | temppro = prolist[j].second; 29 | else 30 | break; 31 | } 32 | result += temppro; 33 | } 34 | return result; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Algorithms/83.Remove-Duplicates-from-Sorted-List/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | ListNode *deleteDuplicates(ListNode *head) 13 | { 14 | if(head == NULL) 15 | return head; 16 | 17 | ListNode *last = head; 18 | ListNode *temp = head->next; 19 | while(temp != NULL) 20 | { 21 | if(temp->val == last->val) 22 | { 23 | last->next = temp->next; 24 | } 25 | else 26 | { 27 | last = temp; 28 | } 29 | temp = temp->next; 30 | } 31 | return head; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/84.Largest-Rectangle-in-Histogram/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int Max(int a, int b){return a > b ? a : b;} 5 | int largestRectangleArea(vector &height) 6 | { 7 | height.push_back(0); 8 | stack stk; 9 | int i = 0; 10 | int maxArea = 0; 11 | while(i < height.size()) 12 | { 13 | if(stk.empty() || height[stk.top()] <= height[i]) 14 | { 15 | stk.push(i++); 16 | } 17 | else 18 | { 19 | int t = stk.top(); 20 | stk.pop(); 21 | maxArea = Max(maxArea, height[t] * (stk.empty() ? i : i - stk.top() - 1)); 22 | } 23 | } 24 | return maxArea; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/86.Partition-List/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | ListNode *partition(ListNode *head, int x) 14 | { 15 | ListNode *list1 = new ListNode(0); 16 | ListNode *first = list1; 17 | ListNode *list2 = new ListNode(0); 18 | ListNode *second = list2; 19 | while(head != NULL) 20 | { 21 | if(head->val < x) 22 | { 23 | first->next = head; 24 | first = first->next; 25 | } 26 | else 27 | { 28 | second->next = head; 29 | second = second->next; 30 | } 31 | head = head->next; 32 | } 33 | first->next = list2->next; 34 | second->next = NULL; 35 | return list1->next; 36 | } 37 | }; -------------------------------------------------------------------------------- /Algorithms/87.Scramble-String/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isScramble(string s1, string s2) 5 | { 6 | int len = s1.length(); 7 | if(len!=s2.length()) 8 | { 9 | return false; 10 | } 11 | if(len==0) 12 | { 13 | return true; 14 | } 15 | 16 | bool result[len][len][len]; 17 | for(int i=0;i=0;--i) 28 | { 29 | for(int j=len-k;j>=0;--j) 30 | { 31 | bool r = false; 32 | for(int m=1;m grayCode(int n) 5 | { 6 | vector result; 7 | result.push_back(0); 8 | for(int i=0; i=0; i--) 13 | result.push_back(highest+result[i]); 14 | } 15 | return result; 16 | } 17 | }; -------------------------------------------------------------------------------- /Algorithms/897.Increasing-Order-Search-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode *nt; 13 | TreeNode *cur; 14 | TreeNode* increasingBST(TreeNode* root) { 15 | nt = new TreeNode(0); 16 | cur = nt; 17 | midOrder(root); 18 | return nt->right; 19 | } 20 | 21 | int midOrder(TreeNode* node){ 22 | if(node == NULL) 23 | return 0; 24 | midOrder(node->left); 25 | cur->right = new TreeNode(node->val); 26 | cur = cur->right; 27 | midOrder(node->right); 28 | return 0; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/9.Palindrome-Number/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isPalindrome(int x) 5 | { 6 | if(x<0|| (x!=0 &&x%10==0)) return false; 7 | int sum=0; 8 | while(x>sum) 9 | { 10 | sum = sum*10+x%10; 11 | x = x/10; 12 | } 13 | return (x==sum)||(x==sum/10); 14 | } 15 | }; -------------------------------------------------------------------------------- /Algorithms/90.Subsets-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector > v; 5 | vector > subsetsWithDup(vector &S) 6 | { 7 | sort(S.begin(),S.end()); 8 | generate(vector(), S, 0); 9 | return v; 10 | } 11 | 12 | void generate(vector res, vector &S, int i) 13 | { 14 | if(i == S.size()) 15 | { 16 | for(int i = 0; i < v.size(); i++) 17 | { 18 | if(v[i] == res) 19 | { 20 | return; 21 | } 22 | } 23 | v.push_back(res); 24 | return; 25 | } 26 | else 27 | { 28 | generate(res, S, i+1); 29 | res.push_back(S[i]); 30 | generate(res, S, i+1); 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/91.Decode-Ways/solution.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moranzcw/LeetCode-NOTES/49a7e33b83d8d9ce449c758717f74a69e72f808e/Algorithms/91.Decode-Ways/solution.cpp -------------------------------------------------------------------------------- /Algorithms/914.X-of-a-Kind-in-a-Deck-of-Cards/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int get_gcd(int a, int b) { 4 | int h = max(a, b); 5 | int l = min(a, b); 6 | 7 | if (l == 0) return h; 8 | 9 | int m = h % l; 10 | 11 | while (m) { 12 | h = l; 13 | l = m; 14 | m = h % l; 15 | } 16 | return l; 17 | } 18 | 19 | bool hasGroupsSizeX(vector& deck) { 20 | map count; 21 | 22 | for(auto i:deck){ 23 | if(count.find(i) != count.end()) 24 | count[i] += 1; 25 | else 26 | count[i] = 1; 27 | } 28 | 29 | int min_gcd = count.begin()->second; 30 | int last = min_gcd; 31 | for(auto i=count.begin();i!=count.end();i++){ 32 | min_gcd = min(min_gcd, get_gcd(i->second,last)); 33 | last = i->second; 34 | } 35 | return min_gcd>=2; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Algorithms/915.Partition-Array-into-Disjoint-Intervals/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int partitionDisjoint(vector& A) { 4 | vector max_left(A.size()); 5 | vector min_right(A.size()); 6 | max_left[0] = A[0]; 7 | for(int i=1;i=0;i--){ 13 | min_right[i] = min(A[i],min_right[i+1]); 14 | } 15 | 16 | for(int i=0;i& A) { 4 | if(A.size()==0) 5 | return 0; 6 | if(A.size()==1) 7 | return A[0]; 8 | int ans=INT_MIN; 9 | int tol=0; 10 | int least=0; 11 | int num=INT_MAX; 12 | int sum=0; 13 | for(auto ele : A){ 14 | tol+=ele; 15 | sum+=ele; 16 | if(sum<0){ 17 | ans=max(ans,ele); 18 | sum=0; 19 | }else{ 20 | ans=max(sum,ans); 21 | } 22 | least+=ele; 23 | if(least>0) 24 | least=0; 25 | else 26 | num=min(least,num); 27 | } 28 | if(ans<=0) 29 | return ans; 30 | else 31 | return max(ans,tol-num); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/92.Reverse-Linked-List-II/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | 10 | class Solution 11 | { 12 | public: 13 | ListNode *reverseBetween(ListNode *head, int m, int n) 14 | { 15 | if (head == NULL) 16 | return NULL; 17 | 18 | ListNode *q = NULL; 19 | ListNode *p = head; 20 | for(int i = 0; i < m - 1; i++) 21 | { 22 | q = p; 23 | p = p->next; 24 | } 25 | 26 | ListNode *end = p; 27 | ListNode *pPre = p; 28 | p = p->next; 29 | for(int i = m + 1; i <= n; i++) 30 | { 31 | ListNode *pNext = p->next; 32 | 33 | p->next = pPre; 34 | pPre = p; 35 | p = pNext; 36 | } 37 | 38 | end->next = p; 39 | if (q) 40 | q->next = pPre; 41 | else 42 | head = pPre; 43 | 44 | return head; 45 | } 46 | }; -------------------------------------------------------------------------------- /Algorithms/925.Long-Pressed-Name/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isLongPressedName(string name, string typed) { 4 | vector > na, ty; 5 | char last='0'; 6 | for(int i=0;i(name[i], 1)); 11 | last = name[i]; 12 | } 13 | 14 | last='0'; 15 | for(int i=0;i(typed[i], 1)); 20 | last = typed[i]; 21 | } 22 | 23 | if(na.size() != ty.size()) 24 | return false; 25 | for(int i=0;i ty[i].second)) 27 | return false; 28 | } 29 | return true; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/929.Unique-Email-Addresses/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numUniqueEmails(vector& emails) { 4 | set mailset; 5 | for(int i=0;i& A, int S) { 4 | vector dp(A.size()+1,0); 5 | 6 | map > mapp; 7 | 8 | dp[0] = 0; 9 | for(int i=0;i0) 12 | mapp[dp[i+1]].push_back(i); 13 | else 14 | mapp[dp[i+1]] = vector(1,i); 15 | } 16 | 17 | 18 | int num = 0; 19 | for(int i=0;i0){ 22 | for(int j=0;j= i) 24 | num += 1; 25 | } 26 | // for(int j=i;j list; 4 | RecentCounter() { 5 | 6 | } 7 | 8 | int ping(int t) { 9 | list.push_back(t); 10 | int last = t-3000 > 0? t-3000:0; 11 | int i=list.size()-1; 12 | for(;i>=0;i--){ 13 | if(list[i]ping(t); 24 | */ 25 | -------------------------------------------------------------------------------- /Algorithms/938.Range-Sum-of-BST/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int preOrder(TreeNode* root, int L, int R){ 13 | if(root == NULL) 14 | return 0; 15 | if(root->val >= L && root->val <= R){ 16 | return root->val + preOrder(root->left,L,R) + preOrder(root->right,L,R); 17 | } 18 | if(root->val < L){ 19 | return preOrder(root->right,L,R); 20 | } 21 | if(root->val > R){ 22 | return preOrder(root->left,L,R); 23 | } 24 | return 0; 25 | } 26 | 27 | int rangeSumBST(TreeNode* root, int L, int R) { 28 | return preOrder(root, L, R); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/94.Binary-Tree-Inorder-Traversal/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | vector result; 14 | 15 | void dfs(TreeNode *root) 16 | { 17 | if(root == NULL) 18 | return; 19 | else 20 | { 21 | dfs(root->left); 22 | result.push_back(root->val); 23 | dfs(root->right); 24 | } 25 | } 26 | 27 | vector inorderTraversal(TreeNode *root) 28 | { 29 | dfs(root); 30 | return result; 31 | } 32 | }; -------------------------------------------------------------------------------- /Algorithms/940.Distinct-Subsequences-II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int distinctSubseqII(string S) { 4 | vector endsWith(26,0); 5 | long mod = 1e9 + 7; 6 | for (auto c : S) 7 | endsWith[c - 'a'] = accumulate(begin(endsWith), end(endsWith), 1L) % mod; 8 | return accumulate(begin(endsWith), end(endsWith), 0L) % mod; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Algorithms/941.Valid-Mountain-Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validMountainArray(vector& A) { 4 | if(A.size()<3) 5 | return false; 6 | int last = A[0]; 7 | int i; 8 | for(i=1;ilast){ 10 | last = A[i]; 11 | }else{ 12 | break; 13 | } 14 | } 15 | if(i-1==0 || i-1==A.size()-1) 16 | return false; 17 | for(i;i=last) 19 | return false; 20 | last = A[i]; 21 | } 22 | return true; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/942.DI-String-Match/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector diStringMatch(string S) { 4 | int counti = 0, countd = 0; 5 | for(auto c:S){ 6 | if(c == 'I') 7 | counti++; 8 | } 9 | countd = S.size()-counti; 10 | 11 | vector A(S.size()+1); 12 | int iflag = countd, dflag = countd-1; 13 | if(S[0] == 'I'){ 14 | A[0] = 0; 15 | iflag ++; 16 | dflag ++; 17 | }else{ 18 | A[0] = A.size()-1; 19 | } 20 | for(int i=0;i& A) { 4 | string last = A[0]; 5 | int len = A[0].size(); 6 | int del = 0; 7 | for(int i=1;i= last[j]) 11 | last[j] = A[i][j]; 12 | else{ 13 | last[j] = '#'; 14 | del += 1; 15 | } 16 | } 17 | } 18 | } 19 | return del; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Algorithms/945.Minimum-Increment-to-Make-Array-Unique/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minIncrementForUnique(vector& A) { 4 | if(A.size() == 0) 5 | return 0; 6 | sort(A.begin(),A.end()); 7 | vector n; 8 | int last = A[0]; 9 | int move = 0; 10 | for(int i=1;i 1){ 14 | int d = A[i] - last - 1; 15 | for(int j=0;j0;j++){ 16 | last = last + 1; 17 | move += last - n[n.size()-1]; 18 | n.erase(n.end()-1); 19 | } 20 | } 21 | last = A[i]; 22 | } 23 | for(int i=0;i& pushed, vector& popped) { 4 | vector s; 5 | int i=0,j=0; 6 | while(i& tokens, int P) { 4 | sort(tokens.begin(),tokens.end()); 5 | int left = 0, right = tokens.size() - 1; 6 | int points = 0, ans = 0; 7 | while (left <= right && (P >= tokens[left] || points > 0)) { 8 | while (left <= right && P >= tokens[left]) { 9 | P -= tokens[left++]; 10 | points++; 11 | } 12 | ans = max(ans, points); 13 | if (left <= right && points > 0) { 14 | P += tokens[right--]; 15 | points--; 16 | } 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Algorithms/950.Reveal-Cards-In-Increasing-Order/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector deckRevealedIncreasing(vector& deck) { 4 | sort(deck.begin(),deck.end()); 5 | queue q; 6 | for(int i=deck.size()-1;i>=0;i--){ 7 | if(!q.empty()){ 8 | int t = q.front(); 9 | q.pop(); 10 | q.push(t); 11 | } 12 | q.push(deck[i]); 13 | } 14 | vector result(q.size()); 15 | int i = q.size()-1; 16 | while(!q.empty()){ 17 | result[i] = q.front(); 18 | i--; 19 | q.pop(); 20 | } 21 | return result; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Algorithms/951.Flip-Equivalent-Binary-Trees/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool eq(TreeNode* n1, TreeNode* n2){ 13 | if(n1 == NULL && n2 == NULL) 14 | return true; 15 | else if(n1 == NULL || n2 == NULL) 16 | return false; 17 | else{ 18 | if(n1->val == n2->val) 19 | return true; 20 | } 21 | return false; 22 | } 23 | 24 | bool flipEquiv(TreeNode* root1, TreeNode* root2) { 25 | if(eq(root1,root2)){ 26 | if(root1 != NULL){ 27 | return flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right) 28 | || flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left);; 29 | } 30 | return true; 31 | } 32 | return false; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Algorithms/953.Verifying-an-Alien-Dictionary/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool less(string &s1, string &s2, map &m){ 4 | int l = min(s1.size(),s2.size()); 5 | for(int i=0;im[s2[i]]) 9 | return false; 10 | } 11 | if(s1.size() <= s2.size()) 12 | return true; 13 | return false; 14 | } 15 | bool isAlienSorted(vector& words, string order) { 16 | map m; 17 | int i=0; 18 | for(char &a:order){ 19 | m.insert(pair(a,i)); 20 | i++; 21 | } 22 | 23 | for(int i=1;i& A) { 4 | sort(A.begin(),A.end()); 5 | unordered_map used; 6 | for(auto &i:A){ 7 | if(used.find(i) == used.end()) 8 | used.insert(pair(i,1)); 9 | else 10 | used[i] ++; 11 | } 12 | 13 | for(int i=0;i& A, vector &col){ 4 | for (int i=0; i A[i+1][j]) 9 | return false; 10 | } 11 | } 12 | return true; 13 | } 14 | 15 | int minDeletionSize(vector& A) { 16 | int l = A.size(); 17 | int w = A[0].size(); 18 | 19 | vector col; 20 | int res=0; 21 | for(int i=0;i q; 14 | q.push(root); 15 | TreeNode *t; 16 | bool flag=false; 17 | while(q.size()>0){ 18 | t = q.front(); 19 | q.pop(); 20 | if(t==NULL){ 21 | flag = true; 22 | }else{ 23 | if(flag) 24 | return false; 25 | q.push(t->left); 26 | q.push(t->right); 27 | } 28 | } 29 | return true; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/96.Unique-Binary-Search-Trees/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numTrees(int n) 5 | { 6 | if(n<=0) 7 | return 0; 8 | vector res(n+1); 9 | res[0] = 1; 10 | res[1] = 1; 11 | for(int i=2;i<=n;i++) 12 | { 13 | for(int j=0;j &p1, const vector &p2){ 3 | return (p1[0]*p1[0] + p1[1]*p1[1]) < (p2[0]*p2[0] + p2[1]*p2[1]); 4 | } 5 | 6 | class Solution { 7 | public: 8 | vector> kClosest(vector>& points, int K) { 9 | sort(points.begin(), points.end(), cmp); 10 | return vector(points.begin(), points.begin()+K); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Algorithms/974.Subarray-Sums-Divisible-by-K/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraysDivByK(vector& A, int K) { 4 | int sum = 0; 5 | int length = A.size(); 6 | vector mod(K,0); 7 | for(int i = 0; i < length; i++) { 8 | sum += A[i]; 9 | mod[((sum % K) + K) % K]++; // as the sum can be negative, taking modulo twice 10 | } 11 | 12 | sum = 0; 13 | for(int i = 0; i < K; i++) { 14 | if(mod[i] > 1) { 15 | sum += (mod[i] - 1) * mod[i] / 2; 16 | } 17 | } 18 | sum += mod[0]; 19 | return sum; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Algorithms/976.Largest-Perimeter-Triangle/solution.cpp: -------------------------------------------------------------------------------- 1 | bool cmp(int a, int b){ 2 | return a > b; 3 | } 4 | class Solution { 5 | public: 6 | int largestPerimeter(vector& A) { 7 | sort(A.begin(), A.end(), cmp); 8 | for(int i=0;i A[i]) 14 | return A[i] + A[j] + A[k]; 15 | break; 16 | } 17 | } 18 | } 19 | return 0; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Algorithms/98.Validate-Binary-Search-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | class Solution 12 | { 13 | public: 14 | int tmp; 15 | bool tag; 16 | bool key; 17 | bool isValidBST(TreeNode *root) 18 | { 19 | tag = false; 20 | key = true; 21 | check(root); 22 | return key; 23 | } 24 | 25 | void check(TreeNode *root) 26 | { 27 | if(key == false) 28 | return; 29 | if(root == NULL) 30 | return; 31 | check(root->left); 32 | if(tag == false) 33 | { 34 | tmp = root->val; 35 | tag = true; 36 | } 37 | else 38 | { 39 | if(root->val <= tmp) 40 | key = false; 41 | else 42 | tmp = root->val; 43 | } 44 | check(root->right); 45 | } 46 | }; -------------------------------------------------------------------------------- /Algorithms/99.Recover-Binary-Search-Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution 11 | { 12 | public: 13 | TreeNode *node1; 14 | TreeNode *node2; 15 | TreeNode *pre; 16 | 17 | void recoverTree(TreeNode *root) 18 | { 19 | node1 = node2 = pre = NULL; 20 | findout(root); 21 | swap(node1->val, node2->val); 22 | return; 23 | } 24 | 25 | void findout(TreeNode *root) 26 | { 27 | if (root->left != NULL) 28 | findout(root->left); 29 | 30 | if (pre != NULL) 31 | { 32 | if (pre->val > root->val) 33 | { 34 | if (node1 == NULL) 35 | node1 = pre, node2 = root; 36 | else 37 | node2 = root; 38 | } 39 | } 40 | 41 | pre = root; 42 | if (root->right != NULL) 43 | findout(root->right); 44 | } 45 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 默然 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | --------------------------------------------------------------------------------