diff --git a/.github/workflows/ci-cpp.yml b/.github/workflows/ci-cpp.yml new file mode 100644 index 0000000..2d80e89 --- /dev/null +++ b/.github/workflows/ci-cpp.yml @@ -0,0 +1,19 @@ +name: C/C++ CI + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2.1.3 + - name: make + run: python buildcpp.py diff --git a/README.md b/README.md index f44be2e..10a9f14 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,1019 @@ + +![Build](https://github.com/HONGJICAI/LeetCode/actions/workflows/ci-cpp.yml/badge.svg) + # LeetCode + my solution for LeetCode + +# Problem List + +| id | title | language | difficulty | +| ---- | ---- | ---- | ---- | +| 1 | Two Sum | [cpp](cpp/1.cpp) | easy | +| 2 | Add Two Numbers | [cpp](cpp/2.cpp) | medium | +| 3 | Longest Substring Without Repeating Characters | [cpp](cpp/3.cpp) | medium | +| 4 | Median of Two Sorted Arrays | [cpp](cpp/4.cpp) | hard | +| 5 | Longest Palindromic Substring | [cpp](cpp/5.cpp) | medium | +| 6 | Zigzag Conversion | [cpp](cpp/6.cpp) | medium | +| 7 | Reverse Integer | [cpp](cpp/7.cpp) | medium | +| 8 | String to Integer (atoi) | [cpp](cpp/8.cpp) | medium | +| 9 | Palindrome Number | [cpp](cpp/9.cpp) | easy | +| 10 | Regular Expression Matching | | hard | +| 11 | Container With Most Water | [cpp](cpp/11.cpp) | medium | +| 12 | Integer to Roman | [cpp](cpp/12.cpp) | medium | +| 13 | Roman to Integer | [cpp](cpp/13.cpp) | easy | +| 14 | Longest Common Prefix | [cpp](cpp/14.cpp) | easy | +| 15 | 3Sum | [cpp](cpp/15.cpp) | medium | +| 16 | 3Sum Closest | [cpp](cpp/16.cpp) | medium | +| 17 | Letter Combinations of a Phone Number | [cpp](cpp/17.cpp) | medium | +| 18 | 4Sum | [cpp](cpp/18.cpp) | medium | +| 19 | Remove Nth Node From End of List | [cpp](cpp/19.cpp) | medium | +| 20 | Valid Parentheses | [cpp](cpp/20.cpp) | easy | +| 21 | Merge Two Sorted Lists | [cpp](cpp/21.cpp) | easy | +| 22 | Generate Parentheses | [cpp](cpp/22.cpp) | medium | +| 23 | Merge k Sorted Lists | [cpp](cpp/23.cpp) | hard | +| 24 | Swap Nodes in Pairs | [cpp](cpp/24.cpp) | medium | +| 25 | Reverse Nodes in k-Group | [cpp](cpp/25.cpp) | hard | +| 26 | Remove Duplicates from Sorted Array | [cpp](cpp/26.cpp) | easy | +| 27 | Remove Element | [cpp](cpp/27.cpp) | easy | +| 28 | Find the Index of the First Occurrence in a String | [cpp](cpp/28.cpp) | easy | +| 29 | Divide Two Integers | [cpp](cpp/29.cpp) | medium | +| 30 | Substring with Concatenation of All Words | [cpp](cpp/30.cpp) | hard | +| 31 | Next Permutation | [cpp](cpp/31.cpp) | medium | +| 32 | Longest Valid Parentheses | [cpp](cpp/32.cpp) | hard | +| 33 | Search in Rotated Sorted Array | [cpp](cpp/33.cpp) | medium | +| 34 | Find First and Last Position of Element in Sorted Array | [cpp](cpp/34.cpp) | medium | +| 35 | Search Insert Position | [cpp](cpp/35.cpp) | easy | +| 36 | Valid Sudoku | [cpp](cpp/36.cpp) | medium | +| 37 | Sudoku Solver | [cpp](cpp/37.cpp) | hard | +| 38 | Count and Say | [cpp](cpp/38.cpp) | medium | +| 39 | Combination Sum | [cpp](cpp/39.cpp) | medium | +| 40 | Combination Sum II | [cpp](cpp/40.cpp) | medium | +| 41 | First Missing Positive | [cpp](cpp/41.cpp) | hard | +| 42 | Trapping Rain Water | [cpp](cpp/42.cpp) | hard | +| 43 | Multiply Strings | [cpp](cpp/43.cpp) | medium | +| 44 | Wildcard Matching | [cpp](cpp/44.cpp) | hard | +| 45 | Jump Game II | [cpp](cpp/45.cpp) | medium | +| 46 | Permutations | [cpp](cpp/46.cpp) | medium | +| 47 | Permutations II | [cpp](cpp/47.cpp) | medium | +| 48 | Rotate Image | [cpp](cpp/48.cpp) | medium | +| 49 | Group Anagrams | [cpp](cpp/49.cpp) | medium | +| 50 | Pow(x, n) | [cpp](cpp/50.cpp) | medium | +| 51 | N-Queens | [cpp](cpp/51.cpp) | hard | +| 52 | N-Queens II | [cpp](cpp/52.cpp) | hard | +| 53 | Maximum Subarray | [cpp](cpp/53.cpp) | medium | +| 54 | Spiral Matrix | [cpp](cpp/54.cpp) | medium | +| 55 | Jump Game | [cpp](cpp/55.cpp) | medium | +| 56 | Merge Intervals | [cpp](cpp/56.cpp) | medium | +| 57 | Insert Interval | [cpp](cpp/57.cpp) | medium | +| 58 | Length of Last Word | [cpp](cpp/58.cpp) | easy | +| 59 | Spiral Matrix II | [cpp](cpp/59.cpp) | medium | +| 60 | Permutation Sequence | [cpp](cpp/60.cpp) | hard | +| 61 | Rotate List | [cpp](cpp/61.cpp) | medium | +| 62 | Unique Paths | [cpp](cpp/62.cpp) | medium | +| 63 | Unique Paths II | [cpp](cpp/63.cpp) | medium | +| 64 | Minimum Path Sum | [cpp](cpp/64.cpp) | medium | +| 65 | Valid Number | [cpp](cpp/65.cpp) | hard | +| 66 | Plus One | [cpp](cpp/66.cpp) | easy | +| 67 | Add Binary | [cpp](cpp/67.cpp) | easy | +| 68 | Text Justification | [cpp](cpp/68.cpp) | hard | +| 69 | Sqrt(x) | [cpp](cpp/69.cpp) | easy | +| 70 | Climbing Stairs | [cpp](cpp/70.cpp) | easy | +| 71 | Simplify Path | [cpp](cpp/71.cpp) | medium | +| 72 | Edit Distance | [cpp](cpp/72.cpp) | medium | +| 73 | Set Matrix Zeroes | [cpp](cpp/73.cpp) | medium | +| 74 | Search a 2D Matrix | [cpp](cpp/74.cpp) | medium | +| 75 | Sort Colors | [cpp](cpp/75.cpp) | medium | +| 76 | Minimum Window Substring | [cpp](cpp/76.cpp) | hard | +| 77 | Combinations | [cpp](cpp/77.cpp) | medium | +| 78 | Subsets | [cpp](cpp/78.cpp) | medium | +| 79 | Word Search | [cpp](cpp/79.cpp) | medium | +| 80 | Remove Duplicates from Sorted Array II | [cpp](cpp/80.cpp) | medium | +| 81 | Search in Rotated Sorted Array II | [cpp](cpp/81.cpp) | medium | +| 82 | Remove Duplicates from Sorted List II | [cpp](cpp/82.cpp) | medium | +| 83 | Remove Duplicates from Sorted List | [cpp](cpp/83.cpp) | easy | +| 84 | Largest Rectangle in Histogram | [cpp](cpp/84.cpp) | hard | +| 85 | Maximal Rectangle | | hard | +| 86 | Partition List | [cpp](cpp/86.cpp) | medium | +| 87 | Scramble String | | hard | +| 88 | Merge Sorted Array | [cpp](cpp/88.cpp) | easy | +| 89 | Gray Code | [cpp](cpp/89.cpp) | medium | +| 90 | Subsets II | [cpp](cpp/90.cpp) | medium | +| 91 | Decode Ways | [cpp](cpp/91.cpp) | medium | +| 92 | Reverse Linked List II | [cpp](cpp/92.cpp) | medium | +| 93 | Restore IP Addresses | [cpp](cpp/93.cpp) | medium | +| 94 | Binary Tree Inorder Traversal | [cpp](cpp/94.cpp) | easy | +| 95 | Unique Binary Search Trees II | [cpp](cpp/95.cpp) | medium | +| 96 | Unique Binary Search Trees | [cpp](cpp/96.cpp) | medium | +| 97 | Interleaving String | [cpp](cpp/97.cpp) | medium | +| 98 | Validate Binary Search Tree | [cpp](cpp/98.cpp) | medium | +| 99 | Recover Binary Search Tree | [cpp](cpp/99.cpp) | medium | +| 100 | Same Tree | [cpp](cpp/100.cpp) | easy | +| 101 | Symmetric Tree | [cpp](cpp/101.cpp) | easy | +| 102 | Binary Tree Level Order Traversal | [cpp](cpp/102.cpp) | medium | +| 103 | Binary Tree Zigzag Level Order Traversal | [cpp](cpp/103.cpp) | medium | +| 104 | Maximum Depth of Binary Tree | [cpp](cpp/104.cpp) | easy | +| 105 | Construct Binary Tree from Preorder and Inorder Traversal | [cpp](cpp/105.cpp) | medium | +| 106 | Construct Binary Tree from Inorder and Postorder Traversal | | medium | +| 107 | Binary Tree Level Order Traversal II | [cpp](cpp/107.cpp) | medium | +| 108 | Convert Sorted Array to Binary Search Tree | [cpp](cpp/108.cpp) | easy | +| 109 | Convert Sorted List to Binary Search Tree | [cpp](cpp/109.cpp) | medium | +| 110 | Balanced Binary Tree | [cpp](cpp/110.cpp) | easy | +| 111 | Minimum Depth of Binary Tree | [cpp](cpp/111.cpp) | easy | +| 112 | Path Sum | [cpp](cpp/112.cpp) | easy | +| 113 | Path Sum II | [cpp](cpp/113.cpp) | medium | +| 114 | Flatten Binary Tree to Linked List | [cpp](cpp/114.cpp) | medium | +| 115 | Distinct Subsequences | [cpp](cpp/115.cpp) | hard | +| 116 | Populating Next Right Pointers in Each Node | [cpp](cpp/116.cpp) | medium | +| 117 | Populating Next Right Pointers in Each Node II | [cpp](cpp/117.cpp) | medium | +| 118 | Pascal's Triangle | [cpp](cpp/118.cpp) | easy | +| 119 | Pascal's Triangle II | [cpp](cpp/119.cpp) | easy | +| 120 | Triangle | [cpp](cpp/120.cpp) | medium | +| 121 | Best Time to Buy and Sell Stock | [cpp](cpp/121.cpp) | easy | +| 122 | Best Time to Buy and Sell Stock II | [cpp](cpp/122.cpp) | medium | +| 123 | Best Time to Buy and Sell Stock III | | hard | +| 124 | Binary Tree Maximum Path Sum | [cpp](cpp/124.cpp) | hard | +| 125 | Valid Palindrome | [cpp](cpp/125.cpp) | easy | +| 126 | Word Ladder II | | hard | +| 127 | Word Ladder | [cpp](cpp/127.cpp) | hard | +| 128 | Longest Consecutive Sequence | [cpp](cpp/128.cpp) | medium | +| 129 | Sum Root to Leaf Numbers | [cpp](cpp/129.cpp) | medium | +| 130 | Surrounded Regions | [cpp](cpp/130.cpp) | medium | +| 131 | Palindrome Partitioning | [cpp](cpp/131.cpp) | medium | +| 132 | Palindrome Partitioning II | [cpp](cpp/132.cpp) | hard | +| 133 | Clone Graph | [cpp](cpp/133.cpp) | medium | +| 134 | Gas Station | [cpp](cpp/134.cpp) | medium | +| 135 | Candy | | hard | +| 136 | Single Number | [cpp](cpp/136.cpp) | easy | +| 137 | Single Number II | [cpp](cpp/137.cpp) | medium | +| 138 | Copy List with Random Pointer | [cpp](cpp/138.cpp) | medium | +| 139 | Word Break | [cpp](cpp/139.cpp) | medium | +| 140 | Word Break II | [cpp](cpp/140.cpp) | hard | +| 141 | Linked List Cycle | [cpp](cpp/141.cpp) | easy | +| 142 | Linked List Cycle II | [cpp](cpp/142.cpp) | medium | +| 143 | Reorder List | [cpp](cpp/143.cpp) | medium | +| 144 | Binary Tree Preorder Traversal | [cpp](cpp/144.cpp) | easy | +| 145 | Binary Tree Postorder Traversal | [cpp](cpp/145.cpp) | easy | +| 146 | LRU Cache | [cpp](cpp/146.cpp) | medium | +| 147 | Insertion Sort List | [cpp](cpp/147.cpp) | medium | +| 148 | Sort List | [cpp](cpp/148.cpp) | medium | +| 149 | Max Points on a Line | [cpp](cpp/149.cpp) | hard | +| 150 | Evaluate Reverse Polish Notation | [cpp](cpp/150.cpp) | medium | +| 151 | Reverse Words in a String | [cpp](cpp/151.cpp) | medium | +| 152 | Maximum Product Subarray | [cpp](cpp/152.cpp) | medium | +| 153 | Find Minimum in Rotated Sorted Array | [cpp](cpp/153.cpp) | medium | +| 154 | Find Minimum in Rotated Sorted Array II | | hard | +| 155 | Min Stack | [cpp](cpp/155.cpp) | medium | +| 156 | Binary Tree Upside Down | | medium | +| 157 | Read N Characters Given Read4 | | easy | +| 158 | Read N Characters Given read4 II - Call Multiple Times | | hard | +| 159 | Longest Substring with At Most Two Distinct Characters | | medium | +| 160 | Intersection of Two Linked Lists | [cpp](cpp/160.cpp) | easy | +| 161 | One Edit Distance | | medium | +| 162 | Find Peak Element | [cpp](cpp/162.cpp) | medium | +| 163 | Missing Ranges | | easy | +| 164 | Maximum Gap | [cpp](cpp/164.cpp) | medium | +| 165 | Compare Version Numbers | [cpp](cpp/165.cpp) | medium | +| 166 | Fraction to Recurring Decimal | [cpp](cpp/166.cpp) | medium | +| 167 | Two Sum II - Input Array Is Sorted | [cpp](cpp/167.cpp) | medium | +| 168 | Excel Sheet Column Title | [cpp](cpp/168.cpp) | easy | +| 169 | Majority Element | [cpp](cpp/169.cpp) | easy | +| 170 | Two Sum III - Data structure design | | easy | +| 171 | Excel Sheet Column Number | [cpp](cpp/171.cpp) | easy | +| 172 | Factorial Trailing Zeroes | [cpp](cpp/172.cpp) | medium | +| 173 | Binary Search Tree Iterator | [cpp](cpp/173.cpp) | medium | +| 174 | Dungeon Game | | hard | +| 175 | Combine Two Tables | [sql](sql/175.sql) | easy | +| 176 | Second Highest Salary | [sql](sql/176.sql) | medium | +| 177 | Nth Highest Salary | [sql](sql/177.sql) | medium | +| 178 | Rank Scores | | medium | +| 179 | Largest Number | [cpp](cpp/179.cpp) | medium | +| 180 | Consecutive Numbers | | medium | +| 181 | Employees Earning More Than Their Managers | [sql](sql/181.sql) | easy | +| 182 | Duplicate Emails | [sql](sql/182.sql) | easy | +| 183 | Customers Who Never Order | [sql](sql/183.sql) | easy | +| 184 | Department Highest Salary | [sql](sql/184.sql) | medium | +| 185 | Department Top Three Salaries | | hard | +| 186 | Reverse Words in a String II | | medium | +| 187 | Repeated DNA Sequences | [cpp](cpp/187.cpp) | medium | +| 188 | Best Time to Buy and Sell Stock IV | | hard | +| 189 | Rotate Array | [cpp](cpp/189.cpp) | medium | +| 190 | Reverse Bits | [cpp](cpp/190.cpp) | easy | +| 191 | Number of 1 Bits | [cpp](cpp/191.cpp) | easy | +| 192 | Word Frequency | | medium | +| 193 | Valid Phone Numbers | | easy | +| 194 | Transpose File | | medium | +| 195 | Tenth Line | | easy | +| 196 | Delete Duplicate Emails | [sql](sql/196.sql) | easy | +| 197 | Rising Temperature | [sql](sql/197.sql) | easy | +| 198 | House Robber | [cpp](cpp/198.cpp) | medium | +| 199 | Binary Tree Right Side View | [cpp](cpp/199.cpp) | medium | +| 200 | Number of Islands | [cpp](cpp/200.cpp) | medium | +| 201 | Bitwise AND of Numbers Range | [cpp](cpp/201.cpp) | medium | +| 202 | Happy Number | [cpp](cpp/202.cpp) | easy | +| 203 | Remove Linked List Elements | [cpp](cpp/203.cpp) | easy | +| 204 | Count Primes | [cpp](cpp/204.cpp) | medium | +| 205 | Isomorphic Strings | [cpp](cpp/205.cpp) | easy | +| 206 | Reverse Linked List | [cpp](cpp/206.cpp) | easy | +| 207 | Course Schedule | [cpp](cpp/207.cpp) | medium | +| 208 | Implement Trie (Prefix Tree) | [cpp](cpp/208.cpp) | medium | +| 209 | Minimum Size Subarray Sum | [cpp](cpp/209.cpp) | medium | +| 210 | Course Schedule II | | medium | +| 211 | Design Add and Search Words Data Structure | [cpp](cpp/211.cpp) | medium | +| 212 | Word Search II | [cpp](cpp/212.cpp) | hard | +| 213 | House Robber II | [cpp](cpp/213.cpp) | medium | +| 214 | Shortest Palindrome | | hard | +| 215 | Kth Largest Element in an Array | [cpp](cpp/215.cpp) | medium | +| 216 | Combination Sum III | [cpp](cpp/216.cpp) | medium | +| 217 | Contains Duplicate | [cpp](cpp/217.cpp) | easy | +| 218 | The Skyline Problem | | hard | +| 219 | Contains Duplicate II | [cpp](cpp/219.cpp) | easy | +| 220 | Contains Duplicate III | [cpp](cpp/220.cpp) | hard | +| 221 | Maximal Square | [cpp](cpp/221.cpp) | medium | +| 222 | Count Complete Tree Nodes | [cpp](cpp/222.cpp) | easy | +| 223 | Rectangle Area | [cpp](cpp/223.cpp) | medium | +| 224 | Basic Calculator | | hard | +| 225 | Implement Stack using Queues | [cpp](cpp/225.cpp) | easy | +| 226 | Invert Binary Tree | [cpp](cpp/226.cpp) | easy | +| 227 | Basic Calculator II | | medium | +| 228 | Summary Ranges | [cpp](cpp/228.cpp) | easy | +| 229 | Majority Element II | [cpp](cpp/229.cpp) | medium | +| 230 | Kth Smallest Element in a BST | [cpp](cpp/230.cpp) | medium | +| 231 | Power of Two | [cpp](cpp/231.cpp) | easy | +| 232 | Implement Queue using Stacks | [cpp](cpp/232.cpp) | easy | +| 233 | Number of Digit One | | hard | +| 234 | Palindrome Linked List | [cpp](cpp/234.cpp) | easy | +| 235 | Lowest Common Ancestor of a Binary Search Tree | [cpp](cpp/235.cpp) | medium | +| 236 | Lowest Common Ancestor of a Binary Tree | [cpp](cpp/236.cpp) | medium | +| 237 | Delete Node in a Linked List | [cpp](cpp/237.cpp) | medium | +| 238 | Product of Array Except Self | [cpp](cpp/238.cpp) | medium | +| 239 | Sliding Window Maximum | [cpp](cpp/239.cpp) | hard | +| 240 | Search a 2D Matrix II | [cpp](cpp/240.cpp) | medium | +| 241 | Different Ways to Add Parentheses | [cpp](cpp/241.cpp) | medium | +| 242 | Valid Anagram | [cpp](cpp/242.cpp) | easy | +| 243 | Shortest Word Distance | | easy | +| 244 | Shortest Word Distance II | | medium | +| 245 | Shortest Word Distance III | | medium | +| 246 | Strobogrammatic Number | | easy | +| 247 | Strobogrammatic Number II | | medium | +| 248 | Strobogrammatic Number III | | hard | +| 249 | Group Shifted Strings | | medium | +| 250 | Count Univalue Subtrees | | medium | +| 251 | Flatten 2D Vector | | medium | +| 252 | Meeting Rooms | | easy | +| 253 | Meeting Rooms II | | medium | +| 254 | Factor Combinations | | medium | +| 255 | Verify Preorder Sequence in Binary Search Tree | | medium | +| 256 | Paint House | | medium | +| 257 | Binary Tree Paths | [cpp](cpp/257.cpp) | easy | +| 258 | Add Digits | [cpp](cpp/258.cpp) | easy | +| 259 | 3Sum Smaller | | medium | +| 260 | Single Number III | [cpp](cpp/260.cpp) | medium | +| 261 | Graph Valid Tree | | medium | +| 262 | Trips and Users | | hard | +| 263 | Ugly Number | [cpp](cpp/263.cpp) | easy | +| 264 | Ugly Number II | [cpp](cpp/264.cpp) | medium | +| 265 | Paint House II | | hard | +| 266 | Palindrome Permutation | | easy | +| 267 | Palindrome Permutation II | | medium | +| 268 | Missing Number | [cpp](cpp/268.cpp) | easy | +| 269 | Alien Dictionary | | hard | +| 270 | Closest Binary Search Tree Value | | easy | +| 271 | Encode and Decode Strings | | medium | +| 272 | Closest Binary Search Tree Value II | | hard | +| 273 | Integer to English Words | | hard | +| 274 | H-Index | [cpp](cpp/274.cpp) | medium | +| 275 | H-Index II | [cpp](cpp/275.cpp) | medium | +| 276 | Paint Fence | | medium | +| 277 | Find the Celebrity | | medium | +| 278 | First Bad Version | [cpp](cpp/278.cpp) | easy | +| 279 | Perfect Squares | [cpp](cpp/279.cpp) | medium | +| 280 | Wiggle Sort | | medium | +| 281 | Zigzag Iterator | | medium | +| 282 | Expression Add Operators | | hard | +| 283 | Move Zeroes | [cpp](cpp/283.cpp) | easy | +| 284 | Peeking Iterator | [cpp](cpp/284.cpp) | medium | +| 285 | Inorder Successor in BST | | medium | +| 286 | Walls and Gates | | medium | +| 287 | Find the Duplicate Number | [cpp](cpp/287.cpp) | medium | +| 288 | Unique Word Abbreviation | | medium | +| 289 | Game of Life | [cpp](cpp/289.cpp) | medium | +| 290 | Word Pattern | [cpp](cpp/290.cpp) | easy | +| 291 | Word Pattern II | | medium | +| 292 | Nim Game | [cpp](cpp/292.cpp) | easy | +| 293 | Flip Game | | easy | +| 294 | Flip Game II | | medium | +| 295 | Find Median from Data Stream | [cpp](cpp/295.cpp) | hard | +| 296 | Best Meeting Point | | hard | +| 297 | Serialize and Deserialize Binary Tree | [cpp](cpp/297.cpp) | hard | +| 298 | Binary Tree Longest Consecutive Sequence | | medium | +| 299 | Bulls and Cows | [cpp](cpp/299.cpp) | medium | +| 300 | Longest Increasing Subsequence | [cpp](cpp/300.cpp) | medium | +| 301 | Remove Invalid Parentheses | [cpp](cpp/301.cpp) | hard | +| 302 | Smallest Rectangle Enclosing Black Pixels | | hard | +| 303 | Range Sum Query - Immutable | [cpp](cpp/303.cpp) | easy | +| 304 | Range Sum Query 2D - Immutable | [cpp](cpp/304.cpp) | medium | +| 305 | Number of Islands II | | hard | +| 306 | Additive Number | [cpp](cpp/306.cpp) | medium | +| 307 | Range Sum Query - Mutable | [cpp](cpp/307.cpp) | medium | +| 308 | Range Sum Query 2D - Mutable | | medium | +| 309 | Best Time to Buy and Sell Stock with Cooldown | | medium | +| 310 | Minimum Height Trees | | medium | +| 311 | Sparse Matrix Multiplication | | medium | +| 312 | Burst Balloons | | hard | +| 313 | Super Ugly Number | [cpp](cpp/313.cpp) | medium | +| 314 | Binary Tree Vertical Order Traversal | | medium | +| 315 | Count of Smaller Numbers After Self | | hard | +| 316 | Remove Duplicate Letters | [cpp](cpp/316.cpp) | medium | +| 317 | Shortest Distance from All Buildings | | hard | +| 318 | Maximum Product of Word Lengths | [cpp](cpp/318.cpp) | medium | +| 319 | Bulb Switcher | [cpp](cpp/319.cpp) | medium | +| 320 | Generalized Abbreviation | | medium | +| 321 | Create Maximum Number | | hard | +| 322 | Coin Change | [cpp](cpp/322.cpp) | medium | +| 323 | Number of Connected Components in an Undirected Graph | | medium | +| 324 | Wiggle Sort II | [cpp](cpp/324.cpp) | medium | +| 325 | Maximum Size Subarray Sum Equals k | | medium | +| 326 | Power of Three | [cpp](cpp/326.cpp) | easy | +| 327 | Count of Range Sum | | hard | +| 328 | Odd Even Linked List | [cpp](cpp/328.cpp) | medium | +| 329 | Longest Increasing Path in a Matrix | [cpp](cpp/329.cpp) | hard | +| 330 | Patching Array | | hard | +| 331 | Verify Preorder Serialization of a Binary Tree | [cpp](cpp/331.cpp) | medium | +| 332 | Reconstruct Itinerary | | hard | +| 333 | Largest BST Subtree | | medium | +| 334 | Increasing Triplet Subsequence | [cpp](cpp/334.cpp) | medium | +| 335 | Self Crossing | | hard | +| 336 | Palindrome Pairs | [cpp](cpp/336.cpp) | hard | +| 337 | House Robber III | [cpp](cpp/337.cpp) | medium | +| 338 | Counting Bits | [cpp](cpp/338.cpp) | easy | +| 339 | Nested List Weight Sum | | medium | +| 340 | Longest Substring with At Most K Distinct Characters | | medium | +| 341 | Flatten Nested List Iterator | | medium | +| 342 | Power of Four | [cpp](cpp/342.cpp) | easy | +| 343 | Integer Break | [cpp](cpp/343.cpp) | medium | +| 344 | Reverse String | [cpp](cpp/344.cpp) | easy | +| 345 | Reverse Vowels of a String | [cpp](cpp/345.cpp) | easy | +| 346 | Moving Average from Data Stream | | easy | +| 347 | Top K Frequent Elements | [cpp](cpp/347.cpp) | medium | +| 348 | Design Tic-Tac-Toe | | medium | +| 349 | Intersection of Two Arrays | [cpp](cpp/349.cpp) | easy | +| 350 | Intersection of Two Arrays II | [cpp](cpp/350.cpp) | easy | +| 351 | Android Unlock Patterns | | medium | +| 352 | Data Stream as Disjoint Intervals | | hard | +| 353 | Design Snake Game | | medium | +| 354 | Russian Doll Envelopes | | hard | +| 355 | Design Twitter | [cpp](cpp/355.cpp) | medium | +| 356 | Line Reflection | | medium | +| 357 | Count Numbers with Unique Digits | [cpp](cpp/357.cpp) | medium | +| 358 | Rearrange String k Distance Apart | | hard | +| 359 | Logger Rate Limiter | | easy | +| 360 | Sort Transformed Array | | medium | +| 361 | Bomb Enemy | | medium | +| 362 | Design Hit Counter | | medium | +| 363 | Max Sum of Rectangle No Larger Than K | | hard | +| 364 | Nested List Weight Sum II | | medium | +| 365 | Water and Jug Problem | [cpp](cpp/365.cpp) | medium | +| 366 | Find Leaves of Binary Tree | | medium | +| 367 | Valid Perfect Square | [cpp](cpp/367.cpp) | easy | +| 368 | Largest Divisible Subset | | medium | +| 369 | Plus One Linked List | | medium | +| 370 | Range Addition | | medium | +| 371 | Sum of Two Integers | [cpp](cpp/371.cpp) | medium | +| 372 | Super Pow | | medium | +| 373 | Find K Pairs with Smallest Sums | | medium | +| 374 | Guess Number Higher or Lower | [cpp](cpp/374.cpp) | easy | +| 375 | Guess Number Higher or Lower II | | medium | +| 376 | Wiggle Subsequence | [cpp](cpp/376.cpp) | medium | +| 377 | Combination Sum IV | [cpp](cpp/377.cpp) | medium | +| 378 | Kth Smallest Element in a Sorted Matrix | [cpp](cpp/378.cpp) | medium | +| 379 | Design Phone Directory | | medium | +| 380 | Insert Delete GetRandom O(1) | [cpp](cpp/380.cpp) | medium | +| 381 | Insert Delete GetRandom O(1) - Duplicates allowed | | hard | +| 382 | Linked List Random Node | [cpp](cpp/382.cpp) | medium | +| 383 | Ransom Note | [cpp](cpp/383.cpp) | easy | +| 384 | Shuffle an Array | [cpp](cpp/384.cpp) | medium | +| 385 | Mini Parser | | medium | +| 386 | Lexicographical Numbers | [cpp](cpp/386.cpp) | medium | +| 387 | First Unique Character in a String | [cpp](cpp/387.cpp) | easy | +| 388 | Longest Absolute File Path | [cpp](cpp/388.cpp) | medium | +| 389 | Find the Difference | [cpp](cpp/389.cpp) | easy | +| 390 | Elimination Game | [cpp](cpp/390.cpp) | medium | +| 391 | Perfect Rectangle | | hard | +| 392 | Is Subsequence | [cpp](cpp/392.cpp) | easy | +| 393 | UTF-8 Validation | [cpp](cpp/393.cpp) | medium | +| 394 | Decode String | [cpp](cpp/394.cpp) | medium | +| 395 | Longest Substring with At Least K Repeating Characters | [cpp](cpp/395.cpp) | medium | +| 396 | Rotate Function | [cpp](cpp/396.cpp) | medium | +| 397 | Integer Replacement | [cpp](cpp/397.cpp) | medium | +| 398 | Random Pick Index | [cpp](cpp/398.cpp) | medium | +| 399 | Evaluate Division | [cpp](cpp/399.cpp) | medium | +| 400 | Nth Digit | [cpp](cpp/400.cpp) | medium | +| 401 | Binary Watch | [cpp](cpp/401.cpp) | easy | +| 402 | Remove K Digits | [cpp](cpp/402.cpp) | medium | +| 403 | Frog Jump | [cpp](cpp/403.cpp) | hard | +| 404 | Sum of Left Leaves | [cpp](cpp/404.cpp) | easy | +| 405 | Convert a Number to Hexadecimal | [cpp](cpp/405.cpp) | easy | +| 406 | Queue Reconstruction by Height | [cpp](cpp/406.cpp) | medium | +| 407 | Trapping Rain Water II | | hard | +| 408 | Valid Word Abbreviation | | easy | +| 409 | Longest Palindrome | [cpp](cpp/409.cpp) | easy | +| 410 | Split Array Largest Sum | [cpp](cpp/410.cpp) | hard | +| 411 | Minimum Unique Word Abbreviation | | hard | +| 412 | Fizz Buzz | [cpp](cpp/412.cpp) | easy | +| 413 | Arithmetic Slices | [cpp](cpp/413.cpp) | medium | +| 414 | Third Maximum Number | [cpp](cpp/414.cpp) | easy | +| 415 | Add Strings | [cpp](cpp/415.cpp) | easy | +| 416 | Partition Equal Subset Sum | [cpp](cpp/416.cpp) | medium | +| 417 | Pacific Atlantic Water Flow | | medium | +| 418 | Sentence Screen Fitting | | medium | +| 419 | Battleships in a Board | [cpp](cpp/419.cpp) | medium | +| 420 | Strong Password Checker | | hard | +| 421 | Maximum XOR of Two Numbers in an Array | [cpp](cpp/421.cpp) | medium | +| 422 | Valid Word Square | | easy | +| 423 | Reconstruct Original Digits from English | [cpp](cpp/423.cpp) | medium | +| 424 | Longest Repeating Character Replacement | [cpp](cpp/424.cpp) | medium | +| 425 | Word Squares | | hard | +| 432 | All O`one Data Structure | | hard | +| 433 | Minimum Genetic Mutation | | medium | +| 434 | Number of Segments in a String | [cpp](cpp/434.cpp) | easy | +| 435 | Non-overlapping Intervals | | medium | +| 436 | Find Right Interval | | medium | +| 437 | Path Sum III | [cpp](cpp/437.cpp) | medium | +| 438 | Find All Anagrams in a String | [cpp](cpp/438.cpp) | medium | +| 439 | Ternary Expression Parser | | medium | +| 440 | K-th Smallest in Lexicographical Order | | hard | +| 441 | Arranging Coins | [cpp](cpp/441.cpp) | easy | +| 442 | Find All Duplicates in an Array | [cpp](cpp/442.cpp) | medium | +| 443 | String Compression | [cpp](cpp/443.cpp) | medium | +| 444 | Sequence Reconstruction | | medium | +| 445 | Add Two Numbers II | [cpp](cpp/445.cpp) | medium | +| 446 | Arithmetic Slices II - Subsequence | | hard | +| 447 | Number of Boomerangs | [cpp](cpp/447.cpp) | medium | +| 448 | Find All Numbers Disappeared in an Array | [cpp](cpp/448.cpp) | easy | +| 449 | Serialize and Deserialize BST | [cpp](cpp/449.cpp) | medium | +| 450 | Delete Node in a BST | [cpp](cpp/450.cpp) | medium | +| 451 | Sort Characters By Frequency | [cpp](cpp/451.cpp) | medium | +| 452 | Minimum Number of Arrows to Burst Balloons | | medium | +| 453 | Minimum Moves to Equal Array Elements | [cpp](cpp/453.cpp) | medium | +| 454 | 4Sum II | [cpp](cpp/454.cpp) | medium | +| 455 | Assign Cookies | [cpp](cpp/455.cpp) | easy | +| 456 | 132 Pattern | [cpp](cpp/456.cpp) | medium | +| 457 | Circular Array Loop | [cpp](cpp/457.cpp) | medium | +| 458 | Poor Pigs | | hard | +| 459 | Repeated Substring Pattern | [cpp](cpp/459.cpp) | easy | +| 460 | LFU Cache | [cpp](cpp/460.cpp) | hard | +| 461 | Hamming Distance | [cpp](cpp/461.cpp) | easy | +| 462 | Minimum Moves to Equal Array Elements II | [cpp](cpp/462.cpp) | medium | +| 463 | Island Perimeter | [cpp](cpp/463.cpp) | easy | +| 464 | Can I Win | [cpp](cpp/464.cpp) | medium | +| 465 | Optimal Account Balancing | | hard | +| 466 | Count The Repetitions | | hard | +| 467 | Unique Substrings in Wraparound String | | medium | +| 468 | Validate IP Address | | medium | +| 469 | Convex Polygon | | medium | +| 471 | Encode String with Shortest Length | | hard | +| 472 | Concatenated Words | | hard | +| 473 | Matchsticks to Square | [cpp](cpp/473.cpp) | medium | +| 474 | Ones and Zeroes | | medium | +| 475 | Heaters | [cpp](cpp/475.cpp) | medium | +| 476 | Number Complement | [cpp](cpp/476.cpp) | easy | +| 477 | Total Hamming Distance | [cpp](cpp/477.cpp) | medium | +| 479 | Largest Palindrome Product | | hard | +| 480 | Sliding Window Median | | hard | +| 481 | Magical String | | medium | +| 482 | License Key Formatting | [cpp](cpp/482.cpp) | easy | +| 483 | Smallest Good Base | | hard | +| 484 | Find Permutation | | medium | +| 485 | Max Consecutive Ones | [cpp](cpp/485.cpp) | easy | +| 486 | Predict the Winner | | medium | +| 487 | Max Consecutive Ones II | | medium | +| 488 | Zuma Game | | hard | +| 489 | Kth Smallest Instructions | | hard | +| 490 | The Maze | | medium | +| 491 | Non-decreasing Subsequences | [cpp](cpp/491.cpp) | medium | +| 492 | Construct the Rectangle | [cpp](cpp/492.cpp) | easy | +| 493 | Reverse Pairs | | hard | +| 494 | Target Sum | [cpp](cpp/494.cpp) | medium | +| 495 | Teemo Attacking | [cpp](cpp/495.cpp) | easy | +| 496 | Next Greater Element I | [cpp](cpp/496.cpp) | easy | +| 498 | Diagonal Traverse | [cpp](cpp/498.cpp) | medium | +| 499 | The Maze III | | hard | +| 500 | Keyboard Row | [cpp](cpp/500.cpp) | easy | +| 501 | Find Mode in Binary Search Tree | [cpp](cpp/501.cpp) | easy | +| 502 | IPO | | hard | +| 503 | Next Greater Element II | | medium | +| 504 | Base 7 | [cpp](cpp/504.cpp) | easy | +| 505 | The Maze II | | medium | +| 506 | Relative Ranks | [cpp](cpp/506.cpp) | easy | +| 507 | Perfect Number | [cpp](cpp/507.cpp) | easy | +| 508 | Most Frequent Subtree Sum | [cpp](cpp/508.cpp) | medium | +| 509 | Inorder Successor in BST II | [cpp](cpp/509.cpp) | medium | +| 510 | Count Subarrays With More Ones Than Zeros | | medium | +| 511 | All Paths from Source Lead to Destination | | medium | +| 512 | Maximum Alternating Subarray Sum | | medium | +| 513 | Find Bottom Left Tree Value | [cpp](cpp/513.cpp) | medium | +| 514 | Freedom Trail | | hard | +| 515 | Find Largest Value in Each Tree Row | [cpp](cpp/515.cpp) | medium | +| 516 | Longest Palindromic Subsequence | | medium | +| 517 | Super Washing Machines | | hard | +| 518 | Coin Change II | | medium | +| 519 | Widest Pair of Indices With Equal Range Sum | | medium | +| 520 | Detect Capital | [cpp](cpp/520.cpp) | easy | +| 521 | Longest Uncommon Subsequence I | [cpp](cpp/521.cpp) | easy | +| 522 | Longest Uncommon Subsequence II | | medium | +| 523 | Continuous Subarray Sum | [cpp](cpp/523.cpp) | medium | +| 524 | Longest Word in Dictionary through Deleting | [cpp](cpp/524.cpp) | medium | +| 525 | Contiguous Array | [cpp](cpp/525.cpp) | medium | +| 526 | Beautiful Arrangement | [cpp](cpp/526.cpp) | medium | +| 527 | Word Abbreviation | | hard | +| 528 | Swapping Nodes in a Linked List | | medium | +| 529 | Minesweeper | [cpp](cpp/529.cpp) | medium | +| 530 | Minimum Absolute Difference in BST | [cpp](cpp/530.cpp) | easy | +| 531 | Lonely Pixel I | | medium | +| 532 | K-diff Pairs in an Array | [cpp](cpp/532.cpp) | medium | +| 533 | Lonely Pixel II | | medium | +| 535 | Encode and Decode TinyURL | | medium | +| 536 | Construct Binary Tree from String | | medium | +| 537 | Complex Number Multiplication | [cpp](cpp/537.cpp) | medium | +| 538 | Convert BST to Greater Tree | [cpp](cpp/538.cpp) | medium | +| 539 | Minimum Time Difference | [cpp](cpp/539.cpp) | medium | +| 540 | Single Element in a Sorted Array | [cpp](cpp/540.cpp) | medium | +| 541 | Reverse String II | [cpp](cpp/541.cpp) | easy | +| 542 | 01 Matrix | [cpp](cpp/542.cpp) | medium | +| 543 | Diameter of Binary Tree | [cpp](cpp/543.cpp) | easy | +| 544 | Output Contest Matches | | medium | +| 545 | Boundary of Binary Tree | | medium | +| 546 | Remove Boxes | | hard | +| 547 | Number of Provinces | [cpp](cpp/547.cpp) | medium | +| 548 | Split Array with Equal Sum | | hard | +| 549 | Binary Tree Longest Consecutive Sequence II | | medium | +| 550 | Shortest Path to Get Food | | medium | +| 551 | Student Attendance Record I | [cpp](cpp/551.cpp) | easy | +| 552 | Student Attendance Record II | | hard | +| 553 | Optimal Division | [cpp](cpp/553.cpp) | medium | +| 554 | Brick Wall | [cpp](cpp/554.cpp) | medium | +| 555 | Split Concatenated Strings | | medium | +| 556 | Next Greater Element III | | medium | +| 557 | Reverse Words in a String III | [cpp](cpp/557.cpp) | easy | +| 560 | Subarray Sum Equals K | [cpp](cpp/560.cpp) | medium | +| 561 | Array Partition | [cpp](cpp/561.cpp) | easy | +| 562 | Longest Line of Consecutive One in Matrix | | medium | +| 563 | Binary Tree Tilt | [cpp](cpp/563.cpp) | easy | +| 564 | Find the Closest Palindrome | | hard | +| 565 | Array Nesting | [cpp](cpp/565.cpp) | medium | +| 566 | Reshape the Matrix | [cpp](cpp/566.cpp) | easy | +| 567 | Permutation in String | [cpp](cpp/567.cpp) | medium | +| 568 | Maximum Vacation Days | | hard | +| 569 | Median Employee Salary | | hard | +| 570 | Managers with at Least 5 Direct Reports | | medium | +| 571 | Find Median Given Frequency of Numbers | | hard | +| 572 | Subtree of Another Tree | [cpp](cpp/572.cpp) | easy | +| 573 | Squirrel Simulation | | medium | +| 574 | Winning Candidate | | medium | +| 575 | Distribute Candies | [cpp](cpp/575.cpp) | easy | +| 576 | Out of Boundary Paths | | medium | +| 577 | Employee Bonus | | easy | +| 578 | Get Highest Answer Rate Question | | medium | +| 579 | Find Cumulative Salary of an Employee | | hard | +| 580 | Count Student Number in Departments | | medium | +| 581 | Shortest Unsorted Continuous Subarray | [cpp](cpp/581.cpp) | medium | +| 582 | Kill Process | | medium | +| 583 | Delete Operation for Two Strings | [cpp](cpp/583.cpp) | medium | +| 584 | Find Customer Referee | | easy | +| 585 | Investments in 2016 | | medium | +| 586 | Customer Placing the Largest Number of Orders | | easy | +| 587 | Erect the Fence | | hard | +| 588 | Design In-Memory File System | | hard | +| 591 | Tag Validator | | hard | +| 592 | Fraction Addition and Subtraction | [cpp](cpp/592.cpp) | medium | +| 593 | Valid Square | [cpp](cpp/593.cpp) | medium | +| 594 | Longest Harmonious Subsequence | [cpp](cpp/594.cpp) | easy | +| 595 | Big Countries | | easy | +| 596 | Classes More Than 5 Students | | easy | +| 597 | Friend Requests I: Overall Acceptance Rate | | easy | +| 598 | Range Addition II | [cpp](cpp/598.cpp) | easy | +| 599 | Minimum Index Sum of Two Lists | [cpp](cpp/599.cpp) | easy | +| 600 | Non-negative Integers without Consecutive Ones | | hard | +| 601 | Human Traffic of Stadium | | hard | +| 602 | Friend Requests II: Who Has the Most Friends | | medium | +| 603 | Consecutive Available Seats | | easy | +| 604 | Design Compressed String Iterator | [cpp](cpp/604.cpp) | easy | +| 605 | Can Place Flowers | [cpp](cpp/605.cpp) | easy | +| 606 | Construct String from Binary Tree | [cpp](cpp/606.cpp) | medium | +| 607 | Sales Person | | easy | +| 608 | Tree Node | | medium | +| 609 | Find Duplicate File in System | [cpp](cpp/609.cpp) | medium | +| 610 | Triangle Judgement | | easy | +| 611 | Valid Triangle Number | | medium | +| 612 | Shortest Distance in a Plane | | medium | +| 613 | Shortest Distance in a Line | | easy | +| 614 | Second Degree Follower | | medium | +| 615 | Average Salary: Departments VS Company | | hard | +| 616 | Add Bold Tag in String | | medium | +| 617 | Merge Two Binary Trees | [cpp](cpp/617.cpp) | easy | +| 618 | Students Report By Geography | | hard | +| 619 | Biggest Single Number | | easy | +| 620 | Not Boring Movies | | easy | +| 621 | Task Scheduler | [cpp](cpp/621.cpp) | medium | +| 623 | Add One Row to Tree | [cpp](cpp/623.cpp) | medium | +| 624 | Maximum Distance in Arrays | | medium | +| 625 | Minimum Factorization | | medium | +| 626 | Exchange Seats | | medium | +| 627 | Swap Salary | | easy | +| 628 | Maximum Product of Three Numbers | [cpp](cpp/628.cpp) | easy | +| 629 | K Inverse Pairs Array | | hard | +| 630 | Course Schedule III | | hard | +| 631 | Design Excel Sum Formula | | hard | +| 632 | Smallest Range Covering Elements from K Lists | | hard | +| 633 | Sum of Square Numbers | [cpp](cpp/633.cpp) | medium | +| 634 | Find the Derangement of An Array | | medium | +| 635 | Design Log Storage System | | medium | +| 636 | Exclusive Time of Functions | [cpp](cpp/636.cpp) | medium | +| 637 | Average of Levels in Binary Tree | [cpp](cpp/637.cpp) | easy | +| 638 | Shopping Offers | | medium | +| 639 | Decode Ways II | | hard | +| 640 | Solve the Equation | | medium | +| 642 | Design Search Autocomplete System | | hard | +| 643 | Maximum Average Subarray I | [cpp](cpp/643.cpp) | easy | +| 644 | Maximum Average Subarray II | | hard | +| 645 | Set Mismatch | [cpp](cpp/645.cpp) | easy | +| 646 | Maximum Length of Pair Chain | | medium | +| 647 | Palindromic Substrings | [cpp](cpp/647.cpp) | medium | +| 648 | Replace Words | [cpp](cpp/648.cpp) | medium | +| 649 | Dota2 Senate | | medium | +| 650 | 2 Keys Keyboard | [cpp](cpp/650.cpp) | medium | +| 651 | 4 Keys Keyboard | | medium | +| 652 | Find Duplicate Subtrees | | medium | +| 653 | Two Sum IV - Input is a BST | [cpp](cpp/653.cpp) | easy | +| 654 | Maximum Binary Tree | [cpp](cpp/654.cpp) | medium | +| 655 | Print Binary Tree | [cpp](cpp/655.cpp) | medium | +| 656 | Coin Path | | hard | +| 657 | Robot Return to Origin | [cpp](cpp/657.cpp) | easy | +| 658 | Find K Closest Elements | | medium | +| 659 | Split Array into Consecutive Subsequences | | medium | +| 660 | Remove 9 | | hard | +| 661 | Image Smoother | [cpp](cpp/661.cpp) | easy | +| 662 | Maximum Width of Binary Tree | | medium | +| 663 | Equal Tree Partition | | medium | +| 664 | Strange Printer | | hard | +| 665 | Non-decreasing Array | [cpp](cpp/665.cpp) | medium | +| 666 | Path Sum IV | | medium | +| 667 | Beautiful Arrangement II | | medium | +| 668 | Kth Smallest Number in Multiplication Table | | hard | +| 669 | Trim a Binary Search Tree | [cpp](cpp/669.cpp) | medium | +| 670 | Maximum Swap | [cpp](cpp/670.cpp) | medium | +| 671 | Second Minimum Node In a Binary Tree | [cpp](cpp/671.cpp) | easy | +| 672 | Bulb Switcher II | | medium | +| 673 | Number of Longest Increasing Subsequence | | medium | +| 674 | Longest Continuous Increasing Subsequence | [cpp](cpp/674.cpp) | easy | +| 675 | Cut Off Trees for Golf Event | | hard | +| 676 | Implement Magic Dictionary | [cpp](cpp/676.cpp) | medium | +| 677 | Map Sum Pairs | [cpp](cpp/677.cpp) | medium | +| 678 | Valid Parenthesis String | | medium | +| 679 | 24 Game | | hard | +| 680 | Valid Palindrome II | [cpp](cpp/680.cpp) | easy | +| 681 | Next Closest Time | | medium | +| 682 | Baseball Game | [cpp](cpp/682.cpp) | easy | +| 683 | K Empty Slots | | hard | +| 684 | Redundant Connection | | medium | +| 685 | Redundant Connection II | | hard | +| 686 | Repeated String Match | [cpp](cpp/686.cpp) | medium | +| 687 | Longest Univalue Path | [cpp](cpp/687.cpp) | medium | +| 688 | Knight Probability in Chessboard | | medium | +| 689 | Maximum Sum of 3 Non-Overlapping Subarrays | | hard | +| 690 | Employee Importance | [cpp](cpp/690.cpp) | medium | +| 691 | Stickers to Spell Word | | hard | +| 692 | Top K Frequent Words | [cpp](cpp/692.cpp) | medium | +| 693 | Binary Number with Alternating Bits | | easy | +| 694 | Number of Distinct Islands | | medium | +| 695 | Max Area of Island | [cpp](cpp/695.cpp) | medium | +| 696 | Count Binary Substrings | [cpp](cpp/696.cpp) | easy | +| 697 | Degree of an Array | [cpp](cpp/697.cpp) | easy | +| 698 | Partition to K Equal Sum Subsets | [cpp](cpp/698.cpp) | medium | +| 699 | Falling Squares | | hard | +| 711 | Number of Distinct Islands II | | hard | +| 712 | Minimum ASCII Delete Sum for Two Strings | [cpp](cpp/712.cpp) | medium | +| 713 | Subarray Product Less Than K | | medium | +| 714 | Best Time to Buy and Sell Stock with Transaction Fee | | medium | +| 715 | Range Module | | hard | +| 716 | Max Stack | | hard | +| 717 | 1-bit and 2-bit Characters | [cpp](cpp/717.cpp) | easy | +| 718 | Maximum Length of Repeated Subarray | [cpp](cpp/718.cpp) | medium | +| 719 | Find K-th Smallest Pair Distance | | hard | +| 720 | Longest Word in Dictionary | [cpp](cpp/720.cpp) | medium | +| 721 | Accounts Merge | | medium | +| 722 | Remove Comments | [cpp](cpp/722.cpp) | medium | +| 723 | Candy Crush | | medium | +| 724 | Find Pivot Index | [cpp](cpp/724.cpp) | easy | +| 725 | Split Linked List in Parts | | medium | +| 726 | Number of Atoms | | hard | +| 727 | Minimum Window Subsequence | | hard | +| 728 | Self Dividing Numbers | [cpp](cpp/728.cpp) | easy | +| 729 | My Calendar I | | medium | +| 730 | Count Different Palindromic Subsequences | | hard | +| 731 | My Calendar II | | medium | +| 732 | My Calendar III | | hard | +| 733 | Flood Fill | [cpp](cpp/733.cpp) | easy | +| 734 | Sentence Similarity | [cpp](cpp/734.cpp) | easy | +| 735 | Asteroid Collision | | medium | +| 736 | Parse Lisp Expression | | hard | +| 737 | Sentence Similarity II | | medium | +| 738 | Monotone Increasing Digits | | medium | +| 739 | Daily Temperatures | [cpp](cpp/739.cpp) | medium | +| 740 | Delete and Earn | [cpp](cpp/740.cpp) | medium | +| 741 | Cherry Pickup | | hard | +| 742 | To Lower Case | | easy | +| 743 | Closest Leaf in a Binary Tree | | medium | +| 744 | Network Delay Time | [cpp](cpp/744.cpp) | medium | +| 745 | Find Smallest Letter Greater Than Target | | easy | +| 746 | Prefix and Suffix Search | [cpp](cpp/746.cpp) | hard | +| 747 | Min Cost Climbing Stairs | [cpp](cpp/747.cpp) | easy | +| 748 | Largest Number At Least Twice of Others | [cpp](cpp/748.cpp) | easy | +| 749 | Shortest Completing Word | | easy | +| 750 | Contain Virus | | hard | +| 751 | Number Of Corner Rectangles | | medium | +| 752 | IP to CIDR | | medium | +| 753 | Open the Lock | | medium | +| 754 | Cracking the Safe | | hard | +| 755 | Reach a Number | | medium | +| 756 | Pour Water | | medium | +| 757 | Pyramid Transition Matrix | | medium | +| 758 | Convert Binary Search Tree to Sorted Doubly Linked List | | medium | +| 759 | Set Intersection Size At Least Two | | hard | +| 760 | Bold Words in String | | medium | +| 761 | Employee Free Time | | hard | +| 762 | Find Anagram Mappings | [cpp](cpp/762.cpp) | easy | +| 763 | Special Binary String | [cpp](cpp/763.cpp) | hard | +| 764 | N-ary Tree Level Order Traversal | | medium | +| 765 | Serialize and Deserialize N-ary Tree | | hard | +| 766 | Flatten a Multilevel Doubly Linked List | [cpp](cpp/766.cpp) | medium | +| 767 | Prime Number of Set Bits in Binary Representation | | easy | +| 768 | Partition Labels | | medium | +| 769 | Largest Plus Sign | | medium | +| 770 | Couples Holding Hands | | hard | +| 771 | Encode N-ary Tree to Binary Tree | [cpp](cpp/771.cpp) | hard | +| 772 | Construct Quad Tree | | medium | +| 773 | Logical OR of Two Binary Grids Represented as Quad-Trees | | medium | +| 774 | Maximum Depth of N-ary Tree | | easy | +| 775 | N-ary Tree Preorder Traversal | | easy | +| 776 | N-ary Tree Postorder Traversal | | easy | +| 777 | Toeplitz Matrix | | easy | +| 778 | Reorganize String | | medium | +| 779 | Max Chunks To Make Sorted II | | hard | +| 780 | Max Chunks To Make Sorted | | medium | +| 781 | Basic Calculator IV | | hard | +| 782 | Jewels and Stones | | easy | +| 783 | Search in a Binary Search Tree | [cpp](cpp/783.cpp) | easy | +| 784 | Insert into a Binary Search Tree | [cpp](cpp/784.cpp) | medium | +| 785 | Basic Calculator III | | hard | +| 786 | Search in a Sorted Array of Unknown Size | | medium | +| 787 | Sliding Puzzle | | hard | +| 788 | Minimize Max Distance to Gas Station | [cpp](cpp/788.cpp) | hard | +| 789 | Kth Largest Element in a Stream | | easy | +| 790 | Global and Local Inversions | | medium | +| 791 | Split BST | [cpp](cpp/791.cpp) | medium | +| 792 | Binary Search | | easy | +| 793 | Swap Adjacent in LR String | | medium | +| 794 | Swim in Rising Water | | hard | +| 795 | K-th Symbol in Grammar | | medium | +| 796 | Reaching Points | [cpp](cpp/796.cpp) | hard | +| 797 | Rabbits in Forest | [cpp](cpp/797.cpp) | medium | +| 798 | Transform to Chessboard | | hard | +| 799 | Minimum Distance Between BST Nodes | | easy | +| 800 | Letter Case Permutation | | medium | +| 801 | Is Graph Bipartite? | | medium | +| 802 | K-th Smallest Prime Fraction | | medium | +| 803 | Cheapest Flights Within K Stops | | medium | +| 804 | Rotated Digits | [cpp](cpp/804.cpp) | medium | +| 805 | Escape The Ghosts | | medium | +| 806 | Domino and Tromino Tiling | [cpp](cpp/806.cpp) | medium | +| 807 | Custom Sort String | | medium | +| 808 | Number of Matching Subsequences | | medium | +| 809 | Preimage Size of Factorial Zeroes Function | | hard | +| 810 | Valid Tic-Tac-Toe State | | medium | +| 811 | Number of Subarrays with Bounded Maximum | [cpp](cpp/811.cpp) | medium | +| 812 | Rotate String | [cpp](cpp/812.cpp) | easy | +| 813 | All Paths From Source to Target | | medium | +| 814 | Smallest Rotation with Highest Score | [cpp](cpp/814.cpp) | hard | +| 815 | Champagne Tower | | medium | +| 816 | Design HashSet | | easy | +| 817 | Design HashMap | | easy | +| 818 | Similar RGB Color | | easy | +| 819 | Minimum Swaps To Make Sequences Increasing | [cpp](cpp/819.cpp) | hard | +| 820 | Find Eventual Safe States | | medium | +| 821 | Bricks Falling When Hit | [cpp](cpp/821.cpp) | hard | +| 822 | Unique Morse Code Words | | easy | +| 823 | Split Array With Same Average | | hard | +| 824 | Number of Lines To Write String | [cpp](cpp/824.cpp) | easy | +| 825 | Max Increase to Keep City Skyline | | medium | +| 826 | Soup Servings | | medium | +| 827 | Expressive Words | | medium | +| 828 | Chalkboard XOR Game | | hard | +| 829 | Subdomain Visit Count | | medium | +| 830 | Largest Triangle Area | | easy | +| 831 | Largest Sum of Averages | | medium | +| 832 | Binary Tree Pruning | [cpp](cpp/832.cpp) | medium | +| 833 | Bus Routes | | hard | +| 834 | Ambiguous Coordinates | | medium | +| 835 | Linked List Components | | medium | +| 836 | Race Car | | hard | +| 837 | Most Common Word | | easy | +| 838 | Design Linked List | | medium | +| 839 | Short Encoding of Words | | medium | +| 841 | Shortest Distance to a Character | [cpp](cpp/841.cpp) | easy | +| 842 | Card Flipping Game | | medium | +| 843 | Binary Trees With Factors | | medium | +| 850 | Insert into a Sorted Circular Linked List | | medium | +| 851 | Goat Latin | | easy | +| 852 | Friends Of Appropriate Ages | [cpp](cpp/852.cpp) | medium | +| 853 | Most Profit Assigning Work | | medium | +| 854 | Making A Large Island | | hard | +| 855 | Count Unique Characters of All Substrings of a Given String | | hard | +| 856 | Consecutive Numbers Sum | | hard | +| 857 | Positions of Large Groups | | easy | +| 858 | Masking Personal Information | | medium | +| 859 | Design Circular Deque | | medium | +| 860 | Design Circular Queue | [cpp](cpp/860.cpp) | medium | +| 861 | Flipping an Image | | easy | +| 862 | Find And Replace in String | | medium | +| 863 | Sum of Distances in Tree | | hard | +| 864 | Image Overlap | | medium | +| 865 | Robot Room Cleaner | | hard | +| 866 | Rectangle Overlap | | easy | +| 867 | New 21 Game | [cpp](cpp/867.cpp) | medium | +| 868 | Push Dominoes | | medium | +| 869 | Similar String Groups | | hard | +| 870 | Magic Squares In Grid | | medium | +| 871 | Keys and Rooms | | medium | +| 872 | Split Array into Fibonacci Sequence | | medium | +| 873 | Guess the Word | [cpp](cpp/873.cpp) | hard | +| 874 | Backspace String Compare | | easy | +| 875 | Longest Mountain in Array | | medium | +| 876 | Hand of Straights | [cpp](cpp/876.cpp) | medium | +| 877 | Shortest Path Visiting All Nodes | [cpp](cpp/877.cpp) | hard | +| 878 | Shifting Letters | | medium | +| 879 | Maximize Distance to Closest Person | | medium | +| 880 | Rectangle Area II | | hard | +| 881 | Loud and Rich | | medium | +| 882 | Peak Index in a Mountain Array | | medium | +| 883 | Car Fleet | | medium | +| 884 | K-Similar Strings | [cpp](cpp/884.cpp) | hard | +| 885 | Exam Room | [cpp](cpp/885.cpp) | medium | +| 886 | Score of Parentheses | | medium | +| 887 | Minimum Cost to Hire K Workers | | hard | +| 888 | Mirror Reflection | | medium | +| 889 | Buddy Strings | | easy | +| 890 | Lemonade Change | | easy | +| 891 | Score After Flipping Matrix | | medium | +| 892 | Shortest Subarray with Sum at Least K | [cpp](cpp/892.cpp) | hard | +| 893 | All Nodes Distance K in Binary Tree | | medium | +| 894 | Random Pick with Blacklist | [cpp](cpp/894.cpp) | hard | +| 895 | Shortest Path to Get All Keys | | hard | +| 896 | Smallest Subtree with all the Deepest Nodes | [cpp](cpp/896.cpp) | medium | +| 897 | Prime Palindrome | [cpp](cpp/897.cpp) | medium | +| 898 | Transpose Matrix | | easy | +| 899 | Binary Gap | | easy | +| 900 | Reordered Power of 2 | | medium | +| 901 | Advantage Shuffle | | medium | +| 902 | Minimum Number of Refueling Stops | | hard | +| 903 | Implement Rand10() Using Rand7() | | medium | +| 904 | Leaf-Similar Trees | | easy | +| 905 | Length of Longest Fibonacci Subsequence | [cpp](cpp/905.cpp) | medium | +| 906 | Walking Robot Simulation | | medium | +| 907 | Koko Eating Bananas | | medium | +| 908 | Middle of the Linked List | [cpp](cpp/908.cpp) | easy | +| 909 | Stone Game | | medium | +| 910 | Nth Magical Number | | hard | +| 911 | Profitable Schemes | | hard | +| 912 | Random Pick with Weight | [cpp](cpp/912.cpp) | medium | +| 913 | Random Flip Matrix | | medium | +| 914 | Random Point in Non-overlapping Rectangles | | medium | +| 915 | Generate Random Point in a Circle | | medium | +| 916 | Decoded String at Index | | medium | +| 917 | Boats to Save People | [cpp](cpp/917.cpp) | medium | +| 918 | Reachable Nodes In Subdivided Graph | | hard | +| 919 | Projection Area of 3D Shapes | | easy | +| 920 | Uncommon Words from Two Sentences | | easy | +| 921 | Spiral Matrix III | | medium | +| 922 | Possible Bipartition | [cpp](cpp/922.cpp) | medium | +| 923 | Super Egg Drop | | hard | +| 924 | Fair Candy Swap | | easy | +| 925 | Construct Binary Tree from Preorder and Postorder Traversal | [cpp](cpp/925.cpp) | medium | +| 926 | Find and Replace Pattern | | medium | +| 927 | Sum of Subsequence Widths | | hard | +| 928 | Surface Area of 3D Shapes | | easy | +| 929 | Groups of Special-Equivalent Strings | [cpp](cpp/929.cpp) | medium | +| 930 | All Possible Full Binary Trees | | medium | +| 931 | Maximum Frequency Stack | | hard | +| 932 | Monotonic Array | | easy | +| 933 | Increasing Order Search Tree | [cpp](cpp/933.cpp) | easy | +| 934 | Bitwise ORs of Subarrays | | medium | +| 935 | Orderly Queue | | hard | +| 936 | RLE Iterator | | medium | +| 937 | Online Stock Span | | medium | +| 938 | Numbers At Most N Given Digit Set | [cpp](cpp/938.cpp) | hard | +| 939 | Valid Permutations for DI Sequence | | hard | +| 940 | Fruit Into Baskets | | medium | +| 941 | Sort Array By Parity | | easy | +| 942 | Super Palindromes | | hard | +| 943 | Sum of Subarray Minimums | | medium | +| 944 | Smallest Range I | | easy | +| 945 | Snakes and Ladders | | medium | +| 946 | Smallest Range II | | medium | +| 947 | Online Election | | medium | +| 948 | Sort an Array | | medium | +| 949 | Cat and Mouse | | hard | +| 950 | X of a Kind in a Deck of Cards | | easy | +| 951 | Partition Array into Disjoint Intervals | [cpp](cpp/951.cpp) | medium | +| 952 | Word Subsets | | medium | +| 953 | Reverse Only Letters | [cpp](cpp/953.cpp) | easy | +| 954 | Maximum Sum Circular Subarray | | medium | +| 955 | Complete Binary Tree Inserter | | medium | +| 956 | Number of Music Playlists | | hard | +| 957 | Minimum Add to Make Parentheses Valid | | medium | +| 958 | Sort Array By Parity II | | easy | +| 959 | 3Sum With Multiplicity | | medium | +| 960 | Minimize Malware Spread | | hard | +| 961 | Long Pressed Name | [cpp](cpp/961.cpp) | easy | +| 962 | Flip String to Monotone Increasing | | medium | +| 963 | Three Equal Parts | | hard | +| 964 | Minimize Malware Spread II | | hard | +| 965 | Unique Email Addresses | [cpp](cpp/965.cpp) | easy | +| 966 | Binary Subarrays With Sum | | medium | +| 967 | Minimum Falling Path Sum | | medium | +| 968 | Beautiful Array | | medium | +| 969 | Number of Recent Calls | | easy | +| 971 | Shortest Bridge | | medium | +| 972 | Knight Dialer | | medium | +| 973 | Stamping The Sequence | [cpp](cpp/973.cpp) | hard | +| 974 | Reorder Data in Log Files | | medium | +| 975 | Range Sum of BST | | easy | +| 976 | Minimum Area Rectangle | | medium | +| 977 | Distinct Subsequences II | [cpp](cpp/977.cpp) | hard | +| 978 | Valid Mountain Array | | easy | +| 979 | DI String Match | [cpp](cpp/979.cpp) | easy | +| 980 | Find the Shortest Superstring | | hard | +| 981 | Delete Columns to Make Sorted | | easy | +| 982 | Minimum Increment to Make Array Unique | | medium | +| 983 | Validate Stack Sequences | [cpp](cpp/983.cpp) | medium | +| 984 | Most Stones Removed with Same Row or Column | | medium | +| 985 | Bag of Tokens | | medium | +| 986 | Largest Time for Given Digits | [cpp](cpp/986.cpp) | medium | +| 987 | Reveal Cards In Increasing Order | | medium | +| 988 | Flip Equivalent Binary Trees | | medium | +| 989 | Largest Component Size by Common Factor | | hard | +| 990 | Verifying an Alien Dictionary | | easy | +| 991 | Array of Doubled Pairs | | medium | +| 992 | Delete Columns to Make Sorted II | | medium | +| 993 | Tallest Billboard | [cpp](cpp/993.cpp) | hard | +| 994 | Prison Cells After N Days | | medium | +| 998 | Check Completeness of a Binary Tree | | medium | +| 999 | Regions Cut By Slashes | [cpp](cpp/999.cpp) | medium | +| 1000 | Delete Columns to Make Sorted III | | hard | +| 1001 | N-Repeated Element in Size 2N Array | | easy | +| 1002 | Maximum Width Ramp | [cpp](cpp/1002.cpp) | medium | +| 1003 | Minimum Area Rectangle II | | medium | +| 1004 | Least Operators to Express Number | | hard | +| 1005 | Univalued Binary Tree | | easy | +| 1006 | Vowel Spellchecker | | medium | +| 1007 | Numbers With Same Consecutive Differences | | medium | +| 1008 | Binary Tree Cameras | [cpp](cpp/1008.cpp) | hard | +| 1009 | Pancake Sorting | [cpp](cpp/1009.cpp) | medium | +| 1010 | Powerful Integers | | medium | +| 1011 | Flip Binary Tree To Match Preorder Traversal | | medium | +| 1012 | Equal Rational Numbers | | hard | +| 1013 | Fibonacci Number | | easy | +| 1014 | K Closest Points to Origin | | medium | +| 1016 | Subarray Sums Divisible by K | | medium | +| 1017 | Odd Even Jump | | hard | +| 1018 | Largest Perimeter Triangle | | easy | +| 1019 | Squares of a Sorted Array | | easy | +| 1020 | Longest Turbulent Subarray | | medium | +| 1021 | Distribute Coins in Binary Tree | [cpp](cpp/1021.cpp) | medium | +| 1022 | Unique Paths III | [cpp](cpp/1022.cpp) | hard | +| 1023 | Time Based Key-Value Store | | medium | +| 1024 | Triples with Bitwise AND Equal To Zero | | hard | +| 1025 | Minimum Cost For Tickets | [cpp](cpp/1025.cpp) | medium | +| 1026 | String Without AAA or BBB | [cpp](cpp/1026.cpp) | medium | +| 1027 | Sum of Even Numbers After Queries | | medium | +| 1028 | Interval List Intersections | | medium | +| 1029 | Vertical Order Traversal of a Binary Tree | [cpp](cpp/1029.cpp) | hard | +| 1030 | Smallest String Starting From Leaf | [cpp](cpp/1030.cpp) | medium | +| 1031 | Add to Array-Form of Integer | | easy | +| 1032 | Satisfiability of Equality Equations | | medium | +| 1033 | Broken Calculator | | medium | +| 1034 | Subarrays with K Different Integers | | hard | +| 1035 | Cousins in Binary Tree | | easy | +| 1036 | Rotting Oranges | | medium | +| 1037 | Minimum Number of K Consecutive Bit Flips | | hard | +| 1038 | Number of Squareful Arrays | [cpp](cpp/1038.cpp) | hard | +| 1039 | Find the Town Judge | | easy | +| 1040 | Maximum Binary Tree II | | medium | +| 1041 | Available Captures for Rook | | easy | +| 1042 | Minimum Cost to Merge Stones | | hard | +| 1043 | Grid Illumination | | hard | +| 1044 | Find Common Characters | | easy | +| 1045 | Check If Word Is Valid After Substitutions | | medium | +| 1046 | Max Consecutive Ones III | [cpp](cpp/1046.cpp) | medium | +| 1047 | Maximize Sum Of Array After K Negations | [cpp](cpp/1047.cpp) | easy | diff --git a/buildcpp.py b/buildcpp.py new file mode 100644 index 0000000..f250980 --- /dev/null +++ b/buildcpp.py @@ -0,0 +1,64 @@ +import glob +import os + +cpps = glob.glob("cpp/*.cpp") +errors = [] +for cpp in cpps: + print(cpp) + code = ''' +#include +using namespace std; +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; +struct RandomListNode { + int label; + RandomListNode *next, *random; + RandomListNode(int x) : label(x), next(NULL), random(NULL) {} +}; +struct Interval { + int start; + int end; + Interval() : start(0), end(0) {} + Interval(int s, int e) : start(s), end(e) {} +}; +struct TreeLinkNode { + int val; + TreeLinkNode *left, *right, *next; + TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} +}; +class Employee { +public: + // It's the unique ID of each node. + // unique id of this employee + int id; + // the importance value of this employee + int importance; + // the id of direct subordinates + vector subordinates; +}; +''' + with open(cpp) as f: + code += f.read() + with open("a.cpp", "w") as f: + f.writelines(code) + cmd = "g++ a.cpp -o a.so -shared -fpic -std=c++20" + if 0 != os.system(cmd): + errors.append(cpp) +if len(errors) > 0: + print("Errors in the following files:") + for error in errors: + print(error) + exit(1) +print("All files compiled successfully.") diff --git a/cpp/.clang-format b/cpp/.clang-format new file mode 100644 index 0000000..a40958e --- /dev/null +++ b/cpp/.clang-format @@ -0,0 +1,8 @@ +BasedOnStyle: LLVM +IndentWidth: 4 +--- +Language: Cpp +# Force pointers to the type for C++. +AccessModifierOffset: -4 +DerivePointerAlignment: false +PointerAlignment: Left \ No newline at end of file diff --git a/cpp/1.TwoSum.cpp b/cpp/1.TwoSum.cpp deleted file mode 100644 index c795250..0000000 --- a/cpp/1.TwoSum.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - vector twoSum(vector& nums, int target) { - unordered_mapmap; - for (int i=0;isecond,i}; - map[nums[i]]= i; - } - return {}; - } -}; diff --git a/cpp/1.cpp b/cpp/1.cpp new file mode 100644 index 0000000..8b35494 --- /dev/null +++ b/cpp/1.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map map; + for (int i = 0; i < nums.size(); ++i) { + if (auto it = map.find(target - nums[i]); it != map.end()) + return {it->second, i}; + map[nums[i]] = i; + } + return {}; + } +}; diff --git a/cpp/100.SameTree/recursion-3ms.cpp b/cpp/100.SameTree/recursion-3ms.cpp deleted file mode 100644 index 4086ce0..0000000 --- a/cpp/100.SameTree/recursion-3ms.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - bool isSameTree(TreeNode* p, TreeNode* q) { - if(p==NULL||q==NULL)return p==q; - return p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); - } -}; diff --git a/cpp/100.cpp b/cpp/100.cpp new file mode 100644 index 0000000..ad27e3c --- /dev/null +++ b/cpp/100.cpp @@ -0,0 +1,18 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode *p, TreeNode *q) { + if (p == nullptr || q == nullptr) + return p == q; + return p->val == q->val && isSameTree(p->left, q->left) && + isSameTree(p->right, q->right); + } +}; diff --git a/cpp/1002.FindCommonCharacters.cpp b/cpp/1002.FindCommonCharacters.cpp deleted file mode 100644 index da3ec77..0000000 --- a/cpp/1002.FindCommonCharacters.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { //8ms 99.37% -public: - vector commonChars(vector& A) { - vectorarr(26,numeric_limits::max()); - vector res; - for (auto &s : A) { - array cnt={}; - for (auto c : s) - ++cnt[c - 'a']; - for (auto i = 0; i < 26; ++i) - arr[i] = min(arr[i], cnt[i]); - } - for (auto i = 0; i < 26; ++i) - while(arr[i]!=numeric_limits::max()&&arr[i]-->0) - res.push_back(string(1, i + 'a')); - return res; - } -}; \ No newline at end of file diff --git a/cpp/1002.cpp b/cpp/1002.cpp new file mode 100644 index 0000000..be621af --- /dev/null +++ b/cpp/1002.cpp @@ -0,0 +1,18 @@ +class Solution { // 8ms 99.37% +public: + vector commonChars(vector &A) { + vector arr(26, numeric_limits::max()); + vector res; + for (auto &s : A) { + array cnt = {}; + for (auto c : s) + ++cnt[c - 'a']; + for (auto i = 0; i < 26; ++i) + arr[i] = min(arr[i], cnt[i]); + } + for (auto i = 0; i < 26; ++i) + while (arr[i] != numeric_limits::max() && arr[i]-- > 0) + res.push_back(string(1, i + 'a')); + return res; + } +}; \ No newline at end of file diff --git a/cpp/1008.ConstructBinarySearchTreeFromPreorderTraversal.cpp b/cpp/1008.ConstructBinarySearchTreeFromPreorderTraversal.cpp deleted file mode 100644 index 38d90fd..0000000 --- a/cpp/1008.ConstructBinarySearchTreeFromPreorderTraversal.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 4 ms, faster than 96.40% of C++ online submissions for Construct Binary Search Tree from Preorder Traversal. -//Memory Usage: 8.7 MB, less than 97.42% of C++ online submissions for Construct Binary Search Tree from Preorder Traversal. -public: - TreeNode* bstFromPreorder(vector& preorder) { - if(not preorder.size()) - return nullptr; - auto r=new TreeNode(preorder[0]); - auto now=r; - vectorst; - for(int i=1;ival){ - st.push_back(now); - now=now->left=new TreeNode(t); - } - else{ - while(st.size()&&t>st.back()->val){ - now=st.back(); - st.pop_back(); - } - now=now->right=new TreeNode(t); - } - } - return r; - } -}; \ No newline at end of file diff --git a/cpp/1008.cpp b/cpp/1008.cpp new file mode 100644 index 0000000..d573717 --- /dev/null +++ b/cpp/1008.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 4 ms, faster than 96.40% of C++ online submissions for Construct + // Binary Search Tree from Preorder Traversal. Memory Usage: 8.7 MB, less + // than 97.42% of C++ online submissions for Construct Binary Search Tree from + // Preorder Traversal. +public: + TreeNode *bstFromPreorder(vector &preorder) { + if (not preorder.size()) + return nullptr; + auto r = new TreeNode(preorder[0]); + auto now = r; + vector st; + for (int i = 1; i < preorder.size(); ++i) { + auto t = preorder[i]; + if (t < now->val) { + st.push_back(now); + now = now->left = new TreeNode(t); + } else { + while (st.size() && t > st.back()->val) { + now = st.back(); + st.pop_back(); + } + now = now->right = new TreeNode(t); + } + } + return r; + } +}; \ No newline at end of file diff --git a/cpp/1009.ComplementofBase10Integer.cpp b/cpp/1009.ComplementofBase10Integer.cpp deleted file mode 100644 index 6db41c2..0000000 --- a/cpp/1009.ComplementofBase10Integer.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { // 0ms iteration -public: - int bitwiseComplement(int N) { - if(!N) - return 1; - int res=0,time=0; - while(N){ - res+=(!(N&1))<>=1; - } - return res; - } -}; \ No newline at end of file diff --git a/cpp/1009.cpp b/cpp/1009.cpp new file mode 100644 index 0000000..dc68201 --- /dev/null +++ b/cpp/1009.cpp @@ -0,0 +1,13 @@ +class Solution { // 0ms iteration +public: + int bitwiseComplement(int N) { + if (!N) + return 1; + int res = 0, time = 0; + while (N) { + res += (!(N & 1)) << time++; + N >>= 1; + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/101.SymmetricTree/iteration.cpp b/cpp/101.SymmetricTree/iteration.cpp deleted file mode 100644 index a060afc..0000000 --- a/cpp/101.SymmetricTree/iteration.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - bool isSymmetric(TreeNode* root) { - if(root==NULL)return 1; - queueqe1,qe2; - qe1.push(root->left); - qe2.push(root->right); - while(!qe1.empty()&&!qe2.empty()){ - TreeNode *r1=qe1.front(); - TreeNode *r2=qe2.front(); - qe1.pop(); - qe2.pop(); - if(r1&&r2){ - if(r1->val!=r2->val) - return 0; - qe1.push(r1->left); - qe1.push(r1->right); - qe2.push(r2->right); - qe2.push(r2->left); - } - else if(r1!=r2) - return 0; - } - return 1; - } -}; diff --git a/cpp/101.cpp b/cpp/101.cpp new file mode 100644 index 0000000..a48580e --- /dev/null +++ b/cpp/101.cpp @@ -0,0 +1,36 @@ +// iteration.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if (root == NULL) + return 1; + queue qe1, qe2; + qe1.push(root->left); + qe2.push(root->right); + while (!qe1.empty() && !qe2.empty()) { + TreeNode* r1 = qe1.front(); + TreeNode* r2 = qe2.front(); + qe1.pop(); + qe2.pop(); + if (r1 && r2) { + if (r1->val != r2->val) + return 0; + qe1.push(r1->left); + qe1.push(r1->right); + qe2.push(r2->right); + qe2.push(r2->left); + } else if (r1 != r2) + return 0; + } + return 1; + } +}; diff --git a/cpp/102.BinaryTreeLevelOrderTraversal/preOrderReversion-3ms.cpp b/cpp/102.BinaryTreeLevelOrderTraversal/preOrderReversion-3ms.cpp deleted file mode 100644 index fa9cca6..0000000 --- a/cpp/102.BinaryTreeLevelOrderTraversal/preOrderReversion-3ms.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector> levelOrder(TreeNode* root) { - vector>result; - preOrder(0,root,result); - return result; - } - void preOrder(int i,TreeNode* root,vector>&nums){ - if(root==NULL)return; - if(nums.size()==i) - nums.push_back(vector()); - nums[i].push_back(root->val); - preOrder(i+1,root->left,nums); - preOrder(i+1,root->right,nums); - } -}; diff --git a/cpp/102.cpp b/cpp/102.cpp new file mode 100644 index 0000000..d89fd8c --- /dev/null +++ b/cpp/102.cpp @@ -0,0 +1,28 @@ +// preOrderReversion-3ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + void preOrder(int i, TreeNode* root, vector>& nums) { + if (root == nullptr) + return; + if (nums.size() == i) + nums.push_back({}); + nums[i].push_back(root->val); + preOrder(i + 1, root->left, nums); + preOrder(i + 1, root->right, nums); + } + +public: + vector> levelOrder(TreeNode* root) { + vector> result; + preOrder(0, root, result); + return result; + } +}; diff --git a/cpp/1021.RemoveOutermostParentheses.cpp b/cpp/1021.RemoveOutermostParentheses.cpp deleted file mode 100644 index 3769953..0000000 --- a/cpp/1021.RemoveOutermostParentheses.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { // Runtime: 4 ms, faster than 97.26% of C++ online submissions for Remove Outermost Parentheses. -public: - string removeOuterParentheses(string S) { - string res; - int opened = 0; - for (char c : S) { - if (c == '(' && opened++) - res += c; - else if (c == ')' && --opened) - res += c; - } - return res; - } -}; \ No newline at end of file diff --git a/cpp/1021.cpp b/cpp/1021.cpp new file mode 100644 index 0000000..167f4bf --- /dev/null +++ b/cpp/1021.cpp @@ -0,0 +1,15 @@ +class Solution { // Runtime: 4 ms, faster than 97.26% of C++ online submissions + // for Remove Outermost Parentheses. +public: + string removeOuterParentheses(string S) { + string res; + int opened = 0; + for (char c : S) { + if (c == '(' && opened++) + res += c; + else if (c == ')' && --opened) + res += c; + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/1022.SumofRootToLeafBinaryNumbers.cpp b/cpp/1022.SumofRootToLeafBinaryNumbers.cpp deleted file mode 100644 index 8e02a86..0000000 --- a/cpp/1022.SumofRootToLeafBinaryNumbers.cpp +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { //Runtime: 4 ms, faster than 99.07% of C++ online submissions for Sum of Root To Leaf Binary Numbers. -public: - int sumRootToLeaf(TreeNode* root, int val = 0) { - if (!root) - return 0; - val = (val * 2 + root->val); - return root->left == root->right ? val : sumRootToLeaf(root->left, val) + sumRootToLeaf(root->right, val); - } -}; \ No newline at end of file diff --git a/cpp/1022.cpp b/cpp/1022.cpp new file mode 100644 index 0000000..c8b2543 --- /dev/null +++ b/cpp/1022.cpp @@ -0,0 +1,21 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 4 ms, faster than 99.07% of C++ online submissions + // for Sum of Root To Leaf Binary Numbers. +public: + int sumRootToLeaf(TreeNode *root, int val = 0) { + if (!root) + return 0; + val = (val * 2 + root->val); + return root->left == root->right ? val + : sumRootToLeaf(root->left, val) + + sumRootToLeaf(root->right, val); + } +}; \ No newline at end of file diff --git a/cpp/1025.DivisorGame.cpp b/cpp/1025.DivisorGame.cpp deleted file mode 100644 index 0958306..0000000 --- a/cpp/1025.DivisorGame.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Divisor Game. -//Memory Usage: 8.6 MB, less than 12.27% of C++ online submissions for Divisor Game. -public: - bool divisorGame(int N) { - vectordp={0,0,1,0}; - dp.resize(N+1); - for(int i=4;i<=N;++i){ - dp[i]=0; - for(int j=i/2;j>=1;--j){ - if(i%j==0 and dp[i-j]==0){ - dp[i]=1; - break; - } - } - } - return dp[N]; - } -}; \ No newline at end of file diff --git a/cpp/1025.cpp b/cpp/1025.cpp new file mode 100644 index 0000000..cdf327b --- /dev/null +++ b/cpp/1025.cpp @@ -0,0 +1,20 @@ +class Solution { + // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Divisor + // Game. Memory Usage: 8.6 MB, less than 12.27% of C++ online submissions for + // Divisor Game. +public: + bool divisorGame(int N) { + vector dp = {0, 0, 1, 0}; + dp.resize(N + 1); + for (int i = 4; i <= N; ++i) { + dp[i] = 0; + for (int j = i / 2; j >= 1; --j) { + if (i % j == 0 and dp[i - j] == 0) { + dp[i] = 1; + break; + } + } + } + return dp[N]; + } +}; \ No newline at end of file diff --git a/cpp/1026.MaximumDifferenceBetweenNodeAndAncestor.cpp b/cpp/1026.MaximumDifferenceBetweenNodeAndAncestor.cpp deleted file mode 100644 index 725c60b..0000000 --- a/cpp/1026.MaximumDifferenceBetweenNodeAndAncestor.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 8 ms, faster than 92.53% of C++ online submissions for Maximum Difference Between Node and Ancestor. -public: - int maxAncestorDiff(TreeNode* root) { - int ret=0; - function recursion = [&ret,&recursion](auto root,auto maxVal,auto minVal){ - ret=max({abs(maxVal-root->val),abs(minVal-root->val),ret}); - maxVal=max(root->val,maxVal); - minVal=min(root->val,minVal); - if(root->left) - recursion(root->left,maxVal,minVal); - if(root->right) - recursion(root->right,maxVal,minVal); - }; - recursion(root,root->val,root->val); - return ret; - } -}; \ No newline at end of file diff --git a/cpp/1026.cpp b/cpp/1026.cpp new file mode 100644 index 0000000..34dde87 --- /dev/null +++ b/cpp/1026.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 8 ms, faster than 92.53% of C++ online submissions for Maximum + // Difference Between Node and Ancestor. +public: + int maxAncestorDiff(TreeNode *root) { + int ret = 0; + function recursion = + [&ret, &recursion](auto root, auto maxVal, auto minVal) { + ret = max({abs(maxVal - root->val), abs(minVal - root->val), ret}); + maxVal = max(root->val, maxVal); + minVal = min(root->val, minVal); + if (root->left) + recursion(root->left, maxVal, minVal); + if (root->right) + recursion(root->right, maxVal, minVal); + }; + recursion(root, root->val, root->val); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/1029.TwoCityScheduling.cpp b/cpp/1029.TwoCityScheduling.cpp deleted file mode 100644 index 7c55465..0000000 --- a/cpp/1029.TwoCityScheduling.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { // Runtime: 4 ms, faster than 97.52% of C++ online submissions for Two City Scheduling. -public: - int twoCitySchedCost(vector>& cs, int res = 0) { - sort(begin(cs), end(cs), [](auto &v1,auto &v2) { - return (v1[0] - v1[1] < v2[0] - v2[1]); - }); - for (auto i = 0; i < cs.size() / 2; ++i) - res += cs[i][0] + cs[i + cs.size() / 2][1]; - return res; - } -}; \ No newline at end of file diff --git a/cpp/1029.cpp b/cpp/1029.cpp new file mode 100644 index 0000000..1a048e6 --- /dev/null +++ b/cpp/1029.cpp @@ -0,0 +1,11 @@ +class Solution { // Runtime: 4 ms, faster than 97.52% of C++ online submissions + // for Two City Scheduling. +public: + int twoCitySchedCost(vector> &cs, int res = 0) { + sort(begin(cs), end(cs), + [](auto &v1, auto &v2) { return (v1[0] - v1[1] < v2[0] - v2[1]); }); + for (auto i = 0; i < cs.size() / 2; ++i) + res += cs[i][0] + cs[i + cs.size() / 2][1]; + return res; + } +}; \ No newline at end of file diff --git a/cpp/103.BinaryTreeZigzagLevelOrderTraversal/queue.cpp b/cpp/103.BinaryTreeZigzagLevelOrderTraversal/queue.cpp deleted file mode 100644 index 91775d7..0000000 --- a/cpp/103.BinaryTreeZigzagLevelOrderTraversal/queue.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector> zigzagLevelOrder(TreeNode* root) { - queueqe; - vector>result; - if(root==NULL)return result; - qe.push(root); - TreeNode *p; - int level=0,size; - while(!qe.empty()){ - result.push_back(vector(qe.size())); - size=qe.size(); - for(int i=0;ival; - if(p->left!=NULL) - qe.push(p->left); - if(p->right!=NULL) - qe.push(p->right); - } - if(qe.empty())break; - ++level; - result.push_back(vector(qe.size())); - for(int i=qe.size()-1;i>=0;--i){ - p=qe.front(); - qe.pop(); - result[level][i]=p->val; - if(p->left!=NULL) - qe.push(p->left); - if(p->right!=NULL) - qe.push(p->right); - } - ++level; - } - return result; - } -}; diff --git a/cpp/103.cpp b/cpp/103.cpp new file mode 100644 index 0000000..31bd0e6 --- /dev/null +++ b/cpp/103.cpp @@ -0,0 +1,50 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} + * }; + */ +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + if (root == nullptr) + return {}; + queue qe({root}); + vector> result; + int level = 0, size; + while (!qe.empty()) { + result.push_back(vector(qe.size())); + size = qe.size(); + for (int i = 0; i < size; ++i) { + auto p = qe.front(); + qe.pop(); + result[level][i] = p->val; + if (p->left != nullptr) + qe.push(p->left); + if (p->right != nullptr) + qe.push(p->right); + } + if (qe.empty()) + break; + ++level; + result.push_back(vector(qe.size())); + for (int i = qe.size() - 1; i >= 0; --i) { + auto p = qe.front(); + qe.pop(); + result[level][i] = p->val; + if (p->left != nullptr) + qe.push(p->left); + if (p->right != nullptr) + qe.push(p->right); + } + ++level; + } + return result; + } +}; \ No newline at end of file diff --git a/cpp/1030.MatrixCellsinDistanceOrder.cpp b/cpp/1030.MatrixCellsinDistanceOrder.cpp deleted file mode 100644 index 611ebc1..0000000 --- a/cpp/1030.MatrixCellsinDistanceOrder.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { //116 ms -public: - vector> allCellsDistOrder(int R, int C, int r0, int c0) { - vector>>bucket(R + C); - for (int r = 0; r < R; r++) - for (int c = 0; c < C; c++) - bucket[abs(r-r0)+abs(c-c0)].push_back({r,c}); - vector>ret; - for(auto &arr:bucket) - for(auto &pos:arr) - ret.push_back({pos.first,pos.second}); - return ret; - } -}; \ No newline at end of file diff --git a/cpp/1030.cpp b/cpp/1030.cpp new file mode 100644 index 0000000..7a58f64 --- /dev/null +++ b/cpp/1030.cpp @@ -0,0 +1,14 @@ +class Solution { // 116 ms +public: + vector> allCellsDistOrder(int R, int C, int r0, int c0) { + vector>> bucket(R + C); + for (int r = 0; r < R; r++) + for (int c = 0; c < C; c++) + bucket[abs(r - r0) + abs(c - c0)].push_back({r, c}); + vector> ret; + for (auto &arr : bucket) + for (auto &pos : arr) + ret.push_back({pos.first, pos.second}); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/1038.BinarySearchTreetoGreaterSumTree.cpp b/cpp/1038.BinarySearchTreetoGreaterSumTree.cpp deleted file mode 100644 index 9c42ee2..0000000 --- a/cpp/1038.BinarySearchTreetoGreaterSumTree.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { //Runtime: 0 ms, faster than 100.00% of C++ online submissions for Binary Search Tree to Greater Sum Tree. -public: - TreeNode* bstToGst(TreeNode* root,int pre = 0) { - function reverse=[&pre,&reverse](TreeNode* node){ - if (node->right) - reverse(node->right); - pre = node->val = pre + node->val; - if (node->left) - reverse(node->left); - }; - reverse(root); - return root; - } -}; \ No newline at end of file diff --git a/cpp/1038.cpp b/cpp/1038.cpp new file mode 100644 index 0000000..00c0096 --- /dev/null +++ b/cpp/1038.cpp @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 0 ms, faster than 100.00% of C++ online submissions + // for Binary Search Tree to Greater Sum Tree. +public: + TreeNode *bstToGst(TreeNode *root, int pre = 0) { + function reverse = [&pre, &reverse](TreeNode *node) { + if (node->right) + reverse(node->right); + pre = node->val = pre + node->val; + if (node->left) + reverse(node->left); + }; + reverse(root); + return root; + } +}; \ No newline at end of file diff --git a/cpp/104.MaximunDepthOfBinaryTree/recursion-6ms.cpp b/cpp/104.MaximunDepthOfBinaryTree/recursion-6ms.cpp deleted file mode 100644 index c9d2c78..0000000 --- a/cpp/104.MaximunDepthOfBinaryTree/recursion-6ms.cpp +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - int maxDepth(TreeNode* root) { - if(root==NULL)return 0; - int a=1+maxDepth(root->left),b=1+maxDepth(root->right); - if(a>=b) - return a; - return b; - } -}; diff --git a/cpp/104.cpp b/cpp/104.cpp new file mode 100644 index 0000000..8e046ac --- /dev/null +++ b/cpp/104.cpp @@ -0,0 +1,20 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (root == nullptr) + return 0; + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; diff --git a/cpp/1046.LastStoneWeight.cpp b/cpp/1046.LastStoneWeight.cpp deleted file mode 100644 index 252f751..0000000 --- a/cpp/1046.LastStoneWeight.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { // 0ms -public: - int lastStoneWeight(vector& stones) { - make_heap(stones.begin(),stones.end()); - while(stones.size()>1){ - int a=stones[0]; - pop_heap(stones.begin(),stones.end()); - stones.pop_back(); - int b=stones[0]; - pop_heap(stones.begin(),stones.end()); - // stones.pop_back(); - // stones.push_back(a-b); - stones[stones.size()-1]=a-b; - push_heap(stones.begin(),stones.end()); - } - return stones[0]; - } -}; \ No newline at end of file diff --git a/cpp/1046.cpp b/cpp/1046.cpp new file mode 100644 index 0000000..dffba26 --- /dev/null +++ b/cpp/1046.cpp @@ -0,0 +1,18 @@ +class Solution { // 0ms +public: + int lastStoneWeight(vector &stones) { + make_heap(stones.begin(), stones.end()); + while (stones.size() > 1) { + int a = stones[0]; + pop_heap(stones.begin(), stones.end()); + stones.pop_back(); + int b = stones[0]; + pop_heap(stones.begin(), stones.end()); + // stones.pop_back(); + // stones.push_back(a-b); + stones[stones.size() - 1] = a - b; + push_heap(stones.begin(), stones.end()); + } + return stones[0]; + } +}; \ No newline at end of file diff --git a/cpp/1047.RemoveAllAdjacentDuplicatesInString.cpp b/cpp/1047.RemoveAllAdjacentDuplicatesInString.cpp deleted file mode 100644 index b078124..0000000 --- a/cpp/1047.RemoveAllAdjacentDuplicatesInString.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution { //344ms recursion -public: - string removeDuplicates(string S) { - int i=-1,j=1; - for(;jst; - vectordeleted(S.size()); - for(int i=0;i st; + vector deleted(S.size()); + for (int i = 0; i < S.size(); ++i) { + if (!st.empty() && S[st.top()] == S[i]) { + deleted[st.top()] = deleted[i] = true; + st.pop(); + } else { + st.push(i); + } + } + string ret; + for (int i = 0; i < S.size(); ++i) { + if (!deleted[i]) + ret += S[i]; + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/105.ConstructBinaryTreeFromPreorderAndInorderTraversal.cpp b/cpp/105.ConstructBinaryTreeFromPreorderAndInorderTraversal.cpp deleted file mode 100644 index 3126c43..0000000 --- a/cpp/105.ConstructBinaryTreeFromPreorderAndInorderTraversal.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 20 ms, faster than 79.16% of C++ online submissions for Construct Binary Tree from Preorder and Inorder Traversal. -//Memory Usage: 19.2 MB, less than 25.65% of C++ online submissions for Construct Binary Tree from Preorder and Inorder Traversal. -public: - TreeNode* buildTree(vector& preorder, vector& inorder) { - if(!preorder.size()) - return nullptr; - using itr = vector::iterator; - function build=[&build](itr first,itr last,itr& t)->TreeNode* { - auto it=find(first,last,*t); - if(it==last) - return nullptr; - TreeNode *root=new TreeNode(*t++); - root->left=build(first,it,t); - root->right=build(it+1,last,t); - return root; - }; - auto it=begin(preorder); - return build(begin(inorder),end(inorder),it); - } -}; \ No newline at end of file diff --git a/cpp/105.cpp b/cpp/105.cpp new file mode 100644 index 0000000..48b50b9 --- /dev/null +++ b/cpp/105.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 20 ms, faster than 79.16% of C++ online submissions for Construct + // Binary Tree from Preorder and Inorder Traversal. Memory Usage: 19.2 MB, + // less than 25.65% of C++ online submissions for Construct Binary Tree from + // Preorder and Inorder Traversal. +public: + TreeNode *buildTree(vector &preorder, vector &inorder) { + if (!preorder.size()) + return nullptr; + using itr = vector::iterator; + function build = + [&build](itr first, itr last, itr &t) -> TreeNode * { + auto it = find(first, last, *t); + if (it == last) + return nullptr; + TreeNode *root = new TreeNode(*t++); + root->left = build(first, it, t); + root->right = build(it + 1, last, t); + return root; + }; + auto it = begin(preorder); + return build(begin(inorder), end(inorder), it); + } +}; \ No newline at end of file diff --git a/cpp/107.BinaryTreeLevelOrderTraversalII/dfsANDreverse.cpp b/cpp/107.BinaryTreeLevelOrderTraversalII/dfsANDreverse.cpp deleted file mode 100644 index 621019e..0000000 --- a/cpp/107.BinaryTreeLevelOrderTraversalII/dfsANDreverse.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - vector>result; -public: - vector> levelOrderBottom(TreeNode* root) { - dfs(root,0); - return vector>(result.rbegin(),result.rend()); - } - void dfs(TreeNode* root,int depth){ - if(root==NULL) - return; - if(depth==result.size()){ - result.push_back(vector()); - } - result[depth].push_back(root->val); - dfs(root->left,depth+1); - dfs(root->right,depth+1); - } -}; diff --git a/cpp/107.cpp b/cpp/107.cpp new file mode 100644 index 0000000..bd1393e --- /dev/null +++ b/cpp/107.cpp @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} + * }; + */ + +class Solution { + vector> result; + void dfs(TreeNode* root, int depth) { + if (root == nullptr) + return; + if (depth == result.size()) { + result.push_back({}); + } + result[depth].push_back(root->val); + dfs(root->left, depth + 1); + dfs(root->right, depth + 1); + } + +public: + vector> levelOrderBottom(TreeNode* root) { + dfs(root, 0); + return {result.rbegin(), result.rend()}; + } +}; diff --git a/cpp/108.ConvertSortedArrayToBinarySearchTree/recursion.cpp b/cpp/108.ConvertSortedArrayToBinarySearchTree/recursion.cpp deleted file mode 100644 index af469bd..0000000 --- a/cpp/108.ConvertSortedArrayToBinarySearchTree/recursion.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* sortedArrayToBST(vector& nums) { - return recursion(0,nums.size(),nums); - } - TreeNode* recursion(int low,int high,vector&nums){ - if(low>=high) - return NULL; - int mid=(low+high)/2; - TreeNode *p=new TreeNode(nums[mid]); - p->left=recursion(low,mid,nums); - p->right=recursion(mid+1,high,nums); - return p; - } -}; diff --git a/cpp/108.cpp b/cpp/108.cpp new file mode 100644 index 0000000..5f0f39e --- /dev/null +++ b/cpp/108.cpp @@ -0,0 +1,26 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + TreeNode* recursion(int low, int high, vector& nums) { + if (low >= high) + return nullptr; + int mid = (low + high) / 2; + TreeNode* p = new TreeNode(nums[mid]); + p->left = recursion(low, mid, nums); + p->right = recursion(mid + 1, high, nums); + return p; + } + + public: + TreeNode* sortedArrayToBST(vector& nums) { + return recursion(0, nums.size(), nums); + } +}; diff --git a/cpp/109.ConvertSortedListToBinarySearchTree/noExtraSpace-40ms.cpp b/cpp/109.ConvertSortedListToBinarySearchTree/noExtraSpace-40ms.cpp deleted file mode 100644 index b938d2e..0000000 --- a/cpp/109.ConvertSortedListToBinarySearchTree/noExtraSpace-40ms.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - ListNode* getMedian(ListNode *head){ - ListNode *p1=head,*p2=head,*p3=nullptr; - while(p2&&p2->next){ - p2=p2->next->next; - p3=p1; - p1=p1->next; - } - if(p3) - p3->next=nullptr; - return p1; - } -public: - TreeNode* sortedListToBST(ListNode* head) { - auto median = getMedian(head); - if(!median) - return nullptr; - auto root = new TreeNode(median->val); - if(head!=median) - root->left = sortedListToBST(head); - if(median) - root->right = sortedListToBST(median->next); - return root; - } -}; diff --git a/cpp/109.cpp b/cpp/109.cpp new file mode 100644 index 0000000..6d8baa7 --- /dev/null +++ b/cpp/109.cpp @@ -0,0 +1,44 @@ +// noExtraSpace-40ms.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + ListNode *getMedian(ListNode *head) { + ListNode *p1 = head, *p2 = head, *p3 = nullptr; + while (p2 && p2->next) { + p2 = p2->next->next; + p3 = p1; + p1 = p1->next; + } + if (p3) + p3->next = nullptr; + return p1; + } + +public: + TreeNode *sortedListToBST(ListNode *head) { + auto median = getMedian(head); + if (!median) + return nullptr; + auto root = new TreeNode(median->val); + if (head != median) + root->left = sortedListToBST(head); + if (median) + root->right = sortedListToBST(median->next); + return root; + } +}; diff --git a/cpp/11.ContainerWithMostWater.cpp b/cpp/11.ContainerWithMostWater.cpp deleted file mode 100644 index 76b3c0d..0000000 --- a/cpp/11.ContainerWithMostWater.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { //16ms -public: - int maxArea(vector& height) { - int i=0,j=height.size()-1,result=0; - while(i& height) { + int i = 0, j = height.size() - 1, result = 0; + while (i < j) { + result = max(result, min(height[i], height[j]) * (j - i)); + height[i] < height[j] ? ++i : --j; + } + return result; + } +}; \ No newline at end of file diff --git a/cpp/110.BalancedBinaryTree/recursion.cpp b/cpp/110.BalancedBinaryTree/recursion.cpp deleted file mode 100644 index b3b22f4..0000000 --- a/cpp/110.BalancedBinaryTree/recursion.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - bool isBalance=1; -public: - bool isBalanced(TreeNode* root) { - getHeight(root); - return isBalance; - } - int getHeight(TreeNode *root){ - if(!root){ - return 0; - } - int d1=getHeight(root->left)+1; - int d2=getHeight(root->right)+1; - if(abs(d1-d2)>=2) - isBalance=0; - return max(d1,d2); - } -}; diff --git a/cpp/110.cpp b/cpp/110.cpp new file mode 100644 index 0000000..3b6817b --- /dev/null +++ b/cpp/110.cpp @@ -0,0 +1,29 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + bool isBalance = 1; + +public: + bool isBalanced(TreeNode *root) { + getHeight(root); + return isBalance; + } + int getHeight(TreeNode *root) { + if (!root) { + return 0; + } + int d1 = getHeight(root->left) + 1; + int d2 = getHeight(root->right) + 1; + if (abs(d1 - d2) >= 2) + isBalance = 0; + return max(d1, d2); + } +}; diff --git a/cpp/111.MinimumDepthOfBinaryTree/conciseIdea.cpp b/cpp/111.MinimumDepthOfBinaryTree/conciseIdea.cpp deleted file mode 100644 index 91d856b..0000000 --- a/cpp/111.MinimumDepthOfBinaryTree/conciseIdea.cpp +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { -public: - int minDepth(TreeNode *root) { - if(!root) return 0; - if(!root->left) return 1 + minDepth(root->right); - if(!root->right) return 1 + minDepth(root->left); - return 1+min(minDepth(root->left),minDepth(root->right)); - } -}; diff --git a/cpp/111.MinimumDepthOfBinaryTree/recursion.cpp b/cpp/111.MinimumDepthOfBinaryTree/recursion.cpp deleted file mode 100644 index c9fc552..0000000 --- a/cpp/111.MinimumDepthOfBinaryTree/recursion.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int min=INT_MAX; -public: - int minDepth(TreeNode* root) { - if(!root)return 0; - searchDepth(root,1); - return min; - } - void searchDepth(TreeNode* root,int depth){ - if(root==NULL) - return; - if(!root->left&&!root->right) - min=minleft,depth+1); - searchDepth(root->right,depth+1); - } -}; diff --git a/cpp/111.cpp b/cpp/111.cpp new file mode 100644 index 0000000..d4b18b2 --- /dev/null +++ b/cpp/111.cpp @@ -0,0 +1,42 @@ +// conciseIdea.cpp +class Solution { +public: + int minDepth(TreeNode *root) { + if (!root) + return 0; + if (!root->left) + return 1 + minDepth(root->right); + if (!root->right) + return 1 + minDepth(root->left); + return 1 + min(minDepth(root->left), minDepth(root->right)); + } +}; +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution2 { + int min = INT_MAX; + +public: + int minDepth(TreeNode *root) { + if (!root) + return 0; + searchDepth(root, 1); + return min; + } + void searchDepth(TreeNode *root, int depth) { + if (root == NULL) + return; + if (!root->left && !root->right) + min = min < depth ? min : depth; + searchDepth(root->left, depth + 1); + searchDepth(root->right, depth + 1); + } +}; diff --git a/cpp/112.PathSum/recursion-9ms.cpp b/cpp/112.PathSum/recursion-9ms.cpp deleted file mode 100644 index 8d3b439..0000000 --- a/cpp/112.PathSum/recursion-9ms.cpp +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - bool hasPathSum(TreeNode* root, int sum) { - if(root==NULL) - return 0; - if(root->val==sum&&root->left==NULL&&root->right==NULL) - return 1; - return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val); - } -}; diff --git a/cpp/112.cpp b/cpp/112.cpp new file mode 100644 index 0000000..41a68df --- /dev/null +++ b/cpp/112.cpp @@ -0,0 +1,21 @@ +// recursion-9ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * }; + */ +class Solution { + public: + bool hasPathSum(TreeNode* root, int sum) { + if (root == nullptr) + return 0; + if (root->val == sum && root->left == nullptr && root->right == nullptr) + return 1; + return hasPathSum(root->left, sum - root->val) || + hasPathSum(root->right, sum - root->val); + } +}; diff --git a/cpp/113.PathSumII/recursion-13ms.cpp b/cpp/113.PathSumII/recursion-13ms.cpp deleted file mode 100644 index 48d9dad..0000000 --- a/cpp/113.PathSumII/recursion-13ms.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - vector>result; -public: - vector> pathSum(TreeNode* root, int sum) { - vectornow; - hasSum(root,sum,now); - return result; - } - void hasSum(TreeNode* root, int sum,vector&now){ - if(root==NULL) - return; - now.push_back(root->val); - if(0==sum-root->val&&root->left==NULL&&root->right==NULL) - result.push_back(now); - hasSum(root->left,sum-root->val,now); - hasSum(root->right,sum-root->val,now); - now.pop_back(); - } -}; \ No newline at end of file diff --git a/cpp/113.cpp b/cpp/113.cpp new file mode 100644 index 0000000..85d6d12 --- /dev/null +++ b/cpp/113.cpp @@ -0,0 +1,31 @@ +// recursion-13ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * }; + */ +class Solution { + vector> result; + void hasSum(TreeNode* root, int sum, vector& now) { + if (root == nullptr) + return; + now.push_back(root->val); + if (0 == sum - root->val && root->left == nullptr && + root->right == nullptr) + result.push_back(now); + hasSum(root->left, sum - root->val, now); + hasSum(root->right, sum - root->val, now); + now.pop_back(); + } + + public: + vector> pathSum(TreeNode* root, int sum) { + vector now; + hasSum(root, sum, now); + return result; + } +}; \ No newline at end of file diff --git a/cpp/114.FlattenBinaryTreeToLinkedList/recursion.cpp b/cpp/114.FlattenBinaryTreeToLinkedList/recursion.cpp deleted file mode 100644 index ca9e177..0000000 --- a/cpp/114.FlattenBinaryTreeToLinkedList/recursion.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - TreeNode *pre=nullptr; -public: - void flatten(TreeNode* root) { - if(!root) - return; - flatten(root->right); - flatten(root->left); - root->left=nullptr; - root->right=pre; - pre=root; - } -}; diff --git a/cpp/114.cpp b/cpp/114.cpp new file mode 100644 index 0000000..5673144 --- /dev/null +++ b/cpp/114.cpp @@ -0,0 +1,24 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + TreeNode *pre = nullptr; + +public: + void flatten(TreeNode *root) { + if (!root) + return; + flatten(root->right); + flatten(root->left); + root->left = nullptr; + root->right = pre; + pre = root; + } +}; diff --git a/cpp/115.DistinctSubsequences/dp.cpp b/cpp/115.DistinctSubsequences/dp.cpp deleted file mode 100644 index 75d2a90..0000000 --- a/cpp/115.DistinctSubsequences/dp.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int numDistinct(string s, string t) { - vector>dp(t.size()+1,vector(s.size()+1,0)); - dp[0]=vector(s.size()+1,1); - for(int i=1;i<=t.size();++i) - for(int j=1;j<=s.size();++j) - dp[i][j]=dp[i][j-1]+(t[i-1]==s[j-1]?dp[i-1][j-1]:0); - return dp[t.size()][s.size()]; - } -}; diff --git a/cpp/115.cpp b/cpp/115.cpp new file mode 100644 index 0000000..2e65895 --- /dev/null +++ b/cpp/115.cpp @@ -0,0 +1,12 @@ +// dp.cpp +class Solution { +public: + int numDistinct(string s, string t) { + vector> dp(t.size() + 1, vector(s.size() + 1, 0)); + dp[0] = vector(s.size() + 1, 1); + for (int i = 1; i <= t.size(); ++i) + for (int j = 1; j <= s.size(); ++j) + dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0); + return dp[t.size()][s.size()]; + } +}; diff --git a/cpp/116.PopulatingNextRightPointersInEachNode/iteration.cpp b/cpp/116.PopulatingNextRightPointersInEachNode/iteration.cpp deleted file mode 100644 index 88b2d92..0000000 --- a/cpp/116.PopulatingNextRightPointersInEachNode/iteration.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for binary tree with next pointer. - * struct TreeLinkNode { - * int val; - * TreeLinkNode *left, *right, *next; - * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} - * }; - */ -class Solution { -public: - void connect(TreeLinkNode *root) { - while(root&&root->left){ - TreeLinkNode *p=root; - while(root){ - root->left->next=root->right; - if(!root->next)break; - root->right->next=root->next->left; - root=root->next; - } - root=p->left; - } - } -}; diff --git a/cpp/116.cpp b/cpp/116.cpp new file mode 100644 index 0000000..740baea --- /dev/null +++ b/cpp/116.cpp @@ -0,0 +1,25 @@ +// iteration.cpp +/** + * Definition for binary tree with next pointer. + * struct TreeLinkNode { + * int val; + * TreeLinkNode *left, *right, *next; + * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} + * }; + */ +class Solution { +public: + void connect(TreeLinkNode *root) { + while (root && root->left) { + TreeLinkNode *p = root; + while (root) { + root->left->next = root->right; + if (!root->next) + break; + root->right->next = root->next->left; + root = root->next; + } + root = p->left; + } + } +}; diff --git a/cpp/117.PopulatingNextRightPointersInEachNodeII/iteration.cpp b/cpp/117.PopulatingNextRightPointersInEachNodeII/iteration.cpp deleted file mode 100644 index d7e2dab..0000000 --- a/cpp/117.PopulatingNextRightPointersInEachNodeII/iteration.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for binary tree with next pointer. - * struct TreeLinkNode { - * int val; - * TreeLinkNode *left, *right, *next; - * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} - * }; - */ -class Solution { - TreeLinkNode *getFirstChild(TreeLinkNode *&root) { - for (;root;root=root->next) { - if (root->left) - return root->left; - if (root->right) - return root->right; - } - return nullptr; - } - TreeLinkNode *getNext(TreeLinkNode *now, TreeLinkNode *&parent) { - if (parent->left == now&&parent->right) - return parent->right; - for (parent = parent->next; parent; parent = parent->next) { - if (parent->left) - return parent->left; - if (parent->right) - return parent->right; - } - return nullptr; - } -public: - void connect(TreeLinkNode *root) { - while (root) { - TreeLinkNode *head = getFirstChild(root); - for (TreeLinkNode *cur=head;cur;cur=cur->next) - cur->next = getNext(cur, root); - root=head; - } - } -}; diff --git a/cpp/117.cpp b/cpp/117.cpp new file mode 100644 index 0000000..f4fc726 --- /dev/null +++ b/cpp/117.cpp @@ -0,0 +1,41 @@ +// iteration.cpp +/** + * Definition for binary tree with next pointer. + * struct TreeLinkNode { + * int val; + * TreeLinkNode *left, *right, *next; + * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} + * }; + */ +class Solution { + TreeLinkNode *getFirstChild(TreeLinkNode *&root) { + for (; root; root = root->next) { + if (root->left) + return root->left; + if (root->right) + return root->right; + } + return nullptr; + } + TreeLinkNode *getNext(TreeLinkNode *now, TreeLinkNode *&parent) { + if (parent->left == now && parent->right) + return parent->right; + for (parent = parent->next; parent; parent = parent->next) { + if (parent->left) + return parent->left; + if (parent->right) + return parent->right; + } + return nullptr; + } + +public: + void connect(TreeLinkNode *root) { + while (root) { + TreeLinkNode *head = getFirstChild(root); + for (TreeLinkNode *cur = head; cur; cur = cur->next) + cur->next = getNext(cur, root); + root = head; + } + } +}; diff --git a/cpp/118.PascalsTriangle/iteration-3ms.cpp b/cpp/118.PascalsTriangle/iteration-3ms.cpp deleted file mode 100644 index f2f1f75..0000000 --- a/cpp/118.PascalsTriangle/iteration-3ms.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - vector> generate(int numRows) { - vector>result; - if(numRows==0)return result; - result.push_back(vector(1,1)); - if(numRows==1)return result; - vectora; - for(int row=1;row> generate(int numRows) { + vector> result{{1}}; + vector a; + for (int row = 1; row < numRows; ++row) { + a.push_back(1); + for (int i = 1; i < row; ++i) + a.push_back(result[row - 1][i] + result[row - 1][i - 1]); + a.push_back(1); + result.push_back(move(a)); + } + return result; + } +}; \ No newline at end of file diff --git a/cpp/119.PascalsTriangleII/iteration-0ms.cpp b/cpp/119.PascalsTriangleII/iteration-0ms.cpp deleted file mode 100644 index 0344a9e..0000000 --- a/cpp/119.PascalsTriangleII/iteration-0ms.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - vector getRow(int rowIndex) { - vectora(rowIndex+1,1); - for(int row=2;row<=rowIndex;++row) - for(int i=row-1;i>0;--i) - a[i]=a[i]+a[i-1]; - return a; - } -}; \ No newline at end of file diff --git a/cpp/119.cpp b/cpp/119.cpp new file mode 100644 index 0000000..4ac9829 --- /dev/null +++ b/cpp/119.cpp @@ -0,0 +1,11 @@ +// iteration-0ms.cpp +class Solution { +public: + vector getRow(int rowIndex) { + vector a(rowIndex + 1, 1); + for (int row = 2; row <= rowIndex; ++row) + for (int i = row - 1; i > 0; --i) + a[i] = a[i] + a[i - 1]; + return a; + } +}; \ No newline at end of file diff --git a/cpp/12.IntegerToRoman/ugly.cpp b/cpp/12.IntegerToRoman/ugly.cpp deleted file mode 100644 index f3beb5a..0000000 --- a/cpp/12.IntegerToRoman/ugly.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { -public: - string intToRoman(int num) { - string res=""; - unordered_maphash={{1,'I'},{5,'V'},{10,'X'},{50,'L'},{100,'C'},{500,'D'},{1000,'M'}}; - for(int base=1000,r;base;base/=10){ - r=num/base; - if(r){ - switch(r){ - case 4: - res=res+hash[base]+hash[base*5];break; - case 9: - res=res+hash[base]+hash[base*10];break; - default: - if(r>=5) - res.append(1,hash[base*5]); - res.append(r%5,hash[base]); - } - num-=r*base; - } - } - return res; - } -}; diff --git a/cpp/12.cpp b/cpp/12.cpp new file mode 100644 index 0000000..3d059f0 --- /dev/null +++ b/cpp/12.cpp @@ -0,0 +1,29 @@ +// ugly.cpp +class Solution { +public: + string intToRoman(int num) { + string res = ""; + unordered_map hash = {{1, 'I'}, {5, 'V'}, {10, 'X'}, + {50, 'L'}, {100, 'C'}, {500, 'D'}, + {1000, 'M'}}; + for (int base = 1000, r; base; base /= 10) { + r = num / base; + if (r) { + switch (r) { + case 4: + res = res + hash[base] + hash[base * 5]; + break; + case 9: + res = res + hash[base] + hash[base * 10]; + break; + default: + if (r >= 5) + res.append(1, hash[base * 5]); + res.append(r % 5, hash[base]); + } + num -= r * base; + } + } + return res; + } +}; diff --git a/cpp/120.Triangle/dp.cpp b/cpp/120.Triangle/dp.cpp deleted file mode 100644 index bdea1c9..0000000 --- a/cpp/120.Triangle/dp.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int minimumTotal(vector>& triangle) { - int row=triangle.size(); - if(row==0) - return 0; - vector>dp; - dp.push_back( triangle[0]); - for(int i=0;i(triangle[i+1].size(),0x7fffffff)); - for(int j=0;j=0&&j+x>& triangle) { + int row = triangle.size(); + vector> dp{triangle[0]}; + for (int i = 0; i < row - 1; ++i) { + dp.push_back(vector(triangle[i + 1].size(), 0x7fffffff)); + for (int j = 0; j < triangle[i].size(); ++j) { + for (int x = 0; x <= 1; ++x) + if (j + x >= 0 && j + x < triangle[i + 1].size()) + dp[i + 1][j + x] = + min(dp[i + 1][j + x], + triangle[i + 1][j + x] + dp[i][j]); + } + } + return *min_element(dp.back().begin(), dp.back().end()); + } +}; diff --git a/cpp/121.BestTimeToBuyAndSellStock/onepass-9ms.cpp b/cpp/121.BestTimeToBuyAndSellStock/onepass-9ms.cpp deleted file mode 100644 index 470a983..0000000 --- a/cpp/121.BestTimeToBuyAndSellStock/onepass-9ms.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int maxProfit(vector& prices) { - if(prices.size()==0)return 0; - int min=prices[0],len=prices.size(),profit=0; - for(int i=1;iprofit?prices[i]-min:profit; - return profit; - } -}; diff --git a/cpp/121.cpp b/cpp/121.cpp new file mode 100644 index 0000000..21a49f0 --- /dev/null +++ b/cpp/121.cpp @@ -0,0 +1,16 @@ +// onepass +class Solution { + public: + int maxProfit(vector& prices) { + if (prices.size() == 0) + return 0; + int minPrice = prices[0], profit = 0; + for (auto price : prices) { + if (price < minPrice) + minPrice = price; + else + profit = max(price - minPrice, profit); + } + return profit; + } +}; \ No newline at end of file diff --git a/cpp/122.BestTimeToBuyAndSellStockII/onepass.cpp b/cpp/122.BestTimeToBuyAndSellStockII/onepass.cpp deleted file mode 100644 index 0b037d6..0000000 --- a/cpp/122.BestTimeToBuyAndSellStockII/onepass.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int maxProfit(vector& prices) { - int profit=0,n=prices.size(); - if(n==0)return 0; - int buy=prices[0]; - for(int i=0;i& prices) { + int profit = 0, n = prices.size(); + for (int i = 0; i < n - 1; ++i) + if (prices[i] < prices[i + 1]) + profit += prices[i + 1] - prices[i]; + return profit; + } +}; diff --git a/cpp/124.BinaryTreeMaximumPathSum/recursion.cpp b/cpp/124.BinaryTreeMaximumPathSum/recursion.cpp deleted file mode 100644 index 5ba1637..0000000 --- a/cpp/124.BinaryTreeMaximumPathSum/recursion.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int maxSum=INT_MIN; -public: - int maxPathSum(TreeNode* root) { - maxPath(root); - return maxSum; - } - int maxPath(TreeNode* root) { - if(root==NULL) - return 0; - int left=maxPath(root->left),right=maxPath(root->right); - maxSum=max(maxSum,root->val+(left>0?left:0)+(right>0?right:0)); - int sub=max(left,right); - return max(sub+root->val,root->val); - } -}; diff --git a/cpp/124.cpp b/cpp/124.cpp new file mode 100644 index 0000000..45fdea3 --- /dev/null +++ b/cpp/124.cpp @@ -0,0 +1,28 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * }; + */ +class Solution { + int maxSum = INT_MIN; + int maxPath(TreeNode* root) { + if (root == nullptr) + return 0; + int left = maxPath(root->left), right = maxPath(root->right); + maxSum = max(maxSum, root->val + (left > 0 ? left : 0) + + (right > 0 ? right : 0)); + int sub = max(left, right); + return max(sub + root->val, root->val); + } + + public: + int maxPathSum(TreeNode* root) { + maxPath(root); + return maxSum; + } +}; diff --git a/cpp/125.ValidPalindrome/onepass-12ms.cpp b/cpp/125.ValidPalindrome/onepass-12ms.cpp deleted file mode 100644 index 509679e..0000000 --- a/cpp/125.ValidPalindrome/onepass-12ms.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { -public: - bool isPalindrome(string s) { - int i=0,j=s.size()-1; - while(i=i && !isalphanumeric(s[j]))--j; - if(i>=j)return 1; - if( (s[i]==s[j]||s[i]-'a'+'A'==s[j]||s[i]-'A'+'a'==s[j] )&& isalphanumeric(s[i])==isalphanumeric(s[j]) ){ - ++i;--j; - } - else - return 0; - } - return 1; - } - int isalphanumeric(char ch){ - if(ch>='0'&&ch<='9') - return 1; - if( (ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z') ) - return 2; - return 0; - } -}; diff --git a/cpp/125.cpp b/cpp/125.cpp new file mode 100644 index 0000000..a5e91e9 --- /dev/null +++ b/cpp/125.cpp @@ -0,0 +1,45 @@ +// onepass-12ms.cpp +class Solution { + public: + bool isPalindrome(string s) { + int i = 0, j = s.size() - 1; + while (i < j) { + while (i < j && !isalphanumeric(s[i])) + ++i; + while (j >= i && !isalphanumeric(s[j])) + --j; + if (i >= j) + return 1; + if ((s[i] == s[j] || s[i] - 'a' + 'A' == s[j] || + s[i] - 'A' + 'a' == s[j]) && + isalphanumeric(s[i]) == isalphanumeric(s[j])) { + ++i; + --j; + } else + return 0; + } + return 1; + } + int isalphanumeric(char ch) { + if (ch >= '0' && ch <= '9') + return 1; + if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) + return 2; + return 0; + } +}; +class Solution2 { + public: + bool isPalindrome(string s) { + string filtered; + copy_if(s.begin(), s.end(), back_inserter(filtered), [](char c) { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || + c >= '0' && c <= '9'; + }); + transform( + filtered.begin(), filtered.end(), filtered.begin(), + [](char c) { return c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c; }); + return equal(filtered.begin(), filtered.begin() + filtered.size() / 2, + filtered.rbegin()); + } +}; \ No newline at end of file diff --git a/cpp/127.WordLadder/bfs.cpp b/cpp/127.WordLadder/bfs.cpp deleted file mode 100644 index 80812e7..0000000 --- a/cpp/127.WordLadder/bfs.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -public: - int ladderLength(string beginWord, string endWord, vector& wordList) { - unordered_mapmap; - int len=1,n=beginWord.size(); - queueqe; - qe.push(beginWord); - unordered_setwordlist(wordList.begin(),wordList.end()); - string temp; - while(!qe.empty()){ - int times=qe.size(); - for(int k=0;k &wordList) { + unordered_map map; + int len = 1, n = beginWord.size(); + queue qe; + qe.push(beginWord); + unordered_set wordlist(wordList.begin(), wordList.end()); + string temp; + while (!qe.empty()) { + int times = qe.size(); + for (int k = 0; k < times; ++k) { + temp = qe.front(); + if (temp == endWord) + return len; + qe.pop(); + for (int i = 0; i < n; ++i) { + char ch = temp[i]; + for (int j = 0; j < 26; ++j) { + temp[i] = 'a' + j; + if (wordlist.find(temp) != wordlist.end()) { + qe.push(temp); + wordlist.erase(temp); + } + } + temp[i] = ch; + } + } + len++; + } + return 0; + } +}; diff --git a/cpp/128.LongestConsecutiveSequence/hashmap.cpp b/cpp/128.LongestConsecutiveSequence/hashmap.cpp deleted file mode 100644 index fd775f6..0000000 --- a/cpp/128.LongestConsecutiveSequence/hashmap.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - int longestConsecutive(vector& nums) { - unordered_maphashmap; - int maxLen=0; - for(auto num:nums){ - if(hashmap.find(num)!=hashmap.end()) - continue; - auto left=hashmap.find(num-1); - auto right=hashmap.find(num+1); - int l=left==hashmap.end()?0:left->second; - int r=right==hashmap.end()?0:right->second; - int len=1+l+r; - hashmap[num]=len; - hashmap[num-l]=len; - hashmap[num+r]=len; - maxLen=max(maxLen,len); - } - return maxLen; - } -}; diff --git a/cpp/128.cpp b/cpp/128.cpp new file mode 100644 index 0000000..2f220e5 --- /dev/null +++ b/cpp/128.cpp @@ -0,0 +1,20 @@ +// hashmap.cpp +class Solution { + public: + int longestConsecutive(vector& nums) { + unordered_map hashmap; + int maxLen = 0; + for (auto num : nums) { + if (hashmap.find(num) != hashmap.end()) + continue; + auto left = hashmap.find(num - 1); + auto right = hashmap.find(num + 1); + int l = left == hashmap.end() ? 0 : left->second; + int r = right == hashmap.end() ? 0 : right->second; + int len = 1 + l + r; + hashmap[num] = hashmap[num - l] = hashmap[num + r] = len; + maxLen = max(maxLen, len); + } + return maxLen; + } +}; diff --git a/cpp/129.SumRootToLeafNumbers/recursion-3ms.cpp b/cpp/129.SumRootToLeafNumbers/recursion-3ms.cpp deleted file mode 100644 index 10f6498..0000000 --- a/cpp/129.SumRootToLeafNumbers/recursion-3ms.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - int sumNumbers(TreeNode* root) { - int sum=0; - calc(root,0,sum); - return sum; - } - void calc(TreeNode *root,int value,int &sum){ - if(root==NULL) - return; - value=value*10+root->val; - if(root->left==NULL && root->right==NULL){ - sum+=value; - return; - } - calc(root->left,value,sum); - calc(root->right,value,sum); - - } -}; \ No newline at end of file diff --git a/cpp/129.cpp b/cpp/129.cpp new file mode 100644 index 0000000..16a86fd --- /dev/null +++ b/cpp/129.cpp @@ -0,0 +1,30 @@ +// recursion-3ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * }; + */ +class Solution { + void calc(TreeNode* root, int value, int& sum) { + if (root == nullptr) + return; + value = value * 10 + root->val; + if (root->left == nullptr && root->right == nullptr) { + sum += value; + return; + } + calc(root->left, value, sum); + calc(root->right, value, sum); + } + + public: + int sumNumbers(TreeNode* root) { + int sum = 0; + calc(root, 0, sum); + return sum; + } +}; \ No newline at end of file diff --git a/cpp/13.RomantoInteger/notExactlyRight.cpp b/cpp/13.RomantoInteger/notExactlyRight.cpp deleted file mode 100644 index c7f4fe6..0000000 --- a/cpp/13.RomantoInteger/notExactlyRight.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution {// wrong at "IIIVM" -public: - int romanToInt(string s) { - vector st; - unordered_maphash = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}}; - for(auto c:s){ - auto n=hash[c]; - if(st.empty()||st.back()>=n){ - st.push_back(n); - } - else{ - int res=0; - while(st.size()&&st.back() hash; + +public: + int romanToInt(string s) { + vector st; + for (auto c : s) { + auto n = hash[c]; + if (st.empty() || st.back() >= n) { + st.push_back(n); + } else { + int res = 0; + while (st.size() && st.back() < n) { + res += st.back(); + st.pop_back(); + } + n -= res; + st.push_back(n); + } + } + return accumulate(st.begin(), st.end(), 0); + } +}; + +unordered_map Solution::hash = {{'I', 1}, {'V', 5}, {'X', 10}, + {'L', 50}, {'C', 100}, {'D', 500}, + {'M', 1000}}; \ No newline at end of file diff --git a/cpp/130.SurroundedRegions/dfs.cpp b/cpp/130.SurroundedRegions/dfs.cpp deleted file mode 100644 index 5a52d4a..0000000 --- a/cpp/130.SurroundedRegions/dfs.cpp +++ /dev/null @@ -1,55 +0,0 @@ -class Solution { - int row,col,row2,col2; -public: - void solve(vector>& board) { - row=board.size(),row2=row-1; - if(row==0)return; - col=board[0].size(),col2=col-1; - for(int i=0;i>&board,char origin,char target,int i,int j){ - stack>st; - st.push(make_pair(i,j)); - while(!st.empty()){ - i=st.top().first; - j=st.top().second; - st.pop(); - if(i<0||j<0||i>=row||j>=col||board[i][j]!=origin) - continue; - board[i][j]=target; - st.push(make_pair(i+1,j)); - st.push(make_pair(i-1,j)); - st.push(make_pair(i,j+1)); - st.push(make_pair(i,j-1)); - } - } -}; diff --git a/cpp/130.cpp b/cpp/130.cpp new file mode 100644 index 0000000..50a33d7 --- /dev/null +++ b/cpp/130.cpp @@ -0,0 +1,57 @@ +// bfs.cpp +class Solution { + int row, col, row2, col2; + void bfs(vector>& board, char origin, char target, int i, + int j) { + vector> st = {{i, j}}; + while (!st.empty()) { + auto [i, j] = st.back(); + st.pop_back(); + if (i < 0 || j < 0 || i >= row || j >= col || board[i][j] != origin) + continue; + board[i][j] = target; + st.push_back({i + 1, j}); + st.push_back({i - 1, j}); + st.push_back({i, j + 1}); + st.push_back({i, j - 1}); + } + } + + public: + void solve(vector>& board) { + row = board.size(), row2 = row - 1; + if (row == 0) + return; + col = board[0].size(), col2 = col - 1; + for (int i = 0; i < col; ++i) { + if (board[0][i] == 'O') + bfs(board, 'O', 'a', 0, i); + if (board[row - 1][i] == 'O') + bfs(board, 'O', 'a', row - 1, i); + } + for (int i = 1; i < row - 1; ++i) { + if (board[i][0] == 'O') + bfs(board, 'O', 'a', i, 0); + if (board[i][col - 1] == 'O') + bfs(board, 'O', 'a', i, col - 1); + } + + for (int i = 1; i < row2; ++i) + for (int j = 1; j < col2; ++j) + if (board[i][j] == 'O') + board[i][j] = 'X'; + + for (int i = 0; i < col; ++i) { + if (board[0][i] == 'a') + bfs(board, 'a', 'O', 0, i); + if (board[row - 1][i] == 'a') + bfs(board, 'a', 'O', row - 1, i); + } + for (int i = 1; i < row - 1; ++i) { + if (board[i][0] == 'a') + bfs(board, 'a', 'O', i, 0); + if (board[i][col - 1] == 'a') + bfs(board, 'a', 'O', i, col - 1); + } + } +}; diff --git a/cpp/131.PalindromePartitioning/bad-dfs.cpp b/cpp/131.PalindromePartitioning/bad-dfs.cpp deleted file mode 100644 index 3b6535a..0000000 --- a/cpp/131.PalindromePartitioning/bad-dfs.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { -public: - vector> partition(string s) { - vector>res; - vectorr; - dfs(res,r,"",s); - return res; - } - void dfs(vector>&res,vector&r,string pre,string last){ - if(pre!=""&&isPalindrome(pre)){ - r.push_back(pre); - dfs(res,r,"",last); - r.pop_back(); - } - if(last==""){ - if(pre=="") - res.push_back(r); - return; - } - dfs(res,r,pre+last[0],last.substr(1)); - } - bool isPalindrome(string &s){ - int i=0,j=s.size()-1; - while(i> partition(string s) { - vector > ret; - int n=s.size(); - if(n==0) return ret; - vector path; - vector>dp(n,vector(n,0)); - for(int i=0;i& path, vector >& ret,vector>&dp) { - if(index == s.size()) { - ret.push_back(path); - return; - } - for(int i = index; i < s.size(); ++i) - if(dp[index][i]) { - path.push_back(s.substr(index, i - index + 1)); - dfs(i+1, s, path, ret,dp); - path.pop_back(); - } - } -}; diff --git a/cpp/131.PalindromePartitioning/smart-dfs.cpp b/cpp/131.PalindromePartitioning/smart-dfs.cpp deleted file mode 100644 index 0f4a4dc..0000000 --- a/cpp/131.PalindromePartitioning/smart-dfs.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution { -public: - vector> partition(string s) { - vector > ret; - if(s.empty()) return ret; - vector path; - dfs(0, s, path, ret); - return ret; - } - void dfs(int index, string& s, vector& path, vector >& ret) { - if(index == s.size()) { - ret.push_back(path); - return; - } - for(int i = index; i < s.size(); ++i) - if(isPalindrome(s, index, i)) { - path.push_back(s.substr(index, i - index + 1)); - dfs(i+1, s, path, ret); - path.pop_back(); - } - } - bool isPalindrome(const string& s, int start, int end) { - while(start < end) - if(s[start++] != s[end--]) - return false; - return true; - } -}; diff --git a/cpp/131.cpp b/cpp/131.cpp new file mode 100644 index 0000000..c022de2 --- /dev/null +++ b/cpp/131.cpp @@ -0,0 +1,63 @@ +// dp-dfs.cpp +class Solution { + void dfs(int index, string& s, vector& path, + vector>& ret, vector>& dp) { + if (index == s.size()) { + ret.push_back(path); + return; + } + for (int i = index; i < s.size(); ++i) + if (dp[index][i]) { + path.push_back(s.substr(index, i - index + 1)); + dfs(i + 1, s, path, ret, dp); + path.pop_back(); + } + } + + public: + vector> partition(string s) { + int n = s.size(); + if (n == 0) + return {}; + vector> ret; + vector path; + vector> dp(n, vector(n, 0)); + for (int i = 0; i < n; ++i) + for (int j = 0; j <= i; ++j) + dp[j][i] = s[i] == s[j] && (i - j <= 2 || dp[j + 1][i - 1]); + dfs(0, s, path, ret, dp); + return ret; + } +}; +// dfs.cpp +class Solution2 { + void dfs(int index, string& s, vector& path, + vector>& ret) { + if (index == s.size()) { + ret.push_back(path); + return; + } + for (int i = index; i < s.size(); ++i) + if (isPalindrome(s, index, i)) { + path.push_back(s.substr(index, i - index + 1)); + dfs(i + 1, s, path, ret); + path.pop_back(); + } + } + bool isPalindrome(const string& s, int start, int end) { + while (start < end) + if (s[start++] != s[end--]) + return false; + return true; + } + + public: + vector> partition(string s) { + vector> ret; + if (s.empty()) + return ret; + vector path; + dfs(0, s, path, ret); + return ret; + } +}; diff --git a/cpp/132.cpp b/cpp/132.cpp new file mode 100644 index 0000000..b29d06b --- /dev/null +++ b/cpp/132.cpp @@ -0,0 +1,25 @@ +class Solution { + public: + int minCut(string s) { + int n = s.size(); + if (n == 0) + return 0; + vector> dp(n, vector(n, 0)); + for (int i = 0; i < n; ++i) + for (int j = 0; j <= i; ++j) + dp[j][i] = s[i] == s[j] && (i - j <= 2 || dp[j + 1][i - 1]); + if (dp[0][n - 1]) + return 0; + vector dp2(n, INT_MAX); + for (int i = 0; i < n; ++i) { + if (dp[0][i]) + dp2[i] = 0; + else + for (int j = 1; j <= i; ++j) { + if (dp[j][i]) + dp2[i] = min(dp2[i], dp2[j - 1] + 1); + } + } + return dp2[n - 1]; + } +}; \ No newline at end of file diff --git a/cpp/133.CloneGraph.cpp b/cpp/133.CloneGraph.cpp deleted file mode 100644 index c8e5e1b..0000000 --- a/cpp/133.CloneGraph.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - vector neighbors; - - Node() {} - - Node(int _val, vector _neighbors) { - val = _val; - neighbors = _neighbors; - } -}; -*/ -class Solution { -//Runtime: 24 ms, faster than 92.17% of C++ online submissions for Clone Graph. -//Memory Usage: 16.8 MB, less than 12.63% of C++ online submissions for Clone Graph. - -public: - Node* cloneGraph(Node* node) { - unordered_mapcopies; - function dfs=[&copies,&dfs](Node *node)->Node*{ - if (!node) - return nullptr; - if (copies.find(node) == copies.end()) { - copies[node] = new Node(node -> val, {}); - for (Node* neighbor : node -> neighbors) { - copies[node] -> neighbors.push_back(dfs(neighbor)); - } - } - return copies[node]; - }; - return dfs(node); - } -}; \ No newline at end of file diff --git a/cpp/133.cpp b/cpp/133.cpp new file mode 100644 index 0000000..1c700ca --- /dev/null +++ b/cpp/133.cpp @@ -0,0 +1,37 @@ +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; + +class Solution { + public: + Node* cloneGraph(Node* node) { + unordered_map copies; + function dfs = [&copies, &dfs](Node* node) -> Node* { + if (!node) + return nullptr; + if (auto it = copies.find(node); it != copies.end()) { + return it->second; + } + auto p = copies[node] = new Node(node->val, {}); + for (auto neighbor : node->neighbors) { + p->neighbors.push_back(dfs(neighbor)); + } + return p; + }; + return dfs(node); + } +}; \ No newline at end of file diff --git a/cpp/134.GasStation/singleScan.cpp b/cpp/134.GasStation/singleScan.cpp deleted file mode 100644 index e26bae6..0000000 --- a/cpp/134.GasStation/singleScan.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int canCompleteCircuit(vector& gas, vector& cost) { - int total=0,start=0,end=0,visited=0,n=gas.size(); - while(visited=0;visited++){ - total+=gas[end]-cost[end]; - end=(end+1)%n; - } - for(;visited=0?start:-1; - } -}; diff --git a/cpp/134.cpp b/cpp/134.cpp new file mode 100644 index 0000000..618441d --- /dev/null +++ b/cpp/134.cpp @@ -0,0 +1,18 @@ +// singleScan.cpp +class Solution { + public: + int canCompleteCircuit(vector& gas, vector& cost) { + int total = 0, start = 0, end = 0, visited = 0, n = gas.size(); + while (visited < n) { + for (; visited < n && total >= 0; visited++) { + total += gas[end] - cost[end]; + end = (end + 1) % n; + } + for (; visited < n && total < 0; visited++) { + start = start - 1 < 0 ? start - 1 + n : start - 1; + total += gas[start] - cost[start]; + } + } + return total >= 0 ? start : -1; + } +}; diff --git a/cpp/136.SingleNumber/xor-13ms.cpp b/cpp/136.SingleNumber/xor-13ms.cpp deleted file mode 100644 index 6ea678f..0000000 --- a/cpp/136.SingleNumber/xor-13ms.cpp +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { -public: - int singleNumber(vector& nums) { - int result=0; - for(auto n:nums) - result^=n; - return result; - } -}; diff --git a/cpp/136.cpp b/cpp/136.cpp new file mode 100644 index 0000000..f7425bb --- /dev/null +++ b/cpp/136.cpp @@ -0,0 +1,10 @@ +// xor-13ms.cpp +class Solution { + public: + int singleNumber(vector& nums) { + int result = 0; + for (auto n : nums) + result ^= n; + return result; + } +}; diff --git a/cpp/137.SingleNumberII/O32n.cpp b/cpp/137.SingleNumberII/O32n.cpp deleted file mode 100644 index e9b5901..0000000 --- a/cpp/137.SingleNumberII/O32n.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int singleNumber(vector& nums) { - int res=0,n=nums.size(); - for(int i=0;i<32;++i){ - int count=0,mask=1<& nums) { + int res = 0, n = nums.size(); + for (int i = 0; i < 32; ++i) { + int count = 0, mask = 1 << i; + for (int j = 0; j < n; ++j) + if (nums[j] & mask) + ++count; + if (count % 3 != 0) + res |= mask; + } + return res; + } +}; diff --git a/cpp/138.CopyListWithRandomPointer/noExtraSpace.cpp b/cpp/138.CopyListWithRandomPointer/noExtraSpace.cpp deleted file mode 100644 index d1adeef..0000000 --- a/cpp/138.CopyListWithRandomPointer/noExtraSpace.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for singly-linked list with a random pointer. - * struct RandomListNode { - * int label; - * RandomListNode *next, *random; - * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} - * }; - */ -class Solution { -public: - RandomListNode *copyRandomList(RandomListNode *head) { - RandomListNode *tmp_head = new RandomListNode(-1); - for(auto *cur=head; cur; cur=cur->next->next){ - RandomListNode *copy = new RandomListNode(cur->label); - copy->next = cur->next; - cur->next = copy; - } - for(auto *cur=head; cur; cur=cur->next->next){ - if(cur->random) - cur->next->random = cur->random->next; - } - for(auto *cur=head, *copy=tmp_head; cur; cur=cur->next, copy = copy->next){ - copy->next = cur->next; - cur->next = cur->next->next; - } - return tmp_head->next; - } -}; diff --git a/cpp/138.CopyListWithRandomPointer/scanTWice-60ms.cpp b/cpp/138.CopyListWithRandomPointer/scanTWice-60ms.cpp deleted file mode 100644 index 439e28e..0000000 --- a/cpp/138.CopyListWithRandomPointer/scanTWice-60ms.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for singly-linked list with a random pointer. - * struct RandomListNode { - * int label; - * RandomListNode *next, *random; - * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} - * }; - */ -class Solution { -public: - RandomListNode *copyRandomList(RandomListNode *head) { - unordered_maphash; - vectorarr; - int count = 0; - for(auto p=head;p!=nullptr;p=p->next){ - auto n = new RandomListNode(p->label); - if(count) - arr.back()->next = n; - arr.push_back(n); - hash[p] = count++; - } - count = 0; - for(auto p=head;p!=nullptr;p=p->next,++count){ - if(p->random){ - auto index = hash[p->random]; - arr[count]->random = arr[index]; - } - } - return arr.size()?arr[0]:nullptr; - } -}; diff --git a/cpp/138.cpp b/cpp/138.cpp new file mode 100644 index 0000000..d596ce0 --- /dev/null +++ b/cpp/138.cpp @@ -0,0 +1,58 @@ +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = nullptr; + random = nullptr; + } +}; +// noExtraSpace.cpp +class Solution { + public: + Node* copyRandomList(Node* head) { + auto tmp_head = new Node(-1); + for (auto cur = head; cur; cur = cur->next->next) { + auto copy = new Node(cur->val); + copy->next = cur->next; + cur->next = copy; + } + for (auto cur = head; cur; cur = cur->next->next) { + if (cur->random) + cur->next->random = cur->random->next; + } + for (auto cur = head, copy = tmp_head; cur; + cur = cur->next, copy = copy->next) { + copy->next = cur->next; + cur->next = cur->next->next; + } + return tmp_head->next; + } +}; +// scanTWice-60ms.cpp +class Solution2 { + public: + RandomListNode* copyRandomList(RandomListNode* head) { + unordered_map hash; + vector arr; + int count = 0; + for (auto p = head; p != nullptr; p = p->next) { + auto n = new RandomListNode(p->label); + if (count) + arr.back()->next = n; + arr.push_back(n); + hash[p] = count++; + } + count = 0; + for (auto p = head; p != nullptr; p = p->next, ++count) { + if (p->random) { + auto index = hash[p->random]; + arr[count]->random = arr[index]; + } + } + return arr.size() ? arr[0] : nullptr; + } +}; diff --git a/cpp/139.WordBreak/dp.cpp b/cpp/139.WordBreak/dp.cpp deleted file mode 100644 index 52442e6..0000000 --- a/cpp/139.WordBreak/dp.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - bool wordBreak(string s, vector& wordDict) { - if(wordDict.size()==0)return false; - unordered_sethashset(wordDict.begin(),wordDict.end()); - vectordp(s.size()+1,0); - dp[0]=1; - for(int i=1;i<=s.size();++i) - for(int j=i-1;j>=0;--j) - if(dp[j]&&hashset.find( s.substr(j,i-j) )!=hashset.end()){ - dp[i]=true; - break; - } - return dp[s.size()]; - } -}; diff --git a/cpp/139.WordBreak/trie+dfs-TLE.cpp b/cpp/139.WordBreak/trie+dfs-TLE.cpp deleted file mode 100644 index d877548..0000000 --- a/cpp/139.WordBreak/trie+dfs-TLE.cpp +++ /dev/null @@ -1,49 +0,0 @@ -class Solution { - struct trie{ - trie():isWord(false){ - memset(this,0,sizeof(trie)); - } - bool isWord; - trie *children[26]; - }root; - void insert(string &word) { - trie *p=&root; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - p->children[offset]=new trie(); - p=p->children[offset]; - } - p->isWord=true; - } - bool search(string &word,int start) { - trie *p=&root; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - return false; - p=p->children[offset]; - } - return p->isWord; - } - bool dfs(string &s,int index){ - if(index==s.size()) - return true; - trie *p=&root; - for(;indexchildren[offset]==nullptr ) - return false; - p=p->children[offset]; - if(p->isWord&&dfs(s,index+1)) - return true; - } - return false; - } -public: - bool wordBreak(string s, vector& wordDict) { - for(string &str:wordDict) - insert(str); - return dfs(s,0); - } -}; diff --git a/cpp/139.cpp b/cpp/139.cpp new file mode 100644 index 0000000..dd56fdc --- /dev/null +++ b/cpp/139.cpp @@ -0,0 +1,68 @@ +// dp.cpp 0ms +class Solution { + public: + bool wordBreak(string s, vector& wordDict) { + if (wordDict.size() == 0) + return false; + string_view sv = s; + unordered_set hashset(wordDict.begin(), wordDict.end()); + vector dp(s.size() + 1, 0); + dp[0] = 1; + for (int i = 1; i <= s.size(); ++i) + for (int j = i - 1; j >= 0; --j) + if (dp[j] && + hashset.find(sv.substr(j, i - j)) != hashset.end()) { + dp[i] = true; + break; + } + return dp.back(); + } +}; +// trie+dp.cpp 3ms +class Solution2 { + struct trie { + trie() : isWord(false) {} + bool isWord; + trie* children[26] = {}; + } root; + void insert(string& word) { + trie* p = &root; + for (auto ch : word) { + int offset = ch - 'a'; + if (p->children[offset] == nullptr) + p->children[offset] = new trie(); + p = p->children[offset]; + } + p->isWord = true; + } + bool search(string_view word) { + trie* p = &root; + for (auto ch : word) { + int offset = ch - 'a'; + if (p->children[offset] == nullptr) + return false; + p = p->children[offset]; + } + return p->isWord; + } + bool dp(string_view s) { + vector dp(s.size() + 1, false); + dp[0] = true; + for (int i = 1; i <= s.size(); ++i) { + for (int j = i - 1; j >= 0; --j) { + if (dp[j] && search(s.substr(j, i - j))) { + dp[i] = true; + break; + } + } + } + return dp.back(); + } + + public: + bool wordBreak(string s, vector& wordDict) { + for (string& str : wordDict) + insert(str); + return dp(s); + } +}; diff --git a/cpp/14.LongestCommonPrefix.cpp b/cpp/14.LongestCommonPrefix.cpp deleted file mode 100644 index 27af9c6..0000000 --- a/cpp/14.LongestCommonPrefix.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { // 4ms -public: - string longestCommonPrefix(vector& strs) { - if(strs.size()==0||strs[0].size()==0) - return ""; - string pre=""; - for(int j=0;j& strs) { + if (strs.size() == 1) + return strs[0]; + string ret; + for (int charN = 0; charN < strs[0].size(); ++charN) { + for (int wordN = 0; wordN < strs.size(); ++wordN) { + if (strs[wordN][charN] != strs[0][charN]) { + return ret; + } + } + ret += strs[0][charN]; + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/140.cpp b/cpp/140.cpp new file mode 100644 index 0000000..32493f7 --- /dev/null +++ b/cpp/140.cpp @@ -0,0 +1,23 @@ +class Solution { + public: + vector wordBreak(string s, vector& wordDict) { + string_view sv = s; + unordered_set hashset(wordDict.begin(), wordDict.end()); + vector dp(s.size() + 1, 0); + vector> ret(s.size() + 1); + dp[0] = 1; + for (int i = 1; i <= s.size(); ++i) + for (int j = i - 1; j >= 0; --j) + if (dp[j] && + hashset.find(sv.substr(j, i - j)) != hashset.end()) { + dp[i] = true; + if (ret[j].empty()) + ret[i].push_back(string(sv.substr(j, i - j))); + else + for (auto& str : ret[j]) + ret[i].push_back(str + " " + + string(sv.substr(j, i - j))); + } + return ret.back(); + } +}; \ No newline at end of file diff --git a/cpp/141.LinkedListCycle/iteration.cpp b/cpp/141.LinkedListCycle/iteration.cpp deleted file mode 100644 index 2dafaa3..0000000 --- a/cpp/141.LinkedListCycle/iteration.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - bool hasCycle(ListNode *head) { - ListNode *p1=head,*p2=head; - while(p1!=NULL&&p2!=NULL){ - p1=p1->next; - p2=p2->next; - if(p2!=NULL) - p2=p2->next; - if(p1==p2&&p1!=NULL)return 1; - } - return 0; - } -}; diff --git a/cpp/141.cpp b/cpp/141.cpp new file mode 100644 index 0000000..48c6744 --- /dev/null +++ b/cpp/141.cpp @@ -0,0 +1,24 @@ +// iteration.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(nullptr) {} + * }; + */ +class Solution { + public: + bool hasCycle(ListNode* head) { + ListNode *p1 = head, *p2 = head; + while (p1 != nullptr && p2 != nullptr) { + p1 = p1->next; + p2 = p2->next; + if (p2 != nullptr) + p2 = p2->next; + if (p1 == p2 && p1 != nullptr) + return 1; + } + return 0; + } +}; diff --git a/cpp/142.LinkedListCycleII/towpointer.cpp b/cpp/142.LinkedListCycleII/towpointer.cpp deleted file mode 100644 index cdcc1a4..0000000 --- a/cpp/142.LinkedListCycleII/towpointer.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode *detectCycle(ListNode *head) { - ListNode *p1=hasCycle(head),*p2=head; - if(p1==NULL)return NULL; - while(p1!=p2){ - p1=p1->next; - p2=p2->next; - } - return p1; - } - ListNode *hasCycle(ListNode *head){ - ListNode *fast=head,*slow=head; - while(fast&&fast->next){ - fast=fast->next->next; - slow=slow->next; - if(fast==slow)return fast; - } - return NULL; - } -}; diff --git a/cpp/142.cpp b/cpp/142.cpp new file mode 100644 index 0000000..0fca61d --- /dev/null +++ b/cpp/142.cpp @@ -0,0 +1,32 @@ +// towpointer.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(nullptr) {} + * }; + */ +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + ListNode *p1 = hasCycle(head), *p2 = head; + if (p1 == nullptr) + return nullptr; + while (p1 != p2) { + p1 = p1->next; + p2 = p2->next; + } + return p1; + } + ListNode *hasCycle(ListNode *head) { + ListNode *fast = head, *slow = head; + while (fast && fast->next) { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) + return fast; + } + return nullptr; + } +}; diff --git a/cpp/143.cpp b/cpp/143.cpp new file mode 100644 index 0000000..b87c7f2 --- /dev/null +++ b/cpp/143.cpp @@ -0,0 +1,30 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { + ListNode* reverse(ListNode* head) { + ListNode *pre = nullptr, *next = nullptr; + for (auto cur = head; cur != nullptr;) { + next = cur->next; + cur->next = pre; + pre = cur; + cur = next; + } + return pre; + } + + public: + void reorderList(ListNode* head) { + if (!head) + return; + head->next = reverse(head->next); + reorderList(head->next); + } +}; \ No newline at end of file diff --git a/cpp/144.BinaryTreePreorderTraversal/iteration.cpp b/cpp/144.BinaryTreePreorderTraversal/iteration.cpp deleted file mode 100644 index e37e6d3..0000000 --- a/cpp/144.BinaryTreePreorderTraversal/iteration.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector preorderTraversal(TreeNode* root) { - stackst; - vectorresult; - while(1){ - while(root!=NULL){ - result.push_back(root->val); - st.push(root); - root=root->left; - } - if(st.empty())break; - root=st.top(); - st.pop(); - root=root->right; - }while(!st.empty()); - return result; - } -}; diff --git a/cpp/144.cpp b/cpp/144.cpp new file mode 100644 index 0000000..c107faf --- /dev/null +++ b/cpp/144.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution2 { + public: + vector preorderTraversal(TreeNode* root) { + auto h = TreeNode(0, nullptr, root); + stack st({&h}); + vector result; + while (!st.empty()) { + root = st.top()->right; + st.pop(); + while (root) { + result.push_back(root->val); + st.push(root); + root = root->left; + } + } + return result; + } +}; diff --git a/cpp/145.cpp b/cpp/145.cpp new file mode 100644 index 0000000..80f2eaa --- /dev/null +++ b/cpp/145.cpp @@ -0,0 +1,35 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector postorderTraversal(TreeNode* root) { + if (!root) + return {}; + stack> st({{root, 0}}); + vector result; + while (!st.empty()) { + auto &[node, state] = st.top(); + if (state == 0){ + if (node->left) + st.push({node->left, 0}); + } else if (state == 1) { + if(node->right) + st.push({node->right, 0}); + } else { + result.push_back(node->val); + st.pop(); + } + state++; + } + return result; + } +}; \ No newline at end of file diff --git a/cpp/146.LRUCache/list_hashmap_82msBeat97%.cpp b/cpp/146.LRUCache/list_hashmap_82msBeat97%.cpp deleted file mode 100644 index b65458b..0000000 --- a/cpp/146.LRUCache/list_hashmap_82msBeat97%.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class LRUCache { - unsigned int capacity; - list< pair >timeList; - unordered_map>::iterator>hashmap;//key cache's key,value cache's value's pointer -public: - LRUCache(int capacity) { - this->capacity=capacity; - } - - int get(int key) { - auto it=hashmap.find(key); - if(it==hashmap.end()) - return -1; - timeList.push_back(make_pair(key,(*it->second).second)); - timeList.erase(it->second); - it->second=--timeList.end(); - return (*it->second).second; - } - - void put(int key, int value) { - auto it=hashmap.find(key); - if(it==hashmap.end()){ - timeList.push_back(make_pair(key,value)); - hashmap[key]=--timeList.end(); - if(hashmap.size()>capacity){ - hashmap.erase(timeList.begin()->first); - timeList.pop_front(); - } - } - else{ - timeList.erase(it->second); - timeList.push_back(make_pair(key,value)); - it->second=--timeList.end(); - } - } -}; - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache obj = new LRUCache(capacity); - * int param_1 = obj.get(key); - * obj.put(key,value); - */ diff --git a/cpp/146.LRUCache/map_hashmap_103ms.cpp b/cpp/146.LRUCache/map_hashmap_103ms.cpp deleted file mode 100644 index 28bcbb8..0000000 --- a/cpp/146.LRUCache/map_hashmap_103ms.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class LRUCache { - unsigned int capacity; - maptimemap;//key time,value cache's key - unordered_map>hashmap;//key cache's key,value cache's value and time - unsigned int call; -public: - LRUCache(int capacity) { - this->capacity=capacity; - call=0; - } - - int get(int key) { - auto it=hashmap.find(key); - if(it==hashmap.end()) - return -1; - timemap[call]=key; - int oldTime=hashmap[key].second; - hashmap[key].second=call++; - timemap.erase(oldTime); - return it->second.first; - } - - void put(int key, int value) { - auto it=hashmap.find(key); - if(it==hashmap.end()){ - timemap[call]=key; - hashmap[key]=make_pair(value,call++); - if(hashmap.size()>capacity){ - int erasedKey=timemap.begin()->second; - timemap.erase(timemap.begin()); - hashmap.erase(erasedKey); - } - } - else{ - timemap[call]=key; - int oldTime=hashmap[key].second; - hashmap[key]=make_pair(value,call++); - timemap.erase(oldTime); - } - } -}; - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache obj = new LRUCache(capacity); - * int param_1 = obj.get(key); - * obj.put(key,value); - */ diff --git a/cpp/146.cpp b/cpp/146.cpp new file mode 100644 index 0000000..d820793 --- /dev/null +++ b/cpp/146.cpp @@ -0,0 +1,92 @@ +// list_hashmap_82msBeat97%.cpp +class LRUCache { + unsigned int capacity; + list> timeList; + unordered_map>::iterator> + hashmap; // key cache's key,value cache's value's pointer +public: + LRUCache(int capacity) { this->capacity = capacity; } + + int get(int key) { + auto it = hashmap.find(key); + if (it == hashmap.end()) + return -1; + timeList.push_back(make_pair(key, (*it->second).second)); + timeList.erase(it->second); + it->second = --timeList.end(); + return (*it->second).second; + } + + void put(int key, int value) { + auto it = hashmap.find(key); + if (it == hashmap.end()) { + timeList.push_back(make_pair(key, value)); + hashmap[key] = --timeList.end(); + if (hashmap.size() > capacity) { + hashmap.erase(timeList.begin()->first); + timeList.pop_front(); + } + } else { + timeList.erase(it->second); + timeList.push_back(make_pair(key, value)); + it->second = --timeList.end(); + } + } +}; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); + */ +// map_hashmap_103ms.cpp +class LRUCache2 { + unsigned int capacity; + map timemap; // key time,value cache's key + unordered_map> + hashmap; // key cache's key,value cache's value and time + unsigned int call; + +public: + LRUCache2(int capacity) { + this->capacity = capacity; + call = 0; + } + + int get(int key) { + auto it = hashmap.find(key); + if (it == hashmap.end()) + return -1; + timemap[call] = key; + int oldTime = hashmap[key].second; + hashmap[key].second = call++; + timemap.erase(oldTime); + return it->second.first; + } + + void put(int key, int value) { + auto it = hashmap.find(key); + if (it == hashmap.end()) { + timemap[call] = key; + hashmap[key] = make_pair(value, call++); + if (hashmap.size() > capacity) { + int erasedKey = timemap.begin()->second; + timemap.erase(timemap.begin()); + hashmap.erase(erasedKey); + } + } else { + timemap[call] = key; + int oldTime = hashmap[key].second; + hashmap[key] = make_pair(value, call++); + timemap.erase(oldTime); + } + } +}; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.get(key); + * obj.put(key,value); + */ diff --git a/cpp/147.InsertionSortList/insertSort.cpp b/cpp/147.InsertionSortList/insertSort.cpp deleted file mode 100644 index 0a63830..0000000 --- a/cpp/147.InsertionSortList/insertSort.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* insertionSortList(ListNode* head) { - ListNode h(0); - while(head){ - ListNode*temp=&h; - while(temp->next&&temp->next->valval) - temp=temp->next; - ListNode*cur=head; - head=head->next; - cur->next=temp->next; - temp->next=cur; - } - return h.next; - } -}; diff --git a/cpp/147.cpp b/cpp/147.cpp new file mode 100644 index 0000000..892c493 --- /dev/null +++ b/cpp/147.cpp @@ -0,0 +1,25 @@ +// insertSort.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { + public: + ListNode* insertionSortList(ListNode* head) { + ListNode h(0); + while (head) { + ListNode* temp = &h; + while (temp->next && temp->next->val < head->val) + temp = temp->next; + ListNode* cur = head; + head = head->next; + cur->next = temp->next; + temp->next = cur; + } + return h.next; + } +}; diff --git a/cpp/148.SortList/mergeSort-52ms.cpp b/cpp/148.SortList/mergeSort-52ms.cpp deleted file mode 100644 index 5eb93f2..0000000 --- a/cpp/148.SortList/mergeSort-52ms.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - ListNode* separate(ListNode *h){ - auto l=h,r=h; - ListNode* pre=nullptr; - while(r&&r->next){ - r=r->next->next; - pre=l; - l=l->next; - } - if(pre) - pre->next=nullptr; - return l; - } -public: - ListNode* sortList(ListNode* head) { - if(!head||!head->next) - return head; - auto rp=separate(head); - rp=sortList(rp); - auto lp=sortList(head); - auto h=ListNode(0); - auto p=&h; - while(lp&&rp){ - auto &smallP=(lp->valval)?lp:rp; - p=p->next=smallP; - smallP=smallP->next; - } - for(auto cur=lp?lp:rp;cur;cur=cur->next) - p=p->next=cur; - return h.next; - } -}; diff --git a/cpp/148.SortList/quickSortO1Space-744ms.cpp b/cpp/148.SortList/quickSortO1Space-744ms.cpp deleted file mode 100644 index f459dbe..0000000 --- a/cpp/148.SortList/quickSortO1Space-744ms.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - pair helper(ListNode *head){ - if(!head) - return {nullptr,nullptr}; - ListNode lh(0),rh(0); - ListNode *l=&lh,*r=&rh,*h=head; - for(auto p=head->next;p;p=p->next) - if(h->valval) - r=r->next=p; - else - l=l->next=p; - r->next=l->next=nullptr; - auto lpart=helper(lh.next),rpart=helper(rh.next); - if(lh.next) - lpart.second->next=h; - h->next=rpart.first; - return {lh.next?lpart.first:h,rh.next?rpart.second:h}; - } -public: - ListNode* sortList(ListNode* head) { - return helper(head).first; - } -}; diff --git a/cpp/148.cpp b/cpp/148.cpp new file mode 100644 index 0000000..1ab5da3 --- /dev/null +++ b/cpp/148.cpp @@ -0,0 +1,73 @@ +// mergeSort-52ms.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { + ListNode *separate(ListNode *h) { + auto l = h, r = h; + ListNode *pre = nullptr; + while (r && r->next) { + r = r->next->next; + pre = l; + l = l->next; + } + if (pre) + pre->next = nullptr; + return l; + } + +public: + ListNode *sortList(ListNode *head) { + if (!head || !head->next) + return head; + auto rp = separate(head); + rp = sortList(rp); + auto lp = sortList(head); + auto h = ListNode(0); + auto p = &h; + while (lp && rp) { + auto &smallP = (lp->val < rp->val) ? lp : rp; + p = p->next = smallP; + smallP = smallP->next; + } + for (auto cur = lp ? lp : rp; cur; cur = cur->next) + p = p->next = cur; + return h.next; + } +}; +// quickSortO1Space-744ms.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution2 { + pair helper(ListNode *head) { + if (!head) + return {nullptr, nullptr}; + ListNode lh(0), rh(0); + ListNode *l = &lh, *r = &rh, *h = head; + for (auto p = head->next; p; p = p->next) + if (h->val < p->val) + r = r->next = p; + else + l = l->next = p; + r->next = l->next = nullptr; + auto lpart = helper(lh.next), rpart = helper(rh.next); + if (lh.next) + lpart.second->next = h; + h->next = rpart.first; + return {lh.next ? lpart.first : h, rh.next ? rpart.second : h}; + } + +public: + ListNode *sortList(ListNode *head) { return helper(head).first; } +}; diff --git a/cpp/149.MaxPointsOnALine.cpp b/cpp/149.MaxPointsOnALine.cpp deleted file mode 100644 index fc42691..0000000 --- a/cpp/149.MaxPointsOnALine.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -//Runtime: 12 ms Your runtime beats 92.52 % of cpp submissions -public: - int maxPoints(vector>& points) { - if(points.size()==0) - return 0; - auto getKB=[](int x1,int y1,int x2,int y2){ - int y=y1-y2,x=x1-x2; - int gcd=__gcd(y, x); - y=y/gcd,x=x/gcd; - return (((long long)*reinterpret_cast(&y))<<32ll)|(*reinterpret_cast(&x)); - }; - int ret=0; - for(int i=0;ihash; - int duplicate=0; - int vertical=0; - int res=0; - for(int j=0;j> &points) { + if (points.size() == 0) + return 0; + auto getKB = [](int x1, int y1, int x2, int y2) { + int y = y1 - y2, x = x1 - x2; + int gcd = __gcd(y, x); + y = y / gcd, x = x / gcd; + return (((long long)*reinterpret_cast(&y)) << 32ll) | + (*reinterpret_cast(&x)); + }; + int ret = 0; + for (int i = 0; i < points.size(); ++i) { + unordered_map hash; + int duplicate = 0; + int vertical = 0; + int res = 0; + for (int j = 0; j < points.size(); ++j) { + if (i == j) + continue; + else if (points[i][0] == points[j][0] and points[i][1] == points[j][1]) + ++duplicate; + else if (points[i][0] == points[j][0]) + res = max(res, ++vertical); + else + res = max(res, ++hash[getKB(points[i][0], points[i][1], points[j][0], + points[j][1])]); + } + ret = max(ret, res + 1 + duplicate); + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/15.3Sum.cpp b/cpp/15.3Sum.cpp deleted file mode 100644 index f11f254..0000000 --- a/cpp/15.3Sum.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { //sortAndDoublePointer 100ms -public: - vector> threeSum(vector& nums) { - sort(nums.begin(),nums.end()); - int n=nums.size(); - vector>result; - for(int i=0;i0&&nums[i]==nums[i-1]) - continue; - for(int low=i+1,high=n-1;low-nums[i]) - --high; - else - ++low; - } - } - return result; - } -}; \ No newline at end of file diff --git a/cpp/15.cpp b/cpp/15.cpp new file mode 100644 index 0000000..d247ed5 --- /dev/null +++ b/cpp/15.cpp @@ -0,0 +1,56 @@ +class Solution { // sortAndDoublePointer +public: + vector> threeSum(vector& nums) { + ranges::sort(nums); + int n = nums.size(); + vector> result; + for (int i = 0; i < n - 2; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + for (int low = i + 1, high = n - 1; low < high;) { + if (int sum = nums[low] + nums[high]; sum == -nums[i]) { + result.push_back({nums[i], nums[low], nums[high]}); + do { + ++low; + } while (low < high && nums[low - 1] == nums[low]); + do { + --high; + } while (low < high && nums[high + 1] == nums[high]); + } else if (sum > -nums[i]) + --high; + else + ++low; + } + } + return result; + } +}; +class Solution2 { // same logic, but use lambda +public: + vector> threeSum(vector& nums) { + sort(nums.begin(), nums.end()); + vector> res; + auto find = [&res](vector& nums, int k) { + int i = k + 1, j = nums.size() - 1; + while (i < j) { + if (nums[i] + nums[j] + nums[k] == 0) { + res.push_back({nums[k], nums[i], nums[j]}); + while (++i < j && nums[i - 1] == nums[i]) + ; + while (--j > i && nums[j + 1] == nums[j]) + ; + } else if (nums[i] + nums[j] + nums[k] > 0) { + --j; + } else { + ++i; + } + } + }; + for (int k = 0; k < nums.size();) { + find(nums, k); + while (++k < nums.size() && nums[k - 1] == nums[k]) + ; + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/150.EvaluateReversePolishNotation/stack-20ms.cpp b/cpp/150.EvaluateReversePolishNotation/stack-20ms.cpp deleted file mode 100644 index 15260c3..0000000 --- a/cpp/150.EvaluateReversePolishNotation/stack-20ms.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - int evalRPN(vector& tokens) { - stack nums; - for(auto &s:tokens){ - if(s[s.size()-1]>='0'&&s[s.size()-1]<='9') - nums.push(stoi(s)); - else{ - auto n2=nums.top(); - nums.pop(); - auto n1=nums.top(); - nums.pop(); - switch(s[0]){ - case '+':nums.push(n1+n2);break; - case '-':nums.push(n1-n2);break; - case '*':nums.push(n1*n2);break; - case '/':nums.push(n1/n2);break; - } - } - } - return nums.top(); - } -}; diff --git a/cpp/150.cpp b/cpp/150.cpp new file mode 100644 index 0000000..e29cf52 --- /dev/null +++ b/cpp/150.cpp @@ -0,0 +1,32 @@ +// stack-20ms.cpp +class Solution { + public: + int evalRPN(vector& tokens) { + stack nums; + for (auto& s : tokens) { + if (s[s.size() - 1] >= '0' && s[s.size() - 1] <= '9') + nums.push(stoi(s)); + else { + auto n2 = nums.top(); + nums.pop(); + auto n1 = nums.top(); + nums.pop(); + switch (s[0]) { + case '+': + nums.push(n1 + n2); + break; + case '-': + nums.push(n1 - n2); + break; + case '*': + nums.push(n1 * n2); + break; + case '/': + nums.push(n1 / n2); + break; + } + } + } + return nums.top(); + } +}; diff --git a/cpp/151.ReverseWordsInAString/1-9ms.cpp b/cpp/151.ReverseWordsInAString/1-9ms.cpp deleted file mode 100644 index 6321ae2..0000000 --- a/cpp/151.ReverseWordsInAString/1-9ms.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution { -public: - void reverseWords(string &s) { - int n = s.size() - 1, i, j, k, flag = 1; - for (i = 0; s[i] == ' '; ++i); - for (j = n; s[j] == ' '&&j>i; --j); - for (k = 0; i <= j; ++i) - if (s[i] == ' ') { - if (flag == 1) - s[k++] = s[i]; - flag = 0; - } - else { - s[k++] = s[i]; - flag = 1; - } - s.resize(k); - reverse(s, 0, k-1); - for (i = j = 0; i i; --j) + ; + for (k = 0; i <= j; ++i) + if (s[i] == ' ') { + if (flag == 1) + s[k++] = s[i]; + flag = 0; + } else { + s[k++] = s[i]; + flag = 1; + } + s.resize(k); + reverse(s, 0, k - 1); + for (i = j = 0; i < k && j < k; ++j) + if (s[j] == ' ') { + reverse(s, i, j - 1); + i = j + 1; + } + reverse(s, i, j - 1); + } + void reverse(string &s, int i, int j) { + while (i < j) { + char temp = s[i]; + s[i] = s[j]; + s[j] = temp; + ++i, --j; + } + } +}; diff --git a/cpp/152.MaximumProductSubarray/singleScan-8ms.cpp b/cpp/152.MaximumProductSubarray/singleScan-8ms.cpp deleted file mode 100644 index 4b1837e..0000000 --- a/cpp/152.MaximumProductSubarray/singleScan-8ms.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int maxProduct(vector& nums) { - vector maxPro(nums.size(),nums[0]),minPro(nums.size(),nums[0]); - auto ret=nums[0]; - for(auto i=1;i& nums) { - auto maxPro=nums[0],minPro=nums[0],ret=nums[0]; - for(auto i=1;i &nums) { + vector maxPro(nums.size(), nums[0]), minPro(nums.size(), nums[0]); + auto ret = nums[0]; + for (auto i = 1; i < nums.size(); ++i) { + maxPro[i] = + max({nums[i], maxPro[i - 1] * nums[i], minPro[i - 1] * nums[i]}); + minPro[i] = + min({nums[i], maxPro[i - 1] * nums[i], minPro[i - 1] * nums[i]}); + ret = max({ret, maxPro[i]}); + } + return ret; + } +}; +// singleScanConstantSpace-8ms.cpp +class Solution2 { +public: + int maxProduct(vector &nums) { + auto maxPro = nums[0], minPro = nums[0], ret = nums[0]; + for (auto i = 1; i < nums.size(); ++i) { + auto curMaxPro = max({nums[i], nums[i] * maxPro, nums[i] * minPro}); + auto curMinPro = min({nums[i], nums[i] * maxPro, nums[i] * minPro}); + ret = max({ret, curMaxPro}); + maxPro = curMaxPro; + minPro = curMinPro; + } + return ret; + } +}; diff --git a/cpp/153.FindMinimumInRotatedSortedArray.cpp b/cpp/153.FindMinimumInRotatedSortedArray.cpp deleted file mode 100644 index 5f82edb..0000000 --- a/cpp/153.FindMinimumInRotatedSortedArray.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 89.79% of C++ online submissions for Find Minimum in Rotated Sorted Array. -//Memory Usage: 8.8 MB, less than 29.27% of C++ online submissions for Find Minimum in Rotated Sorted Array. -public: - int findMin(vector& nums) { - int minVal=0x7fffffff; - function helper=[&](int low,int high){ - if(low>high) - return; - if(nums[low]<=nums[high]) - minVal=min(minVal,nums[low]); - else{ - int mid=(high+low)/2; - helper(low,mid-1); - helper(mid+1,high); - minVal=min(minVal,nums[mid]); - } - }; - helper(0,nums.size()-1); - return minVal; - } - -}; \ No newline at end of file diff --git a/cpp/153.cpp b/cpp/153.cpp new file mode 100644 index 0000000..c57c76a --- /dev/null +++ b/cpp/153.cpp @@ -0,0 +1,23 @@ +class Solution { + // Runtime: 4 ms, faster than 89.79% of C++ online submissions for Find + // Minimum in Rotated Sorted Array. Memory Usage: 8.8 MB, less than 29.27% of + // C++ online submissions for Find Minimum in Rotated Sorted Array. +public: + int findMin(vector &nums) { + int minVal = 0x7fffffff; + function helper = [&](int low, int high) { + if (low > high) + return; + if (nums[low] <= nums[high]) + minVal = min(minVal, nums[low]); + else { + int mid = (high + low) / 2; + helper(low, mid - 1); + helper(mid + 1, high); + minVal = min(minVal, nums[mid]); + } + }; + helper(0, nums.size() - 1); + return minVal; + } +}; \ No newline at end of file diff --git a/cpp/155.MinStack/doubleStack-26ms.cpp b/cpp/155.MinStack/doubleStack-26ms.cpp deleted file mode 100644 index 7f0dcf2..0000000 --- a/cpp/155.MinStack/doubleStack-26ms.cpp +++ /dev/null @@ -1,39 +0,0 @@ -class MinStack { - stack st; - stackmin; -public: - /** initialize your data structure here. */ - MinStack() { - } - - void push(int x) { - if(min.size()==0) - min.push(x); - else if(min.top()>=x) - min.push(x); - st.push(x); - } - - void pop() { - if(st.top()==min.top()) - min.pop(); - st.pop(); - } - - int top() { - return st.top(); - } - - int getMin() { - return min.top(); - } -}; - -/** - * Your MinStack object will be instantiated and called as such: - * MinStack obj = new MinStack(); - * obj.push(x); - * obj.pop(); - * int param_3 = obj.top(); - * int param_4 = obj.getMin(); - */ diff --git a/cpp/155.cpp b/cpp/155.cpp new file mode 100644 index 0000000..ce17237 --- /dev/null +++ b/cpp/155.cpp @@ -0,0 +1,36 @@ +// doubleStack-26ms.cpp +class MinStack { + stack st; + stack min; + +public: + /** initialize your data structure here. */ + MinStack() {} + + void push(int x) { + if (min.size() == 0) + min.push(x); + else if (min.top() >= x) + min.push(x); + st.push(x); + } + + void pop() { + if (st.top() == min.top()) + min.pop(); + st.pop(); + } + + int top() { return st.top(); } + + int getMin() { return min.top(); } +}; + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack obj = new MinStack(); + * obj.push(x); + * obj.pop(); + * int param_3 = obj.top(); + * int param_4 = obj.getMin(); + */ diff --git a/cpp/16.3SumClosest/sort.cpp b/cpp/16.3SumClosest/sort.cpp deleted file mode 100644 index 3278a28..0000000 --- a/cpp/16.3SumClosest/sort.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -public: - int threeSumClosest(vector& nums, int target) { - sort(nums.begin(),nums.end()); - int t=0x7fffffff,j,k,n=nums.size(),s; - for(int i=0;iabs(sum-s)) - t=sum-s; - if(sum>s) - k--; - else if(sum& nums, int target) { + sort(nums.begin(), nums.end()); + int t = 0x7fffffff, j, k, n = nums.size(), s; + for (int i = 0; i < n; ++i) { + s = target - nums[i]; + for (j = i + 1, k = n - 1; j < k;) { + int sum = nums[j] + nums[k]; + if (abs(t) > abs(sum - s)) + t = sum - s; + if (sum > s) + k--; + else if (sum < s) + ++j; + else + return target; + } + } + return target + t; + } +}; +class Solution2 { +public: + int threeSumClosest(vector nums, int target) { + sort(nums.begin(), nums.end()); + int ret = 1000000; + auto find = [&ret, &target](vector& nums, int k) { + int i = k + 1, j = nums.size() - 1; + while (i < j) { + int sum = nums[i] + nums[j] + nums[k]; + if (abs(sum - target) < abs(ret - target)) { + ret = sum; + } + if (sum > target) { + --j; + } else if (sum < target) { + ++i; + } else { + return; + } + } + }; + for (int k = 0; k < nums.size(); ++k) { + find(nums, k); + if (ret == target) + return ret; + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/160.IntersectionOfTwoLinkedLists/iteration.cpp b/cpp/160.IntersectionOfTwoLinkedLists/iteration.cpp deleted file mode 100644 index acbd297..0000000 --- a/cpp/160.IntersectionOfTwoLinkedLists/iteration.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { - if(headA==NULL||headB==NULL) - return NULL; - if(headA==headB) - return headA; - ListNode *p1=headA,*p2=headB; - while(p1!=p2){ - p1=p1->next; - p2=p2->next; - if(p1==p2)return p1; - if(p1==NULL) - p1=headB; - if(p2==NULL) - p2=headA; - } - return p1; - } -}; diff --git a/cpp/160.cpp b/cpp/160.cpp new file mode 100644 index 0000000..59daa03 --- /dev/null +++ b/cpp/160.cpp @@ -0,0 +1,30 @@ +// iteration.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + if (headA == NULL || headB == NULL) + return NULL; + if (headA == headB) + return headA; + ListNode *p1 = headA, *p2 = headB; + while (p1 != p2) { + p1 = p1->next; + p2 = p2->next; + if (p1 == p2) + return p1; + if (p1 == NULL) + p1 = headB; + if (p2 == NULL) + p2 = headA; + } + return p1; + } +}; diff --git a/cpp/162.cpp b/cpp/162.cpp new file mode 100644 index 0000000..540d73c --- /dev/null +++ b/cpp/162.cpp @@ -0,0 +1,18 @@ +class Solution { + public: + int findPeakElement(vector& nums) { + int l = 0, r = nums.size(); + while (l < r) { + int m = (l + r) / 2; + bool condition1 = m == 0 || nums[m] > nums[m - 1]; + bool condition2 = m == nums.size() - 1 || nums[m] > nums[m + 1]; + if (condition1 && condition2) + return m; + if (!condition1) + r = m; + else + l = m + 1; + } + return -1; + } +}; \ No newline at end of file diff --git a/cpp/164.MaximumGap/bucket.cpp b/cpp/164.MaximumGap/bucket.cpp deleted file mode 100644 index d3ab9e8..0000000 --- a/cpp/164.MaximumGap/bucket.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Bucket { -public: - bool used = false; - int minval = numeric_limits::max(); // same as INT_MAX - int maxval = numeric_limits::min(); // same as INT_MIN -}; - -int maximumGap(vector& nums) -{ - if (nums.empty() || nums.size() < 2) - return 0; - - int mini = *min_element(nums.begin(), nums.end()), - maxi = *max_element(nums.begin(), nums.end()); - - int bucketSize = max(1, (maxi - mini) / ((int)nums.size() - 1)); // bucket size or capacity - int bucketNum = (maxi - mini) / bucketSize + 1; // number of buckets - vector buckets(bucketNum); - - for (auto&& num : nums) { - int bucketIdx = (num - mini) / bucketSize; // locating correct bucket - buckets[bucketIdx].used = true; - buckets[bucketIdx].minval = min(num, buckets[bucketIdx].minval); - buckets[bucketIdx].maxval = max(num, buckets[bucketIdx].maxval); - } - - int prevBucketMax = mini, maxGap = 0; - for (auto&& bucket : buckets) { - if (!bucket.used) - continue; - - maxGap = max(maxGap, bucket.minval - prevBucketMax); - prevBucketMax = bucket.maxval; - } - - return maxGap; -} diff --git a/cpp/164.MaximumGap/sort.cpp b/cpp/164.MaximumGap/sort.cpp deleted file mode 100644 index c48ec97..0000000 --- a/cpp/164.MaximumGap/sort.cpp +++ /dev/null @@ -1,15 +0,0 @@ -int trick = [](){ - ios_base::sync_with_stdio(false); - cin.tie(nullptr); - return 0; -}(); -class Solution { -public: - int maximumGap(vector& nums) { - sort(begin(nums),end(nums)); - int res=0; - for(int i=1;i::max(); // same as INT_MAX + int maxval = numeric_limits::min(); // same as INT_MIN +}; + +int maximumGap(vector &nums) { + if (nums.empty() || nums.size() < 2) + return 0; + + int mini = *min_element(nums.begin(), nums.end()), + maxi = *max_element(nums.begin(), nums.end()); + + int bucketSize = + max(1, (maxi - mini) / ((int)nums.size() - 1)); // bucket size or capacity + int bucketNum = (maxi - mini) / bucketSize + 1; // number of buckets + vector buckets(bucketNum); + + for (auto &&num : nums) { + int bucketIdx = (num - mini) / bucketSize; // locating correct bucket + buckets[bucketIdx].used = true; + buckets[bucketIdx].minval = min(num, buckets[bucketIdx].minval); + buckets[bucketIdx].maxval = max(num, buckets[bucketIdx].maxval); + } + + int prevBucketMax = mini, maxGap = 0; + for (auto &&bucket : buckets) { + if (!bucket.used) + continue; + + maxGap = max(maxGap, bucket.minval - prevBucketMax); + prevBucketMax = bucket.maxval; + } + + return maxGap; +} +// sort.cpp +int trick = []() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + return 0; +}(); +class Solution { +public: + int maximumGap(vector &nums) { + sort(begin(nums), end(nums)); + int res = 0; + for (int i = 1; i < nums.size(); ++i) + res = max(nums[i] - nums[i - 1], res); + return res; + } +}; diff --git a/cpp/165.CompareVersionNumbers/sstream.cpp b/cpp/165.CompareVersionNumbers/sstream.cpp deleted file mode 100644 index 19d74bc..0000000 --- a/cpp/165.CompareVersionNumbers/sstream.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - int compareVersion(string version1, string version2) { - stringstream ss1,ss2; - ss1<>a; - if(!ss2.eof()) - ss2>>b; - if(a>b) - return 1; - else if(a>ch; - ss2>>ch; - a=0; - b=0; - } - return 0; - } -}; diff --git a/cpp/165.cpp b/cpp/165.cpp new file mode 100644 index 0000000..af626e4 --- /dev/null +++ b/cpp/165.cpp @@ -0,0 +1,23 @@ +// sstream.cpp +class Solution { + public: + int compareVersion(string version1, string version2) { + stringstream ss1(version1), ss2(version2); + int a, b; + char ch; + while (!ss1.eof() || !ss2.eof()) { + if (!ss1.eof()) + ss1 >> a; + if (!ss2.eof()) + ss2 >> b; + if (a > b) + return 1; + else if (a < b) + return -1; + ss1 >> ch; + ss2 >> ch; + a = b = 0; + } + return 0; + } +}; diff --git a/cpp/166.cpp b/cpp/166.cpp new file mode 100644 index 0000000..e57f34f --- /dev/null +++ b/cpp/166.cpp @@ -0,0 +1,34 @@ +class Solution { + string impl(long long numerator, long long denominator) { + auto result = numerator / denominator; + if (result * denominator == numerator) + return to_string(result); + unordered_map meet; + string res; + int pos = 0; + for (numerator -= result * denominator; numerator != 0;) { + do { + if (auto it = meet.find(numerator); it != meet.end()) { + res = res.substr(0, it->second) + '(' + + res.substr(it->second) + ')'; + return to_string(result) + "." + res; + } + meet[numerator] = pos++; + numerator *= 10; + res += "0"; + } while (numerator < denominator); + auto result = numerator / denominator; + res[res.size() - 1] += result; + numerator -= result * denominator; + } + return to_string(result) + "." + res; + } + public: + string fractionToDecimal(int numerator, int denominator) { + bool neg=false; + if((numerator<0&&denominator>0)||(numerator>0&&denominator<0)){ + neg=true; + } + return (neg ? "-" : "") + impl(abs(numerator), abs(denominator)); + } +}; \ No newline at end of file diff --git a/cpp/167.TwoSumII-InputArrayIsSorted/twoPointer-6ms.cpp b/cpp/167.TwoSumII-InputArrayIsSorted/twoPointer-6ms.cpp deleted file mode 100644 index b7d3d25..0000000 --- a/cpp/167.TwoSumII-InputArrayIsSorted/twoPointer-6ms.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - vector twoSum(vector& numbers, int target) { - int i=0,j=numbers.size()-1; - vector result(2); - while(itarget) - j--; - else - i++; - } - return result; - } -}; diff --git a/cpp/167.cpp b/cpp/167.cpp new file mode 100644 index 0000000..1a51c00 --- /dev/null +++ b/cpp/167.cpp @@ -0,0 +1,16 @@ +// twoPointer-6ms.cpp +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int i = 0, j = numbers.size() - 1; + while (i < j) { + if (numbers[i] + numbers[j] == target) { + return {i + 1, j + 1}; + } else if (numbers[i] + numbers[j] > target) + j--; + else + i++; + } + return {}; + } +}; diff --git a/cpp/168.ExcelSheetColumnTitle/onepass-0ms.cpp b/cpp/168.ExcelSheetColumnTitle/onepass-0ms.cpp deleted file mode 100644 index 2757f8e..0000000 --- a/cpp/168.ExcelSheetColumnTitle/onepass-0ms.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - string convertToTitle(int n) { - string str=""; - while(n>0){ - char ch=((n-1)%26+'A'); - str=ch+str; - n=(n-1)/26; - } - return str; - } -}; diff --git a/cpp/168.cpp b/cpp/168.cpp new file mode 100644 index 0000000..2199571 --- /dev/null +++ b/cpp/168.cpp @@ -0,0 +1,13 @@ +// onepass-0ms.cpp +class Solution { + public: + string convertToTitle(int n) { + string str = ""; + while (n > 0) { + char ch = ((n - 1) % 26 + 'A'); + str = ch + str; + n = (n - 1) / 26; + } + return str; + } +}; diff --git a/cpp/169.MajorityElement/onepass-16ms.cpp b/cpp/169.MajorityElement/onepass-16ms.cpp deleted file mode 100644 index b62229c..0000000 --- a/cpp/169.MajorityElement/onepass-16ms.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int majorityElement(vector& nums) { - int last=nums[0],count=1; - for(int i=1;i& nums) { + int last = nums[0], count = 1; + for (int i = 1; i < nums.size(); ++i) + if (nums[i] == last) + ++count; + else { + if (--count == 0) { + last = nums[i]; + count = 1; + } + } + return last; + } +}; \ No newline at end of file diff --git a/cpp/17.LetterCombinationsOfAPhoneNumber/dfs.cpp b/cpp/17.LetterCombinationsOfAPhoneNumber/dfs.cpp deleted file mode 100644 index 9ced8f7..0000000 --- a/cpp/17.LetterCombinationsOfAPhoneNumber/dfs.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - vector letterCombinations(string digits) { - vectorletter={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; - vectorres; - if(digits.size()==0)return res; - dfs(letter,res,digits,"",0); - return res; - } - void dfs(vector&letter,vector&res,const string &digits,string cur,int i){ - if(i==digits.size()){ - res.push_back(cur); - return; - } - for(int j=0;j letter; + void dfs(vector& letter, vector& res, const string& digits, + string cur, int i) { + if (i == digits.size()) { + res.push_back(cur); + return; + } + for (int j = 0; j < letter[digits[i] - '0'].size(); ++j) + dfs(letter, res, digits, cur + letter[digits[i] - '0'][j], i + 1); + } + +public: + vector letterCombinations(string digits) { + vector res; + if (digits.size() == 0) + return res; + dfs(letter, res, digits, "", 0); + return res; + } +}; + +vector Solution::letter = {"", "", "abc", "def", "ghi", + "jkl", "mno", "pqrs", "tuv", "wxyz"}; + +string keymap[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; +class Solution2 { + vector combine(vector& a, string& b) { + vector res; + for (auto& i : a) { + for (auto& j : b) { + res.push_back(i + j); + } + } + return res; + } + +public: + vector letterCombinations(string digits) { + if (digits.empty()) + return {}; + vector res = {""}; + for (auto& d : digits) { + res = combine(res, keymap[d - '2']); + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/171.ExcelSheetColumnNumber/onepass-6ms.cpp b/cpp/171.ExcelSheetColumnNumber/onepass-6ms.cpp deleted file mode 100644 index 79236e9..0000000 --- a/cpp/171.ExcelSheetColumnNumber/onepass-6ms.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - int titleToNumber(string s) { - int j=s.size(),sum=0; - for(int i=0;i0) - sum+=n/=5; - return sum; - } -}; diff --git a/cpp/172.cpp b/cpp/172.cpp new file mode 100644 index 0000000..76156c7 --- /dev/null +++ b/cpp/172.cpp @@ -0,0 +1,10 @@ +// logn-3ms.cpp +class Solution { +public: + int trailingZeroes(int n) { + int sum = 0; + while (n > 0) + sum += n /= 5; + return sum; + } +}; diff --git a/cpp/173.BinarySearchTreeIterator/usingStack.cpp b/cpp/173.BinarySearchTreeIterator/usingStack.cpp deleted file mode 100644 index b4951eb..0000000 --- a/cpp/173.BinarySearchTreeIterator/usingStack.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class BSTIterator { - stackst; -public: - BSTIterator(TreeNode *root) { - while(root!=NULL){ - st.push(root); - root=root->left; - } - } - - /** @return whether we have a next smallest number */ - bool hasNext() { - return !st.empty(); - } - - /** @return the next smallest number */ - int next() { - TreeNode*p=st.top(); - st.pop(); - int value=p->val; - p=p->right; - while(p!=NULL){ - st.push(p); - p=p->left; - } - return value; - } -}; - -/** - * Your BSTIterator will be called like this: - * BSTIterator i = BSTIterator(root); - * while (i.hasNext()) cout << i.next(); - */ diff --git a/cpp/173.cpp b/cpp/173.cpp new file mode 100644 index 0000000..80c8924 --- /dev/null +++ b/cpp/173.cpp @@ -0,0 +1,43 @@ +// usingStack.cpp +/** + * Definition for binary tree + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class BSTIterator { + stack st; + +public: + BSTIterator(TreeNode *root) { + while (root != NULL) { + st.push(root); + root = root->left; + } + } + + /** @return whether we have a next smallest number */ + bool hasNext() { return !st.empty(); } + + /** @return the next smallest number */ + int next() { + TreeNode *p = st.top(); + st.pop(); + int value = p->val; + p = p->right; + while (p != NULL) { + st.push(p); + p = p->left; + } + return value; + } +}; + +/** + * Your BSTIterator will be called like this: + * BSTIterator i = BSTIterator(root); + * while (i.hasNext()) cout << i.next(); + */ diff --git a/cpp/179.LargestNumber/sort.cpp b/cpp/179.LargestNumber/sort.cpp deleted file mode 100644 index 25c9e4a..0000000 --- a/cpp/179.LargestNumber/sort.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - string largestNumber(vector& nums) { - vectors; - string res; - for(int i=0;ibb[i]; - return false; - }); - for(int i=0;i &nums) { + vector s; + string res; + for (int i = 0; i < nums.size(); ++i) + s.push_back(to_string(nums[i])); + sort(s.begin(), s.end(), [](const string &a, const string &b) { + string aa = a + b, bb = b + a; + for (int i = 0; i < aa.size(); i++) + if (aa[i] != bb[i]) + return aa[i] > bb[i]; + return false; + }); + for (int i = 0; i < s.size(); ++i) + res += s[i]; + return res.find_first_not_of("0") == string::npos ? "0" : res; + } +}; diff --git a/cpp/18.4Sum/12msBeat95%.cpp b/cpp/18.4Sum/12msBeat95%.cpp deleted file mode 100644 index 5ca80cc..0000000 --- a/cpp/18.4Sum/12msBeat95%.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -public: - vector> fourSum(vector& nums, int target) { - int i,j,a,b,t,tt,n=nums.size(),sum; - vector>res; - sort(nums.begin(),nums.end()); - for(i=0;i0&&nums[i]==nums[i-1])continue; - if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target)break; - if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]i+1&&nums[j]==nums[j-1])continue; - if(nums[j]+nums[j+1]+nums[j+2]>t) break; - if(nums[j]+nums[n-2]+nums[n-1]tt) - --b; - else{ - res.push_back(vector{nums[i],nums[j],nums[a],nums[b]}); - do{++a;}while(a> fourSum(vector &nums, int target) { + int i, j, a, b, t, tt, n = nums.size(), sum; + vector> res; + sort(nums.begin(), nums.end()); + for (i = 0; i < n - 3; ++i) { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) + break; + if (nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) + continue; + t = target - nums[i]; + for (j = i + 1; j < n - 2; ++j) { + if (j > i + 1 && nums[j] == nums[j - 1]) + continue; + if (nums[j] + nums[j + 1] + nums[j + 2] > t) + break; + if (nums[j] + nums[n - 2] + nums[n - 1] < t) + continue; + tt = t - nums[j]; + for (a = j + 1, b = n - 1; a < b;) { + sum = nums[a] + nums[b]; + if (sum < tt) + ++a; + else if (sum > tt) + --b; + else { + res.push_back(vector{nums[i], nums[j], nums[a], nums[b]}); + do { + ++a; + } while (a < b && nums[a] == nums[a - 1]); + do { + --b; + } while (a < b && nums[b] == nums[b + 1]); + } + } + } + } + return res; + } +}; diff --git a/cpp/187.RepeatedDNASequences/hashset.cpp b/cpp/187.RepeatedDNASequences/hashset.cpp deleted file mode 100644 index 33388fc..0000000 --- a/cpp/187.RepeatedDNASequences/hashset.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - vector findRepeatedDnaSequences(string s) { - unordered_sethashset,res; - for(int i=0;i<=(int)s.size()-10;++i){ - string str=s.substr(i,10); - if(hashset.find(str)!=hashset.end()) - res.insert(str); - else - hashset.insert(str); - } - return vector(res.begin(),res.end()); - } -}; diff --git a/cpp/187.cpp b/cpp/187.cpp new file mode 100644 index 0000000..0d326c6 --- /dev/null +++ b/cpp/187.cpp @@ -0,0 +1,15 @@ +// hashset.cpp +class Solution { + public: + vector findRepeatedDnaSequences(string s) { + unordered_set hashset, res; + for (int i = 0; i <= (int)s.size() - 10; ++i) { + auto str = string_view(s).substr(i, 10); + if (hashset.find(str) != hashset.end()) + res.insert(str); + else + hashset.insert(str); + } + return {res.begin(), res.end()}; + } +}; \ No newline at end of file diff --git a/cpp/189.RotateArray/reverse3times-19ms.cpp b/cpp/189.RotateArray/reverse3times-19ms.cpp deleted file mode 100644 index 8227741..0000000 --- a/cpp/189.RotateArray/reverse3times-19ms.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - void rotate(vector& nums, int k) { - int len=nums.size(); - if( ! (k%=len) )return; - int off=len-k,i,j; - for(i=0,j=off-1;i nums) { reverse(nums.begin(), nums.end()); } + + public: + void rotate(vector& nums, int k) { + if (!(k %= nums.size())) + return; + rotate(nums); + rotate(span(nums).subspan(0, k)); + rotate(span(nums).subspan(k)); + } +}; diff --git a/cpp/19.RemoveNthNodeFromEndOfList.cpp b/cpp/19.RemoveNthNodeFromEndOfList.cpp deleted file mode 100644 index 99b9cd9..0000000 --- a/cpp/19.RemoveNthNodeFromEndOfList.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* removeNthFromEnd(ListNode* head, int n) { - auto h=ListNode(0); - h.next=head; - auto p1=&h,p2=&h; - for(int i=0;i<=n;++i) - p1=p1->next; - while(p1){ - p2=p2->next; - p1=p1->next; - } - p2->next=p2->next->next; - return h.next; - } -}; \ No newline at end of file diff --git a/cpp/19.cpp b/cpp/19.cpp new file mode 100644 index 0000000..cc8dc4d --- /dev/null +++ b/cpp/19.cpp @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + auto h = ListNode(0, head); + auto p1 = &h, p2 = &h; + for (int i = 0; i < n; ++i) + p1 = p1->next; + while (p1->next) { + p2 = p2->next; + p1 = p1->next; + } + p2->next = p2->next->next; + return h.next; + } +}; \ No newline at end of file diff --git a/cpp/190.ReverseBits/onepass-3ms.cpp b/cpp/190.ReverseBits/onepass-3ms.cpp deleted file mode 100644 index 3e80cce..0000000 --- a/cpp/190.ReverseBits/onepass-3ms.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - uint32_t reverseBits(uint32_t n) { - n= (n<<16) |(n>>16); - n=((n<<8)&0xff00ff00)|((n>>8)&0x00ff00ff); - n=((n<<4)&0xf0f0f0f0)|((n>>4)&0x0f0f0f0f); - n=((n<<2)&0xcccccccc)|((n>>2)&0x33333333); - n=((n<<1)&0xaaaaaaaa)|((n>>1)&0x55555555); - return n; - } -}; diff --git a/cpp/190.cpp b/cpp/190.cpp new file mode 100644 index 0000000..1e2cb55 --- /dev/null +++ b/cpp/190.cpp @@ -0,0 +1,12 @@ +// onepass-3ms.cpp +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + n = (n << 16) | (n >> 16); + n = ((n << 8) & 0xff00ff00) | ((n >> 8) & 0x00ff00ff); + n = ((n << 4) & 0xf0f0f0f0) | ((n >> 4) & 0x0f0f0f0f); + n = ((n << 2) & 0xcccccccc) | ((n >> 2) & 0x33333333); + n = ((n << 1) & 0xaaaaaaaa) | ((n >> 1) & 0x55555555); + return n; + } +}; diff --git a/cpp/191.NumberOf1Bits/onepass-3ms.cpp b/cpp/191.NumberOf1Bits/onepass-3ms.cpp deleted file mode 100644 index e32387d..0000000 --- a/cpp/191.NumberOf1Bits/onepass-3ms.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int hammingWeight(uint32_t n) { - int count=0; - while(n>0){ - ++count; - n&=(n-1); - } - return count; - } -}; diff --git a/cpp/191.cpp b/cpp/191.cpp new file mode 100644 index 0000000..eab0828 --- /dev/null +++ b/cpp/191.cpp @@ -0,0 +1,12 @@ +// onepass-3ms.cpp +class Solution { +public: + int hammingWeight(uint32_t n) { + int count = 0; + while (n > 0) { + ++count; + n &= (n - 1); + } + return count; + } +}; diff --git a/cpp/198.HouseRobber/SpaceOnTimeOn.cpp b/cpp/198.HouseRobber/SpaceOnTimeOn.cpp deleted file mode 100644 index c7882e2..0000000 --- a/cpp/198.HouseRobber/SpaceOnTimeOn.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - int rob(vector& nums) { - int n=nums.size(); - vectordp(n+2,0); - for(int i=2;i &nums) { + int n = nums.size(); + vector dp(n + 2, 0); + for (int i = 2; i < n + 2; ++i) + dp[i] = max(dp[i - 2] + nums[i - 2], dp[i - 1]); + return dp[n + 1]; + } +}; diff --git a/cpp/199.BinaryTreeRightSideView/preorder.cpp b/cpp/199.BinaryTreeRightSideView/preorder.cpp deleted file mode 100644 index 009eeef..0000000 --- a/cpp/199.BinaryTreeRightSideView/preorder.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector rightSideView(TreeNode* root) { - vectorresult; - preorder(result,root,0); - return result; - } - void preorder(vector&nums,TreeNode *root,int depth){ - if(!root) - return; - if(nums.size()==depth) - nums.push_back(root->val); - preorder(nums,root->right,depth+1); - preorder(nums,root->left,depth+1); - } -}; diff --git a/cpp/199.cpp b/cpp/199.cpp new file mode 100644 index 0000000..bb920b8 --- /dev/null +++ b/cpp/199.cpp @@ -0,0 +1,26 @@ +// preorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + void preorder(vector &nums, TreeNode *root, int depth) { + if (!root) + return; + if (nums.size() == depth) + nums.push_back(root->val); + preorder(nums, root->right, depth + 1); + preorder(nums, root->left, depth + 1); + } +public: + vector rightSideView(TreeNode *root) { + vector result; + preorder(result, root, 0); + return result; + } +}; diff --git a/cpp/2.AddTwoNumbers.cpp b/cpp/2.AddTwoNumbers.cpp deleted file mode 100644 index 171c66a..0000000 --- a/cpp/2.AddTwoNumbers.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { - ListNode head(0); - auto cur=&head; - int remain=0; - while(l1||l2){ - auto val=remain+(l1?l1->val:0)+(l2?l2->val:0); - cur=cur->next=new ListNode(val%10); - remain=val/10; - if(l1) - l1=l1->next; - if(l2) - l2=l2->next; - } - if(remain) - cur->next=new ListNode(remain); - return head.next; - } -}; \ No newline at end of file diff --git a/cpp/2.cpp b/cpp/2.cpp new file mode 100644 index 0000000..bb24cc8 --- /dev/null +++ b/cpp/2.cpp @@ -0,0 +1,30 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode head(0); + auto cur = &head; + int remain = 0; + while (l1 || l2) { + auto val = remain + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); + cur = cur->next = new ListNode(val % 10); + remain = val / 10; + if (l1) + l1 = l1->next; + if (l2) + l2 = l2->next; + } + if (remain) + cur->next = new ListNode(remain); + return head.next; + } +}; \ No newline at end of file diff --git a/cpp/20.ValidParentheses.cpp b/cpp/20.ValidParentheses.cpp deleted file mode 100644 index ef3c791..0000000 --- a/cpp/20.ValidParentheses.cpp +++ /dev/null @@ -1,56 +0,0 @@ -class Solution { // 3ms -public: - bool isValid(string s) { - if(s.size()%2!=0)return 0; - stackst; - int i=0; - while(ist; - for(int i=0;i st; + unordered_map mapping = { + {'(', ')'}, {'[', ']'}, {'{', '}'}}; + for (auto ch : s) { + switch (ch) { + case '(': + case '[': + case '{': + st.push(ch); + break; + case ')': + case '}': + case ']': + if (st.empty() || ch != mapping[st.top()]) + return false; + st.pop(); + } + } + return st.size() == 0; + } +}; \ No newline at end of file diff --git a/cpp/200.NumberOfIslands/dfs.cpp b/cpp/200.NumberOfIslands/dfs.cpp deleted file mode 100644 index da00240..0000000 --- a/cpp/200.NumberOfIslands/dfs.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { - int row,col; -public: - int numIslands(vector>& grid) { - int count=0; - row=grid.size(); - if(row==0)return 0; - col=grid[0].size(); - for(int i=0;i>& grid,int i,int j){ - if(i<0||i>=row||j<0||j>=col||grid[i][j]=='0')return; - grid[i][j]='0'; - dfs(grid,i-1,j); - dfs(grid,i+1,j); - dfs(grid,i,j-1); - dfs(grid,i,j+1); - } -}; diff --git a/cpp/200.cpp b/cpp/200.cpp new file mode 100644 index 0000000..c8fe13e --- /dev/null +++ b/cpp/200.cpp @@ -0,0 +1,29 @@ +// dfs.cpp +class Solution { + int row, col; + void dfs(vector> &grid, int i, int j) { + if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == '0') + return; + grid[i][j] = '0'; + dfs(grid, i - 1, j); + dfs(grid, i + 1, j); + dfs(grid, i, j - 1); + dfs(grid, i, j + 1); + } + +public: + int numIslands(vector> &grid) { + int count = 0; + row = grid.size(); + if (row == 0) + return 0; + col = grid[0].size(); + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + if (grid[i][j] == '1') { + ++count; + dfs(grid, i, j); + } + return count; + } +}; diff --git a/cpp/201.BitwiseANDOfNumbersRange/uglyBut32ms.cpp b/cpp/201.BitwiseANDOfNumbersRange/uglyBut32ms.cpp deleted file mode 100644 index 599b3a7..0000000 --- a/cpp/201.BitwiseANDOfNumbersRange/uglyBut32ms.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - int rangeBitwiseAnd(int m, int n) { - if(m==n) - return n; - int count=0; - for(int v=n;v>0;++count) - v>>=1; - int res=0; - do{ - int a=(1<<(count-1))&m; - int b=(1<<(count-1))&n; - if(a==b) - res|=a; - else - break; - }while(--count); - return res; - } -}; diff --git a/cpp/201.cpp b/cpp/201.cpp new file mode 100644 index 0000000..64d9bfc --- /dev/null +++ b/cpp/201.cpp @@ -0,0 +1,21 @@ +// uglyBut32ms.cpp +class Solution { +public: + int rangeBitwiseAnd(int m, int n) { + if (m == n) + return n; + int count = 0; + for (int v = n; v > 0; ++count) + v >>= 1; + int res = 0; + do { + int a = (1 << (count - 1)) & m; + int b = (1 << (count - 1)) & n; + if (a == b) + res |= a; + else + break; + } while (--count); + return res; + } +}; diff --git a/cpp/202.HappyNumber/hashset.cpp b/cpp/202.HappyNumber/hashset.cpp deleted file mode 100644 index 32d2d0f..0000000 --- a/cpp/202.HappyNumber/hashset.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - bool isHappy(int n) { - unordered_setset; - while (n!=1) { - int sum = 0; - while (n>0) { - sum += (n % 10)*(n % 10); - n /= 10; - } - n = sum; - if (set.find(sum) == set.end()) - set.insert(sum); - else - return 0; - } - return 1; - } -}; diff --git a/cpp/202.cpp b/cpp/202.cpp new file mode 100644 index 0000000..7c00909 --- /dev/null +++ b/cpp/202.cpp @@ -0,0 +1,20 @@ +// hashset.cpp +class Solution { +public: + bool isHappy(int n) { + unordered_set set; + while (n != 1) { + int sum = 0; + while (n > 0) { + sum += (n % 10) * (n % 10); + n /= 10; + } + n = sum; + if (set.find(sum) == set.end()) + set.insert(sum); + else + return 0; + } + return 1; + } +}; diff --git a/cpp/203.RemoveLinkedListElements/iteration.cpp b/cpp/203.RemoveLinkedListElements/iteration.cpp deleted file mode 100644 index efc4dc2..0000000 --- a/cpp/203.RemoveLinkedListElements/iteration.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* removeElements(ListNode* head, int val) { - if(head==NULL)return head; - while(head->val==val){ - head=head->next; - if(head==NULL)break; - } - ListNode *p=head; - while(p){ - if(p->next!=NULL) - if(p->next->val==val) - p->next=p->next->next; - else - p=p->next; - else - break; - } - return head; - } -}; diff --git a/cpp/203.cpp b/cpp/203.cpp new file mode 100644 index 0000000..54532f0 --- /dev/null +++ b/cpp/203.cpp @@ -0,0 +1,27 @@ +// iteration.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { + public: + ListNode* removeElements(ListNode* head, int val) { + while (head && head->val == val) { + head = head->next; + } + ListNode* p = head; + while (p) { + if (p->next) + if (p->next->val == val) { + p->next = p->next->next; + continue; + } + p = p->next; + } + return head; + } +}; diff --git a/cpp/204.CountPrimes/SieveofEratosthenes-52ms.cpp b/cpp/204.CountPrimes/SieveofEratosthenes-52ms.cpp deleted file mode 100644 index 1914aff..0000000 --- a/cpp/204.CountPrimes/SieveofEratosthenes-52ms.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int countPrimes(int n) { - vectorarr(n,1); - isPrime(arr); - int result=0; - for(int i=2;i&arr){ - for(int i=2;i& arr) { + for (int i = 2; i < arr.size(); ++i) + if (arr[i] != 0) { + for (int j = (i << 1); j < arr.size(); j += i) + arr[j] = 0; + } + } + + public: + int countPrimes(int n) { + vector arr(n, 1); + initPrime(arr); + int result = 0; + for (int i = 2; i < n; ++i) + if (arr[i] == 1) + ++result; + return result; + } +}; diff --git a/cpp/205.IsomorphicStrings/2maps-9ms.cpp b/cpp/205.IsomorphicStrings/2maps-9ms.cpp deleted file mode 100644 index 531d364..0000000 --- a/cpp/205.IsomorphicStrings/2maps-9ms.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - bool isIsomorphic(string s, string t) { - int len=s.size(),index1,index2; - vectorhash1(256,INT_MIN); - vectorhash2(256,INT_MIN); - for(int i=0;i hash1(256, INT_MIN); + vector hash2(256, INT_MIN); + for (int i = 0; i < len; ++i) { + index1 = s[i]; + index2 = t[i]; + if (hash1[index1] == INT_MIN) { + hash1[index1] = t[i]; + if (hash2[index2] != INT_MIN) + return 0; + hash2[index2] = s[i]; + } + if (hash1[index1] != t[i]) + return 0; + if (hash2[index2] != s[i]) + return 0; + } + return 1; + } +}; diff --git a/cpp/206.ReverseLinkedList/iteration.cpp b/cpp/206.ReverseLinkedList/iteration.cpp deleted file mode 100644 index 73c8394..0000000 --- a/cpp/206.ReverseLinkedList/iteration.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - if(head==NULL||head->next==NULL) - return head; - ListNode*pre=NULL,*now=head; - while(now){ - ListNode *next=now->next; - now->next=pre; - pre=now; - now=next; - } - return pre; - } -}; diff --git a/cpp/206.ReverseLinkedList/recursion.cpp b/cpp/206.ReverseLinkedList/recursion.cpp deleted file mode 100644 index 83ac2b0..0000000 --- a/cpp/206.ReverseLinkedList/recursion.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - if(head==NULL)return head; - if(head->next==NULL) - return head; - return recursivelyReverse(NULL,head); - } - ListNode* recursivelyReverse(ListNode* pre,ListNode* now){ - ListNode*next=now->next; - now->next=pre; - if(next==NULL)return now; - return recursivelyReverse(now,next); - } -}; diff --git a/cpp/206.cpp b/cpp/206.cpp new file mode 100644 index 0000000..5b61ad3 --- /dev/null +++ b/cpp/206.cpp @@ -0,0 +1,48 @@ +// iteration.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *reverseList(ListNode *head) { + if (!head || !head->next) + return head; + ListNode *pre = nullptr, *now = head; + while (now) { + ListNode *next = now->next; + now->next = pre; + pre = now; + now = next; + } + return pre; + } +}; +// recursion.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution2 { + ListNode *impl(ListNode *pre, ListNode *now) { + ListNode *next = now->next; + now->next = pre; + if (!next) + return now; + return impl(now, next); + } +public: + ListNode *reverseList(ListNode *head) { + if (!head || !head->next) + return head; + return impl(nullptr, head); + } +}; diff --git a/cpp/207.CourseSchedule/simple.cpp b/cpp/207.CourseSchedule/simple.cpp deleted file mode 100644 index bc30307..0000000 --- a/cpp/207.CourseSchedule/simple.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - bool canFinish(int numCourses, vector>& prerequisites) { - vector>reverse(numCourses); - vectorcounts(numCourses,0); - for(auto p:prerequisites){ - reverse[p.second].push_back(p.first); - counts[p.first]++; - } - int finished=0; - for(auto it=find(counts.begin(),counts.end(),0);it!=counts.end();){ - ++finished; - *it=-1; - int index=(int)(it-counts.begin()); - for(int num:reverse[index]) - counts[num]--; - it=find(counts.begin(),counts.end(),0); - } - return finished==numCourses; - } -}; diff --git a/cpp/207.cpp b/cpp/207.cpp new file mode 100644 index 0000000..f9e29da --- /dev/null +++ b/cpp/207.cpp @@ -0,0 +1,22 @@ +// simple.cpp +class Solution { +public: + bool canFinish(int numCourses, vector> &prerequisites) { + vector> reverse(numCourses); + vector counts(numCourses, 0); + for (auto p : prerequisites) { + reverse[p.second].push_back(p.first); + counts[p.first]++; + } + int finished = 0; + for (auto it = find(counts.begin(), counts.end(), 0); it != counts.end();) { + ++finished; + *it = -1; + int index = (int)(it - counts.begin()); + for (int num : reverse[index]) + counts[num]--; + it = find(counts.begin(), counts.end(), 0); + } + return finished == numCourses; + } +}; diff --git a/cpp/208.ImplementTrie_PrefixTree/trie.cpp b/cpp/208.ImplementTrie_PrefixTree/trie.cpp deleted file mode 100644 index e8209ef..0000000 --- a/cpp/208.ImplementTrie_PrefixTree/trie.cpp +++ /dev/null @@ -1,58 +0,0 @@ -class Trie { - struct trie{ - trie():isWord(false){ - memset(this,0,sizeof(trie)); - } - bool isWord; - trie *children[26]; - }root; -public: - /** Initialize your data structure here. */ - Trie() { - - } - - /** Inserts a word into the trie. */ - void insert(string word) { - trie *p=&root; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - p->children[offset]=new trie(); - p=p->children[offset]; - } - p->isWord=true; - } - - /** Returns if the word is in the trie. */ - bool search(string word) { - trie *p=&root; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - return false; - p=p->children[offset]; - } - return p->isWord; - } - - /** Returns if there is any word in the trie that starts with the given prefix. */ - bool startsWith(string prefix) { - trie *p=&root; - for(auto ch:prefix){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - return false; - p=p->children[offset]; - } - return true; - } -}; - -/** - * Your Trie object will be instantiated and called as such: - * Trie obj = new Trie(); - * obj.insert(word); - * bool param_2 = obj.search(word); - * bool param_3 = obj.startsWith(prefix); - */ diff --git a/cpp/208.cpp b/cpp/208.cpp new file mode 100644 index 0000000..b32bdfd --- /dev/null +++ b/cpp/208.cpp @@ -0,0 +1,57 @@ +// trie.cpp +class Trie { + struct trie { + trie() : isWord(false) { memset(this, 0, sizeof(trie)); } + bool isWord; + trie *children[26]; + } root; + +public: + /** Initialize your data structure here. */ + Trie() {} + + /** Inserts a word into the trie. */ + void insert(string word) { + trie *p = &root; + for (auto ch : word) { + int offset = ch - 'a'; + if (p->children[offset] == nullptr) + p->children[offset] = new trie(); + p = p->children[offset]; + } + p->isWord = true; + } + + /** Returns if the word is in the trie. */ + bool search(string word) { + trie *p = &root; + for (auto ch : word) { + int offset = ch - 'a'; + if (p->children[offset] == nullptr) + return false; + p = p->children[offset]; + } + return p->isWord; + } + + /** Returns if there is any word in the trie that starts with the given + * prefix. */ + bool startsWith(string prefix) { + trie *p = &root; + for (auto ch : prefix) { + int offset = ch - 'a'; + if (p->children[offset] == nullptr) + return false; + p = p->children[offset]; + } + return true; + } +}; + +/** + * Your Trie object will be instantiated and called as such: + * Trie obj = new Trie(); + * obj.insert(word); + * bool param_2 = obj.search(word); + * bool param_3 = obj.startsWith(prefix); + */ diff --git a/cpp/209.MinimumSizeSubarraySum/doublepointers.cpp b/cpp/209.MinimumSizeSubarraySum/doublepointers.cpp deleted file mode 100644 index 1f50a79..0000000 --- a/cpp/209.MinimumSizeSubarraySum/doublepointers.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int minSubArrayLen(int s, vector& nums) { - int min = INT_MAX, i = 0, j = 0, n = nums.size(), sum = 0; - if (n == 0)return 0; - while(j=s){ - min = min &nums) { + int min = INT_MAX, i = 0, j = 0, n = nums.size(), sum = 0; + if (n == 0) + return 0; + while (j < n) { + sum += nums[j++]; + while (sum >= s) { + min = min < j - i ? min : j - i; + sum -= nums[i++]; + } + } + return min == INT_MAX ? 0 : min; + } +}; diff --git a/cpp/21.MergeTwoSortedLists.cpp b/cpp/21.MergeTwoSortedLists.cpp deleted file mode 100644 index e5f532e..0000000 --- a/cpp/21.MergeTwoSortedLists.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { // iteration 8ms -public: - ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { - auto h=ListNode(0); - auto p=&h; - while(l1&&l2){ - auto &smallP = l1->valval?l1:l2; - p=p->next=smallP; - smallP=smallP->next; - } - p->next=l1?l1:l2; - return h.next; - } -}; -class Solution { // recursion -public: - ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { - if(l1==nullptr) - return l2; - if(l2==nullptr) - return l1; - if(l1->valval){ - l1->next=mergeTwoLists(l1->next,l2); - return l1; - } - else{ - l2->next=mergeTwoLists(l1,l2->next); - return l2; - } - } -}; diff --git a/cpp/21.cpp b/cpp/21.cpp new file mode 100644 index 0000000..c7e1646 --- /dev/null +++ b/cpp/21.cpp @@ -0,0 +1,40 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { // iteration 8ms +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + auto h = ListNode(0); + auto p = &h; + while (l1 && l2) { + auto& smallP = l1->val < l2->val ? l1 : l2; + p = p->next = smallP; + smallP = smallP->next; + } + p->next = l1 ? l1 : l2; + return h.next; + } +}; +class Solution2 { // recursion +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if (l1 == nullptr) + return l2; + if (l2 == nullptr) + return l1; + if (l1->val < l2->val) { + l1->next = mergeTwoLists(l1->next, l2); + return l1; + } else { + l2->next = mergeTwoLists(l1, l2->next); + return l2; + } + } +}; diff --git a/cpp/211.AddAndSearchWord-DataStructureDesign/sometimesBetter.cpp b/cpp/211.AddAndSearchWord-DataStructureDesign/sometimesBetter.cpp deleted file mode 100644 index 4e26dbb..0000000 --- a/cpp/211.AddAndSearchWord-DataStructureDesign/sometimesBetter.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class WordDictionary { - unordered_map>words; - - bool isEqual(string &a, string &b){ - for(int i = 0; i < a.size(); i++){ - if(b[i] == '.') continue; - if(a[i] != b[i]) return false; - } - return true; - } -public: - /** Initialize your data structure here. */ - WordDictionary() {} - - /** Adds a word into the data structure. */ - void addWord(string word) { - words[word.size()].insert(word); - } - - /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ - bool search(string word) { - if(words[word.size()].find(word)!=words[word.size()].end()) - return true; - for(auto s: words[word.size()]){ - if(isEqual(s, word)) - return true; - } - return false; - } -}; - -/** - * Your WordDictionary object will be instantiated and called as such: - * WordDictionary obj = new WordDictionary(); - * obj.addWord(word); - * bool param_2 = obj.search(word); - */ diff --git a/cpp/211.AddAndSearchWord-DataStructureDesign/trie.cpp b/cpp/211.AddAndSearchWord-DataStructureDesign/trie.cpp deleted file mode 100644 index 5a1cfeb..0000000 --- a/cpp/211.AddAndSearchWord-DataStructureDesign/trie.cpp +++ /dev/null @@ -1,52 +0,0 @@ -class WordDictionary { - struct trie{ - trie():isWord(false){ - memset(this->children,0,sizeof(children)); - } - bool isWord; - trie *children[26]; - }root; -public: - /** Initialize your data structure here. */ - WordDictionary() { - - } - - /** Adds a word into the data structure. */ - void addWord(string word) { - trie *p=&root; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - p->children[offset]=new trie(); - p=p->children[offset]; - } - p->isWord=true; - } - - /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ - bool search(string word) { - trie *p=&root; - return helper(word,0,p); - } - bool helper(string &word,int index,trie *p){ - if(p==nullptr) - return false; - if(index==word.size()) - return p->isWord; - if(word[index]=='.'){ - for(int i=0;i<26;++i) - if(helper(word,index+1,p->children[i])) - return true; - return false; - } - return helper(word,index+1,p->children[word[index]-'a']); - } -}; - -/** - * Your WordDictionary object will be instantiated and called as such: - * WordDictionary obj = new WordDictionary(); - * obj.addWord(word); - * bool param_2 = obj.search(word); - */ diff --git a/cpp/211.cpp b/cpp/211.cpp new file mode 100644 index 0000000..0569be1 --- /dev/null +++ b/cpp/211.cpp @@ -0,0 +1,91 @@ +// sometimesBetter.cpp +class WordDictionary { + unordered_map> words; + + bool isEqual(string &a, string &b) { + for (int i = 0; i < a.size(); i++) { + if (b[i] == '.') + continue; + if (a[i] != b[i]) + return false; + } + return true; + } + +public: + /** Initialize your data structure here. */ + WordDictionary() {} + + /** Adds a word into the data structure. */ + void addWord(string word) { words[word.size()].insert(word); } + + /** Returns if the word is in the data structure. A word could contain the dot + * character '.' to represent any one letter. */ + bool search(string word) { + if (words[word.size()].find(word) != words[word.size()].end()) + return true; + for (auto s : words[word.size()]) { + if (isEqual(s, word)) + return true; + } + return false; + } +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary obj = new WordDictionary(); + * obj.addWord(word); + * bool param_2 = obj.search(word); + */ +// trie.cpp +class WordDictionary2 { + struct trie { + trie() : isWord(false) { memset(this->children, 0, sizeof(children)); } + bool isWord; + trie *children[26]; + } root; + +public: + /** Initialize your data structure here. */ + WordDictionary2() {} + + /** Adds a word into the data structure. */ + void addWord(string word) { + trie *p = &root; + for (auto ch : word) { + int offset = ch - 'a'; + if (p->children[offset] == nullptr) + p->children[offset] = new trie(); + p = p->children[offset]; + } + p->isWord = true; + } + + /** Returns if the word is in the data structure. A word could contain the dot + * character '.' to represent any one letter. */ + bool search(string word) { + trie *p = &root; + return helper(word, 0, p); + } + bool helper(string &word, int index, trie *p) { + if (p == nullptr) + return false; + if (index == word.size()) + return p->isWord; + if (word[index] == '.') { + for (int i = 0; i < 26; ++i) + if (helper(word, index + 1, p->children[i])) + return true; + return false; + } + return helper(word, index + 1, p->children[word[index] - 'a']); + } +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary obj = new WordDictionary(); + * obj.addWord(word); + * bool param_2 = obj.search(word); + */ diff --git a/cpp/212.WordSearchII/dfs-TLE.cpp b/cpp/212.WordSearchII/dfs-TLE.cpp deleted file mode 100644 index 3862a2a..0000000 --- a/cpp/212.WordSearchII/dfs-TLE.cpp +++ /dev/null @@ -1,42 +0,0 @@ -class Solution { - int row,col; - bool search(string &word,int index,vector>&board,int i,int j,vector>&visited){ - if(i<0||i>=row||j<0||j>=col||visited[i][j]||word[index]!=board[i][j]) - return false; - visited[i][j]=true; - if(index==word.size()-1){ - visited[i][j]=false; - return true; - } - if(search(word,index+1,board,i+1,j,visited)|| - search(word,index+1,board,i-1,j,visited)|| - search(word,index+1,board,i,j+1,visited)|| - search(word,index+1,board,i,j-1,visited)){ - visited[i][j]=false; - return true; - } - visited[i][j]=false; - return false; - } -public: - vector findWords(vector>& board, vector& words) { - unordered_map>>position; - row=board.size(); - vectorres; - unordered_set_words(words.begin(),words.end()); - if(row==0) - return res; - col=board[0].size(); - for(int i=0;i(i,j)); - vector>visited(row,vector(col,0)); - for(auto word:_words) - for(auto p:position[word[0]]) - if(search(word,0,board,p.first,p.second,visited)){ - res.emplace_back(word); - break; - } - return res; - } -}; diff --git a/cpp/212.cpp b/cpp/212.cpp new file mode 100644 index 0000000..4381ed7 --- /dev/null +++ b/cpp/212.cpp @@ -0,0 +1,46 @@ +// dfs-TLE.cpp +class Solution { + int row, col; + bool search(string &word, int index, vector> &board, int i, + int j, vector> &visited) { + if (i < 0 || i >= row || j < 0 || j >= col || visited[i][j] || + word[index] != board[i][j]) + return false; + visited[i][j] = true; + if (index == word.size() - 1) { + visited[i][j] = false; + return true; + } + if (search(word, index + 1, board, i + 1, j, visited) || + search(word, index + 1, board, i - 1, j, visited) || + search(word, index + 1, board, i, j + 1, visited) || + search(word, index + 1, board, i, j - 1, visited)) { + visited[i][j] = false; + return true; + } + visited[i][j] = false; + return false; + } + +public: + vector findWords(vector> &board, vector &words) { + unordered_map>> position; + row = board.size(); + vector res; + unordered_set _words(words.begin(), words.end()); + if (row == 0) + return res; + col = board[0].size(); + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + position[board[i][j]].push_back(pair(i, j)); + vector> visited(row, vector(col, 0)); + for (auto word : _words) + for (auto p : position[word[0]]) + if (search(word, 0, board, p.first, p.second, visited)) { + res.emplace_back(word); + break; + } + return res; + } +}; diff --git a/cpp/213.HouseRobberIi.cpp b/cpp/213.HouseRobberIi.cpp deleted file mode 100644 index 0b0f9a1..0000000 --- a/cpp/213.HouseRobberIi.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for House Robber II. -//Memory Usage: 8.6 MB, less than 52.00% of C++ online submissions for House Robber II. -public: - int rob(vector& nums) { - int n = nums.size(); - if (n < 2) return n ? nums[0] : 0; - auto robber=[&nums](int l, int r) { - int take = 0, notake = 0; - for (int i = l; i <= r; i++) { - int notake_temp=notake; - notake = max(take,notake); - take = max(notake_temp + nums[i], take); - } - return max(take,notake); - }; - return max(robber(0, n - 2), robber(1, n - 1)); - } -}; \ No newline at end of file diff --git a/cpp/213.cpp b/cpp/213.cpp new file mode 100644 index 0000000..e10be0a --- /dev/null +++ b/cpp/213.cpp @@ -0,0 +1,21 @@ +class Solution { + // Runtime: 0 ms, faster than 100.00% of C++ online submissions for House + // Robber II. Memory Usage: 8.6 MB, less than 52.00% of C++ online submissions + // for House Robber II. +public: + int rob(vector &nums) { + int n = nums.size(); + if (n < 2) + return n ? nums[0] : 0; + auto robber = [&nums](int l, int r) { + int take = 0, notake = 0; + for (int i = l; i <= r; i++) { + int notake_temp = notake; + notake = max(take, notake); + take = max(notake_temp + nums[i], take); + } + return max(take, notake); + }; + return max(robber(0, n - 2), robber(1, n - 1)); + } +}; \ No newline at end of file diff --git a/cpp/215.KthLargestElementInAnArray/priority_queue.cpp b/cpp/215.KthLargestElementInAnArray/priority_queue.cpp deleted file mode 100644 index c29bee6..0000000 --- a/cpp/215.KthLargestElementInAnArray/priority_queue.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int findKthLargest(vector& nums, int k) { - priority_queue,greater>pq; - for(int i=0;ipq.top()){ - pq.pop(); - pq.push(nums[i]); - } - return pq.top(); - } -}; diff --git a/cpp/215.cpp b/cpp/215.cpp new file mode 100644 index 0000000..5a78549 --- /dev/null +++ b/cpp/215.cpp @@ -0,0 +1,15 @@ +// priority_queue.cpp +class Solution { +public: + int findKthLargest(vector &nums, int k) { + priority_queue, greater> pq; + for (int i = 0; i < k; ++i) + pq.push(nums[i]); + for (int i = k; i < nums.size(); ++i) + if (nums[i] > pq.top()) { + pq.pop(); + pq.push(nums[i]); + } + return pq.top(); + } +}; diff --git a/cpp/216.CombinationSumIII/dfs.cpp b/cpp/216.CombinationSumIII/dfs.cpp deleted file mode 100644 index 8329989..0000000 --- a/cpp/216.CombinationSumIII/dfs.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { - vector>result; - int targetK; - int targetN; -public: - vector> combinationSum3(int k, int n) { - targetK=k; - if(n>45||n<=0)return result; - targetN=n; - dfs(0,1,0,vector()); - return result; - } - void dfs(int k,int n,int sum,vectornum){ - if(sum==targetN&&k==targetK){ - result.push_back(num); - return; - } - if(k==targetK||n>=10||sum>=targetN) - return; - dfs(k,n+1,sum,num); - num.push_back(n); - dfs(k+1,n+1,sum+n,num); - } -}; diff --git a/cpp/216.cpp b/cpp/216.cpp new file mode 100644 index 0000000..2638535 --- /dev/null +++ b/cpp/216.cpp @@ -0,0 +1,27 @@ +// dfs.cpp +class Solution { + vector> result; + int targetK; + int targetN; + +public: + vector> combinationSum3(int k, int n) { + targetK = k; + if (n > 45 || n <= 0) + return result; + targetN = n; + dfs(0, 1, 0, vector()); + return result; + } + void dfs(int k, int n, int sum, vector num) { + if (sum == targetN && k == targetK) { + result.push_back(num); + return; + } + if (k == targetK || n >= 10 || sum >= targetN) + return; + dfs(k, n + 1, sum, num); + num.push_back(n); + dfs(k + 1, n + 1, sum + n, num); + } +}; diff --git a/cpp/217.ContainsDuplicate/hash-36ms.cpp b/cpp/217.ContainsDuplicate/hash-36ms.cpp deleted file mode 100644 index 03b8656..0000000 --- a/cpp/217.ContainsDuplicate/hash-36ms.cpp +++ /dev/null @@ -1,7 +0,0 @@ -class Solution { -public: - bool containsDuplicate(vector& nums) { - set myset(nums.begin(),nums.end()); - return myset.size() < nums.size(); - } -}; diff --git a/cpp/217.cpp b/cpp/217.cpp new file mode 100644 index 0000000..d010b9f --- /dev/null +++ b/cpp/217.cpp @@ -0,0 +1,8 @@ +// hash-36ms.cpp +class Solution { +public: + bool containsDuplicate(vector &nums) { + set myset(nums.begin(), nums.end()); + return myset.size() < nums.size(); + } +}; diff --git a/cpp/219.ContainsDuplicateII/hash-33ms.cpp b/cpp/219.ContainsDuplicateII/hash-33ms.cpp deleted file mode 100644 index 0645950..0000000 --- a/cpp/219.ContainsDuplicateII/hash-33ms.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - bool containsNearbyDuplicate(vector& nums, int k) { - unordered_mapmap; - int len=nums.size(); - for(int i=0;i &nums, int k) { + unordered_map map; + int len = nums.size(); + for (int i = 0; i < len; ++i) + if (map.find(nums[i]) != map.end()) { + if (abs(i - map[nums[i]]) <= k) + return 1; + map[nums[i]] = i; + } else + map[nums[i]] = i; + return 0; + } +}; diff --git a/cpp/22.GenerateParentheses/dfs.cpp b/cpp/22.GenerateParentheses/dfs.cpp deleted file mode 100644 index b5bfdee..0000000 --- a/cpp/22.GenerateParentheses/dfs.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - vector generateParenthesis(int n) { - vectorres; - dfs(res,"",0,0,n); - return res; - } - void dfs(vector&res,string cur,int left,int right,int n){ - if(right>left||left>n) - return; - if(left+right==n*2){ - res.push_back(cur); - return; - } - dfs(res,cur+"(",left+1,right,n); - dfs(res,cur+")",left,right+1,n); - } -}; diff --git a/cpp/22.cpp b/cpp/22.cpp new file mode 100644 index 0000000..4d89b88 --- /dev/null +++ b/cpp/22.cpp @@ -0,0 +1,27 @@ +// dfs.cpp +class Solution { + void dfs(vector& res, string& cur, int left, int right, int n) { + if (left + right == n * 2) { + res.push_back(cur); + return; + } + if (left < n) { + cur += '('; + dfs(res, cur, left + 1, right, n); + cur.pop_back(); + } + if (left > right) { + cur += ')'; + dfs(res, cur, left, right + 1, n); + cur.pop_back(); + } + } + +public: + vector generateParenthesis(int n) { + vector res; + string s; + dfs(res, s, 0, 0, n); + return res; + } +}; \ No newline at end of file diff --git a/cpp/220.ContainsDuplicateIii.cpp b/cpp/220.ContainsDuplicateIii.cpp deleted file mode 100644 index 9ffef7b..0000000 --- a/cpp/220.ContainsDuplicateIii.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -//Runtime: 20 ms, faster than 71.64% of C++ online submissions for Contains Duplicate III. -//Memory Usage: 10.9 MB, less than 32.96% of C++ online submissions for Contains Duplicate III. -public: - bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { - if (k < 1 or t < 0) return false; - sets; - for(int i=0;ik) - s.erase(nums[i-k-1]); - auto [it,success]=s.insert(nums[i]); - if(not success) - return true; - if(it!=begin(s) and abs((long long)*prev(it)-(long long)*it)<=t) - return true; - if(next(it)!=end(s) and abs((long long)*next(it)-(long long)*it)<=t) - return true; - } - return false; - } -}; \ No newline at end of file diff --git a/cpp/220.cpp b/cpp/220.cpp new file mode 100644 index 0000000..530047f --- /dev/null +++ b/cpp/220.cpp @@ -0,0 +1,24 @@ +class Solution { + // Runtime: 20 ms, faster than 71.64% of C++ online submissions for Contains + // Duplicate III. Memory Usage: 10.9 MB, less than 32.96% of C++ online + // submissions for Contains Duplicate III. +public: + bool containsNearbyAlmostDuplicate(vector &nums, int k, int t) { + if (k < 1 or t < 0) + return false; + set s; + for (int i = 0; i < nums.size(); ++i) { + if (i > k) + s.erase(nums[i - k - 1]); + auto [it, success] = s.insert(nums[i]); + if (not success) + return true; + if (it != begin(s) and abs((long long)*prev(it) - (long long)*it) <= t) + return true; + if (next(it) != end(s) and + abs((long long)*next(it) - (long long)*it) <= t) + return true; + } + return false; + } +}; \ No newline at end of file diff --git a/cpp/221.MaximalSquare/dp_timeOmnspaceOmn.cpp b/cpp/221.MaximalSquare/dp_timeOmnspaceOmn.cpp deleted file mode 100644 index 2b82f2d..0000000 --- a/cpp/221.MaximalSquare/dp_timeOmnspaceOmn.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { -public: - int maximalSquare(vector>& matrix) { - int row=matrix.size(); - if(row==0)return 0; - int col=matrix[0].size(),max=0; - vector>dp(row,vector(col,0)); - for(int i=0;idp[i][0]?max:dp[i][0]; - } - for(int i=0;idp[0][i]?max:dp[0][i]; - } - for(int i=1;idp[i][j]?max:dp[i][j]; - } - return max*max; - } - int min(int a,int b,int c){ - if(a>b) - return b> &matrix) { + int row = matrix.size(); + if (row == 0) + return 0; + int col = matrix[0].size(), max = 0; + vector> dp(row, vector(col, 0)); + for (int i = 0; i < row; ++i) { + dp[i][0] = matrix[i][0] - '0'; + max = max > dp[i][0] ? max : dp[i][0]; + } + for (int i = 0; i < col; ++i) { + dp[0][i] = matrix[0][i] - '0'; + max = max > dp[0][i] ? max : dp[0][i]; + } + for (int i = 1; i < row; ++i) + for (int j = 1; j < col; ++j) + if (matrix[i][j] == '1') { + dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1]) + 1; + max = max > dp[i][j] ? max : dp[i][j]; + } + return max * max; + } + int min(int a, int b, int c) { + if (a > b) + return b < c ? b : c; + return a < c ? a : c; + } +}; diff --git a/cpp/222.CountCompleteTreeNodes/recursion.cpp b/cpp/222.CountCompleteTreeNodes/recursion.cpp deleted file mode 100644 index d429f07..0000000 --- a/cpp/222.CountCompleteTreeNodes/recursion.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - int countNodes(TreeNode* root) { - if(!root) - return 0; - TreeNode *l=root,*r=root; - int ld=0,rd=0; - while(l){ - ++ld; - l=l->left; - } - while(r){ - ++rd; - r=r->right; - } - if(ld==rd) - return (1<left)+countNodes(root->right); - } -}; diff --git a/cpp/222.CountCompleteTreeNodes/somethingFaster.cpp b/cpp/222.CountCompleteTreeNodes/somethingFaster.cpp deleted file mode 100644 index 795b9f6..0000000 --- a/cpp/222.CountCompleteTreeNodes/somethingFaster.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - int countNodes(TreeNode* root) { - int Deep = 0, result = 0; - if (!root) return 0; - TreeNode* temp = root, *cur = root; - while(temp) { - Deep++; - temp=temp->left; - } - int parentHigh = Deep;//父节点的高度,也就是当前节点的高度 - - while (parentHigh>1) {//parentHigh表示当前节点,因为要计算子节点即curHigh,所以不能等于0 - cur = root->left; - int curHigh = parentHigh-1;//当前节点的子节点高度 - for (int i = curHigh; i > 1; i--) cur = cur->right; - if (cur) { - root = root->right; - result += 1<<(curHigh-1); - }else{ - root=root->left; - } - parentHigh--; - } - if (root) result++; - return result + (1<<(Deep-1))-1; - } - - -}; diff --git a/cpp/222.cpp b/cpp/222.cpp new file mode 100644 index 0000000..8451b02 --- /dev/null +++ b/cpp/222.cpp @@ -0,0 +1,73 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int countNodes(TreeNode *root) { + if (!root) + return 0; + TreeNode *l = root, *r = root; + int ld = 0, rd = 0; + while (l) { + ++ld; + l = l->left; + } + while (r) { + ++rd; + r = r->right; + } + if (ld == rd) + return (1 << ld) - 1; + return 1 + countNodes(root->left) + countNodes(root->right); + } +}; +// somethingFaster.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution2 { +public: + int countNodes(TreeNode *root) { + int Deep = 0, result = 0; + if (!root) + return 0; + TreeNode *temp = root, *cur = root; + while (temp) { + Deep++; + temp = temp->left; + } + int parentHigh = Deep; //父节点的高度,也就是当前节点的高度 + + while ( + parentHigh > + 1) { // parentHigh表示当前节点,因为要计算子节点即curHigh,所以不能等于0 + cur = root->left; + int curHigh = parentHigh - 1; //当前节点的子节点高度 + for (int i = curHigh; i > 1; i--) + cur = cur->right; + if (cur) { + root = root->right; + result += 1 << (curHigh - 1); + } else { + root = root->left; + } + parentHigh--; + } + if (root) + result++; + return result + (1 << (Deep - 1)) - 1; + } +}; diff --git a/cpp/223.RectangleArea/decreaseoverlap.cpp b/cpp/223.RectangleArea/decreaseoverlap.cpp deleted file mode 100644 index 9d14fa7..0000000 --- a/cpp/223.RectangleArea/decreaseoverlap.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { - int sum=(C-A)*(D-B)+(G-E)*(H-F); - int left=max(A,E); - int right=min(C,G); - int up=min(D,H); - int down=max(B,F); - if(up>down&&right>left) - sum-=(up-down)*(right-left); - return sum; - } -}; diff --git a/cpp/223.cpp b/cpp/223.cpp new file mode 100644 index 0000000..9a40871 --- /dev/null +++ b/cpp/223.cpp @@ -0,0 +1,14 @@ +// decreaseoverlap.cpp +class Solution { +public: + int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { + int sum = (C - A) * (D - B) + (G - E) * (H - F); + int left = max(A, E); + int right = min(C, G); + int up = min(D, H); + int down = max(B, F); + if (up > down && right > left) + sum -= (up - down) * (right - left); + return sum; + } +}; diff --git a/cpp/225.ImplementStackUsingQueues/notBest-3ms.cpp b/cpp/225.ImplementStackUsingQueues/notBest-3ms.cpp deleted file mode 100644 index 596a6dc..0000000 --- a/cpp/225.ImplementStackUsingQueues/notBest-3ms.cpp +++ /dev/null @@ -1,45 +0,0 @@ -class MyStack { - queueqe; -public: - /** Initialize your data structure here. */ - MyStack() { - - } - - /** Push element x onto stack. */ - void push(int x) { - int size=qe.size(),i=0; - qe.push(x); - while(i qe; + +public: + /** Initialize your data structure here. */ + MyStack() {} + + /** Push element x onto stack. */ + void push(int x) { + int size = qe.size(), i = 0; + qe.push(x); + while (i < size) { + qe.push(qe.front()); + qe.pop(); + ++i; + } + } + + /** Removes the element on top of the stack and returns that element. */ + int pop() { + int temp = qe.front(); + qe.pop(); + return temp; + } + + /** Get the top element. */ + int top() { return qe.front(); } + + /** Returns whether the stack is empty. */ + bool empty() { return qe.empty(); } +}; + +/** + * Your MyStack object will be instantiated and called as such: + * MyStack obj = new MyStack(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.top(); + * bool param_4 = obj.empty(); + */ diff --git a/cpp/226.InvertBinaryTree/recursion-3ms.cpp b/cpp/226.InvertBinaryTree/recursion-3ms.cpp deleted file mode 100644 index 63bd8a8..0000000 --- a/cpp/226.InvertBinaryTree/recursion-3ms.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* invertTree(TreeNode* root) { - if(root==NULL)return NULL; - TreeNode *left=root->left,*right=root->right; - root->left=right; - root->right=left; - invertTree(root->left); - invertTree(root->right); - return root; - } -}; diff --git a/cpp/226.cpp b/cpp/226.cpp new file mode 100644 index 0000000..1552929 --- /dev/null +++ b/cpp/226.cpp @@ -0,0 +1,23 @@ +// recursion-3ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode *invertTree(TreeNode *root) { + if (root == NULL) + return NULL; + TreeNode *left = root->left, *right = root->right; + root->left = right; + root->right = left; + invertTree(root->left); + invertTree(root->right); + return root; + } +}; diff --git a/cpp/228.SummaryRanges/onepass.cpp b/cpp/228.SummaryRanges/onepass.cpp deleted file mode 100644 index df361a8..0000000 --- a/cpp/228.SummaryRanges/onepass.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - vector summaryRanges(vector& nums) { - vectorres; - if(nums.size()==0)return res; - string s=to_string(nums[0]); - for(int i=1;i summaryRanges(vector &nums) { + vector res; + if (nums.size() == 0) + return res; + string s = to_string(nums[0]); + for (int i = 1; i < nums.size(); ++i) + if (nums[i] != nums[i - 1] + 1) { + if (to_string(nums[i - 1]) != s) + s += "->" + to_string(nums[i - 1]); + res.push_back(s); + s = to_string(nums[i]); + } + if (to_string(nums[nums.size() - 1]) != s) + s += "->" + to_string(nums[nums.size() - 1]); + res.push_back(s); + return res; + } +}; diff --git a/cpp/229.MajorityElementIi.cpp b/cpp/229.MajorityElementIi.cpp deleted file mode 100644 index f1297ee..0000000 --- a/cpp/229.MajorityElementIi.cpp +++ /dev/null @@ -1,40 +0,0 @@ -class Solution { -//Runtime: 12 ms, faster than 97.03% of C++ online submissions for Majority Element II. -//Memory Usage: 10.5 MB, less than 85.68% of C++ online submissions for Majority Element II. -public: - vector majorityElement(vector& nums) { - int count1=0, count2=0; - int result1=0, result2=1; - for(int num:nums){ - if(num==result1) - count1++; - else if(num==result2) - count2++; - else if(count1==0) { - result1=num; - count1=1; - } - else if(count2==0) { - result2=num; - count2=1; - } - else { - count1--; - count2--; - } - } - count1=count2=0; - for(int num:nums){ - if(num==result1) - count1++; - else if(num==result2) - count2++; - } - vector ret; - if(count1>nums.size()/3) - ret.push_back(result1); - if(count2>nums.size()/3) - ret.push_back(result2); - return ret; - } -}; \ No newline at end of file diff --git a/cpp/229.cpp b/cpp/229.cpp new file mode 100644 index 0000000..2d15544 --- /dev/null +++ b/cpp/229.cpp @@ -0,0 +1,39 @@ +class Solution { + // Runtime: 12 ms, faster than 97.03% of C++ online submissions for Majority + // Element II. Memory Usage: 10.5 MB, less than 85.68% of C++ online + // submissions for Majority Element II. +public: + vector majorityElement(vector &nums) { + int count1 = 0, count2 = 0; + int result1 = 0, result2 = 1; + for (int num : nums) { + if (num == result1) + count1++; + else if (num == result2) + count2++; + else if (count1 == 0) { + result1 = num; + count1 = 1; + } else if (count2 == 0) { + result2 = num; + count2 = 1; + } else { + count1--; + count2--; + } + } + count1 = count2 = 0; + for (int num : nums) { + if (num == result1) + count1++; + else if (num == result2) + count2++; + } + vector ret; + if (count1 > nums.size() / 3) + ret.push_back(result1); + if (count2 > nums.size() / 3) + ret.push_back(result2); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/23.MergeKSortedLists/make_heap.cpp b/cpp/23.MergeKSortedLists/make_heap.cpp deleted file mode 100644 index 7222b4c..0000000 --- a/cpp/23.MergeKSortedLists/make_heap.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - static bool heapComp(ListNode* a, ListNode* b) { - return a->val > b->val; - } - ListNode* mergeKLists(vector& lists) { //make_heap - ListNode head(0); - ListNode *curNode = &head; - vector v; - for(int i =0; i heap data strcture - - while(v.size()>0){ - curNode->next=v.front(); - pop_heap(v.begin(), v.end(), heapComp); - v.pop_back(); - curNode = curNode->next; - if(curNode->next) { - v.push_back(curNode->next); - push_heap(v.begin(), v.end(), heapComp); - } - } - return head.next; - } -}; diff --git a/cpp/23.MergeKSortedLists/priorityQueue.cpp b/cpp/23.MergeKSortedLists/priorityQueue.cpp deleted file mode 100644 index b0a8ffb..0000000 --- a/cpp/23.MergeKSortedLists/priorityQueue.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - struct compare { - bool operator()(const ListNode* l, const ListNode* r) { - return l->val > r->val; - } - }; - priority_queue,compare>pq; -public: - ListNode* mergeKLists(vector& lists) { - ListNode *p=new ListNode(0),*tail=p; - for(int i=0;inext=pq.top(); - tail=tail->next; - pq.pop(); - if(tail->next!=NULL) - pq.push(tail->next); - } - return p->next; - } -}; diff --git a/cpp/23.cpp b/cpp/23.cpp new file mode 100644 index 0000000..bd07b93 --- /dev/null +++ b/cpp/23.cpp @@ -0,0 +1,60 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +// make_heap.cpp +class Solution { +public: + static bool heapComp(ListNode* a, ListNode* b) { return a->val > b->val; } + ListNode* mergeKLists(vector& lists) { + ListNode head(0); + auto curNode = &head; + vector v; + for (int i = 0; i < lists.size(); i++) { + if (lists[i]) + v.push_back(lists[i]); + } + ranges::make_heap(v, heapComp); // vector -> heap data strcture + + while (v.size() > 0) { + curNode = curNode->next = v.front(); + ranges::pop_heap(v, heapComp); + v.pop_back(); + if (curNode->next) { + v.push_back(curNode->next); + ranges::push_heap(v, heapComp); + } + } + return head.next; + } +}; +// priorityQueue.cpp +class Solution2 { + struct compare { + bool operator()(const ListNode* l, const ListNode* r) { + return l->val > r->val; + } + }; + +public: + ListNode* mergeKLists(vector& lists) { + priority_queue, compare> pq; + ListNode p(0), *tail = &p; + for (int i = 0; i < lists.size(); ++i) + if (lists[i]) + pq.push(lists[i]); + while (!pq.empty()) { + tail = tail->next = pq.top(); + pq.pop(); + if (tail->next) + pq.push(tail->next); + } + return p.next; + } +}; diff --git a/cpp/230.KthSmallestElementInABST/inorderTraversal.cpp b/cpp/230.KthSmallestElementInABST/inorderTraversal.cpp deleted file mode 100644 index 07be226..0000000 --- a/cpp/230.KthSmallestElementInABST/inorderTraversal.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int value; -public: - int kthSmallest(TreeNode* root, int &k) { - if(root==NULL)return 0; - kthSmallest(root->left,k); - if(k-->0)value=root->val; - else return value; - kthSmallest(root->right,k); - return value; - } -}; diff --git a/cpp/230.cpp b/cpp/230.cpp new file mode 100644 index 0000000..5f63b54 --- /dev/null +++ b/cpp/230.cpp @@ -0,0 +1,26 @@ +// inorderTraversal.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int value; + +public: + int kthSmallest(TreeNode *root, int &k) { + if (root == NULL) + return 0; + kthSmallest(root->left, k); + if (k-- > 0) + value = root->val; + else + return value; + kthSmallest(root->right, k); + return value; + } +}; diff --git a/cpp/231.PowerOfTwo/bits-feature-3ms.cpp b/cpp/231.PowerOfTwo/bits-feature-3ms.cpp deleted file mode 100644 index 5339959..0000000 --- a/cpp/231.PowerOfTwo/bits-feature-3ms.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - bool isPowerOfTwo(int n) { - return !(n&(n-1)) && (n>0) ; - } -}; diff --git a/cpp/231.cpp b/cpp/231.cpp new file mode 100644 index 0000000..c2b9093 --- /dev/null +++ b/cpp/231.cpp @@ -0,0 +1,5 @@ +// bits-feature-3ms.cpp +class Solution { +public: + bool isPowerOfTwo(int n) { return !(n & (n - 1)) && (n > 0); } +}; diff --git a/cpp/232.ImplementQueueUsingStacks/doubleStacks-0ms.cpp b/cpp/232.ImplementQueueUsingStacks/doubleStacks-0ms.cpp deleted file mode 100644 index d539287..0000000 --- a/cpp/232.ImplementQueueUsingStacks/doubleStacks-0ms.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class MyQueue { - stackin; - stackout; -public: - /** Initialize your data structure here. */ - MyQueue() { - - } - - /** Push element x to the back of queue. */ - void push(int x) { - in.push(x); - } - - /** Removes the element from in front of queue and returns that element. */ - int pop() { - if(out.empty()){ - while(!in.empty()){ - out.push(in.top()); - in.pop(); - } - } - int temp=out.top(); - out.pop(); - return temp; - } - - /** Get the front element. */ - int peek() { - - if(out.empty()){ - while(!in.empty()){ - out.push(in.top()); - in.pop(); - } - } - return out.top(); - } - - /** Returns whether the queue is empty. */ - bool empty() { - return in.empty()==1 && out.empty()==1 ; - } -}; - -/** - * Your MyQueue object will be instantiated and called as such: - * MyQueue obj = new MyQueue(); - * obj.push(x); - * int param_2 = obj.pop(); - * int param_3 = obj.peek(); - * bool param_4 = obj.empty(); - */ diff --git a/cpp/232.cpp b/cpp/232.cpp new file mode 100644 index 0000000..fa75e7d --- /dev/null +++ b/cpp/232.cpp @@ -0,0 +1,49 @@ +// doubleStacks-0ms.cpp +class MyQueue { + stack in; + stack out; + +public: + /** Initialize your data structure here. */ + MyQueue() {} + + /** Push element x to the back of queue. */ + void push(int x) { in.push(x); } + + /** Removes the element from in front of queue and returns that element. */ + int pop() { + if (out.empty()) { + while (!in.empty()) { + out.push(in.top()); + in.pop(); + } + } + int temp = out.top(); + out.pop(); + return temp; + } + + /** Get the front element. */ + int peek() { + + if (out.empty()) { + while (!in.empty()) { + out.push(in.top()); + in.pop(); + } + } + return out.top(); + } + + /** Returns whether the queue is empty. */ + bool empty() { return in.empty() == 1 && out.empty() == 1; } +}; + +/** + * Your MyQueue object will be instantiated and called as such: + * MyQueue obj = new MyQueue(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.peek(); + * bool param_4 = obj.empty(); + */ diff --git a/cpp/234.PalindromeLinkedList/timeOnSpaceO1.cpp b/cpp/234.PalindromeLinkedList/timeOnSpaceO1.cpp deleted file mode 100644 index e7fe852..0000000 --- a/cpp/234.PalindromeLinkedList/timeOnSpaceO1.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - bool isPalindrome(ListNode* head) { - if(head==NULL)return 1; - if(head->next==NULL)return 1; - ListNode *p1=head,*p2=head; - while(p2->next!=NULL){ - p2=p2->next; - if(p2->next==NULL){ - break; - } - p2=p2->next; - p1=p1->next; - } - p2=reverse(NULL,p1->next); - p1->next=NULL; - while(head!=NULL&&p2!=NULL){ - if(head->val!=p2->val) - return 0; - head=head->next; - p2=p2->next; - } - return 1; - } - ListNode* reverse(ListNode *pre,ListNode *now){ - ListNode *next=now->next; - now->next=pre; - if(next==NULL) - return now; - return reverse(now,next); - } -}; diff --git a/cpp/234.cpp b/cpp/234.cpp new file mode 100644 index 0000000..ffee2c0 --- /dev/null +++ b/cpp/234.cpp @@ -0,0 +1,43 @@ +// timeOnSpaceO1.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool isPalindrome(ListNode *head) { + if (head == NULL) + return 1; + if (head->next == NULL) + return 1; + ListNode *p1 = head, *p2 = head; + while (p2->next != NULL) { + p2 = p2->next; + if (p2->next == NULL) { + break; + } + p2 = p2->next; + p1 = p1->next; + } + p2 = reverse(NULL, p1->next); + p1->next = NULL; + while (head != NULL && p2 != NULL) { + if (head->val != p2->val) + return 0; + head = head->next; + p2 = p2->next; + } + return 1; + } + ListNode *reverse(ListNode *pre, ListNode *now) { + ListNode *next = now->next; + now->next = pre; + if (next == NULL) + return now; + return reverse(now, next); + } +}; diff --git a/cpp/235.LowestCommonAncestorOfABinarySearchTree/recursion.cpp b/cpp/235.LowestCommonAncestorOfABinarySearchTree/recursion.cpp deleted file mode 100644 index 531b4bd..0000000 --- a/cpp/235.LowestCommonAncestorOfABinarySearchTree/recursion.cpp +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - if(root==p||root==q)return root; - if( root->val<=p->val &&root->val<=q->val)return lowestCommonAncestor(root->right,p,q); - if( root->val>=p->val &&root->val>=q->val)return lowestCommonAncestor(root->left,p,q); - return root; - } -}; diff --git a/cpp/235.cpp b/cpp/235.cpp new file mode 100644 index 0000000..b6b4e31 --- /dev/null +++ b/cpp/235.cpp @@ -0,0 +1,22 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { + if (root == p || root == q) + return root; + if (root->val <= p->val && root->val <= q->val) + return lowestCommonAncestor(root->right, p, q); + if (root->val >= p->val && root->val >= q->val) + return lowestCommonAncestor(root->left, p, q); + return root; + } +}; diff --git a/cpp/236.LowestCommonAncestorOfABinaryTree/recursion.cpp b/cpp/236.LowestCommonAncestorOfABinaryTree/recursion.cpp deleted file mode 100644 index a88afb5..0000000 --- a/cpp/236.LowestCommonAncestorOfABinaryTree/recursion.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - if(!root||root==p||root==q) - return root; - TreeNode *l=lowestCommonAncestor(root->left,p,q); - TreeNode *r=lowestCommonAncestor(root->right,p,q); - if(l&&r) - return root; - return l?l:r; - } -}; diff --git a/cpp/236.cpp b/cpp/236.cpp new file mode 100644 index 0000000..dafd2ed --- /dev/null +++ b/cpp/236.cpp @@ -0,0 +1,22 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { + if (!root || root == p || root == q) + return root; + TreeNode *l = lowestCommonAncestor(root->left, p, q); + TreeNode *r = lowestCommonAncestor(root->right, p, q); + if (l && r) + return root; + return l ? l : r; + } +}; diff --git a/cpp/237.DeleteNodeInALinkedList/O1.cpp b/cpp/237.DeleteNodeInALinkedList/O1.cpp deleted file mode 100644 index deea99c..0000000 --- a/cpp/237.DeleteNodeInALinkedList/O1.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - void deleteNode(ListNode* node) { - ListNode* next=node->next; - *node=*next; - delete next; - } -}; diff --git a/cpp/237.cpp b/cpp/237.cpp new file mode 100644 index 0000000..d8a1ce7 --- /dev/null +++ b/cpp/237.cpp @@ -0,0 +1,17 @@ +// O1.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + void deleteNode(ListNode *node) { + ListNode *next = node->next; + *node = *next; + delete next; + } +}; diff --git a/cpp/238.ProductOfArrayExceptSelf/notbest-75ms.cpp b/cpp/238.ProductOfArrayExceptSelf/notbest-75ms.cpp deleted file mode 100644 index adc24cd..0000000 --- a/cpp/238.ProductOfArrayExceptSelf/notbest-75ms.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - vector productExceptSelf(vector& nums) { - int n=nums.size(); - vectorpre(n,nums[0]); - vectorlast(n,nums[n-1]); - for(int i=1;i=0;--i) - last[i]=nums[i]*last[i+1]; - vectorresult(n); - for(int i=1;i productExceptSelf(vector &nums) { + int n = nums.size(); + vector pre(n, nums[0]); + vector last(n, nums[n - 1]); + for (int i = 1; i < n; ++i) + pre[i] = nums[i] * pre[i - 1]; + for (int i = n - 2; i >= 0; --i) + last[i] = nums[i] * last[i + 1]; + vector result(n); + for (int i = 1; i < n - 1; ++i) + result[i] = pre[i - 1] * last[i + 1]; + result[0] = last[1]; + result[n - 1] = pre[n - 2]; + return result; + } +}; diff --git a/cpp/239.SlidingWindowMaximum.cpp b/cpp/239.SlidingWindowMaximum.cpp deleted file mode 100644 index 4e50266..0000000 --- a/cpp/239.SlidingWindowMaximum.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution { -//Runtime: 60 ms, faster than 67.00% of C++ online submissions for Sliding Window Maximum. -//Memory Usage: 13.4 MB, less than 27.55% of C++ online submissions for Sliding Window Maximum. -public: - vector maxSlidingWindow(vector& nums, int k) { - if(k>=nums.size()&&nums.size()) - return {*max_element(begin(nums),end(nums))}; - if(k<=0) - return {}; - deque dq; - vectorret; - for(int i=0;i=nums[i]) - dq.push_back(nums[i]); - else{ - while(dq.size() and dq.back()=k){ - ret.push_back(dq.front()); - if(nums[i+1-k]==dq.front()) - dq.pop_front(); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/cpp/239.cpp b/cpp/239.cpp new file mode 100644 index 0000000..c5f0da7 --- /dev/null +++ b/cpp/239.cpp @@ -0,0 +1,29 @@ +class Solution { + // Runtime: 60 ms, faster than 67.00% of C++ online submissions for Sliding + // Window Maximum. Memory Usage: 13.4 MB, less than 27.55% of C++ online + // submissions for Sliding Window Maximum. +public: + vector maxSlidingWindow(vector &nums, int k) { + if (k >= nums.size() && nums.size()) + return {*max_element(begin(nums), end(nums))}; + if (k <= 0) + return {}; + deque dq; + vector ret; + for (int i = 0; i < nums.size(); ++i) { + if (dq.empty() or dq.back() >= nums[i]) + dq.push_back(nums[i]); + else { + while (dq.size() and dq.back() < nums[i]) + dq.pop_back(); + dq.push_back(nums[i]); + } + if (i + 1 >= k) { + ret.push_back(dq.front()); + if (nums[i + 1 - k] == dq.front()) + dq.pop_front(); + } + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/24.SwapNodesInPairs.cpp b/cpp/24.SwapNodesInPairs.cpp deleted file mode 100644 index a7196d4..0000000 --- a/cpp/24.SwapNodesInPairs.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { // recursion 0ms -public: - ListNode* swapPairs(ListNode* head) { - function swap= [&swap](ListNode* pre,ListNode *a,ListNode* b,ListNode *cur){ - if(a&&b){ - b->next=a; - a->next=cur; - if(pre) - pre->next=b; - } - if(cur&&cur->next) - swap(a,cur,cur->next,cur->next->next); - return b; - }; - if(head&&head->next) - return swap(nullptr,head,head->next,head->next->next); - return head; - } -}; -class Solution { // iteration 4ms -public: - ListNode* swapPairs(ListNode* head) { - if(!head||!head->next) - return head; - auto h=ListNode(0); - h.next=head; - auto p=&h; - while(p->next&&p->next->next){ - auto l=p->next,r=p->next->next; - auto next=r->next; - p->next=r; - r->next=l; - l->next=next; - p=l; - } - return h.next; - } -}; \ No newline at end of file diff --git a/cpp/24.cpp b/cpp/24.cpp new file mode 100644 index 0000000..8a7d573 --- /dev/null +++ b/cpp/24.cpp @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { // recursion +public: + ListNode* swapPairs(ListNode* head) { + function swap = + [&swap](ListNode* a, ListNode* b, ListNode* cur) { + if (a && b) { + b->next = a; + a->next = cur; + } + if (cur && cur->next) + a->next = swap(cur, cur->next, cur->next->next); + return b; + }; + if (head && head->next) + return swap(head, head->next, head->next->next); + return head; + } +}; +class Solution2 { // iteration +public: + ListNode* swapPairs(ListNode* head) { + if (!head || !head->next) + return head; + auto h = ListNode(0, head); + auto p = &h; + while (p->next && p->next->next) { + auto l = p->next, r = p->next->next; + auto next = r->next; + p->next = r; + r->next = l; + l->next = next; + p = l; + } + return h.next; + } +}; \ No newline at end of file diff --git a/cpp/240.SearchA2DMatrixII/1-69ms.cpp b/cpp/240.SearchA2DMatrixII/1-69ms.cpp deleted file mode 100644 index 7d05eb5..0000000 --- a/cpp/240.SearchA2DMatrixII/1-69ms.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - int row=matrix.size(); - if(row==0)return 0; - int col=matrix[0].size(); - int j=col-1,i=0; - while(i=0){ - if(matrix[i][j]>target) - --j; - else if(matrix[i][j]> &matrix, int target) { + int row = matrix.size(); + if (row == 0) + return 0; + int col = matrix[0].size(); + int j = col - 1, i = 0; + while (i < row && j >= 0) { + if (matrix[i][j] > target) + --j; + else if (matrix[i][j] < target) + ++i; + else + return 1; + } + return 0; + } +}; \ No newline at end of file diff --git a/cpp/241.DifferentWaysToAddParentheses.cpp b/cpp/241.DifferentWaysToAddParentheses.cpp deleted file mode 100644 index 65bafae..0000000 --- a/cpp/241.DifferentWaysToAddParentheses.cpp +++ /dev/null @@ -1,39 +0,0 @@ -class Solution { -//Runtime: 0 ms Your runtime beats 100.00 % of cpp submissions -//Memory Usage: 9.1 MB Your memory usage beats 95.63 % of cpp submissions. -public: - vector diffWaysToCompute(string input) { - unordered_map> dpMap; - functionrecursion=[&](string_view input) { - vector result; - for (int i = 0; i < input.size(); i++) { - char cur = input[i]; - if (cur == '+' || cur == '-' || cur == '*') { - auto substr = input.substr(0, i); - if (dpMap.find(substr) == dpMap.end()) - recursion(substr); - auto &result1 = dpMap[substr]; - substr = input.substr(i + 1); - if (dpMap.find(substr) == dpMap.end()) - recursion(substr); - auto &result2 = dpMap[substr]; - for (auto n1 : result1) - for (auto n2 : result2) - switch(cur){ - case '+':result.push_back(n1 + n2);break; - case '-':result.push_back(n1 - n2);break; - case '*':result.push_back(n1 * n2);break; - } - } - } - if (result.empty()){ - int res; - from_chars(input.data(), input.data() + input.size(), res); - result.push_back(res); - } - dpMap[input]=move(result); - }; - recursion(input); - return dpMap[input]; - } -}; \ No newline at end of file diff --git a/cpp/241.cpp b/cpp/241.cpp new file mode 100644 index 0000000..5a70731 --- /dev/null +++ b/cpp/241.cpp @@ -0,0 +1,45 @@ +class Solution { + // Runtime: 0 ms Your runtime beats 100.00 % of cpp submissions + // Memory Usage: 9.1 MB Your memory usage beats 95.63 % of cpp submissions. +public: + vector diffWaysToCompute(string input) { + unordered_map> dpMap; + function recursion = [&](string_view input) { + vector result; + for (int i = 0; i < input.size(); i++) { + char cur = input[i]; + if (cur == '+' || cur == '-' || cur == '*') { + auto substr = input.substr(0, i); + if (dpMap.find(substr) == dpMap.end()) + recursion(substr); + auto &result1 = dpMap[substr]; + substr = input.substr(i + 1); + if (dpMap.find(substr) == dpMap.end()) + recursion(substr); + auto &result2 = dpMap[substr]; + for (auto n1 : result1) + for (auto n2 : result2) + switch (cur) { + case '+': + result.push_back(n1 + n2); + break; + case '-': + result.push_back(n1 - n2); + break; + case '*': + result.push_back(n1 * n2); + break; + } + } + } + if (result.empty()) { + int res; + from_chars(input.data(), input.data() + input.size(), res); + result.push_back(res); + } + dpMap[input] = move(result); + }; + recursion(input); + return dpMap[input]; + } +}; \ No newline at end of file diff --git a/cpp/242.ValidAnagram/hash.cpp b/cpp/242.ValidAnagram/hash.cpp deleted file mode 100644 index d4bf49e..0000000 --- a/cpp/242.ValidAnagram/hash.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - bool isAnagram(string s, string t) { - int count[26]={}; - for(int i=0;inext; - if(count==k){ - ListNode *tail=reverseKGroup(cur,k); - ListNode *pre=tail,*now=head,*next; - while(now!=cur){ - next=now->next; - now->next=pre; - pre=now; - now=next; - } - head=pre; - } - return head; - } -}; diff --git a/cpp/25.cpp b/cpp/25.cpp new file mode 100644 index 0000000..ce33497 --- /dev/null +++ b/cpp/25.cpp @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +// recursion.cpp +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + if (head == nullptr || k <= 1) + return head; + auto cur = head; + int count = 0; + for (; count < k && cur != nullptr; ++count) + cur = cur->next; + if (count == k) { + auto tail = reverseKGroup(cur, k); + auto pre = tail, now = head; + while (now != cur) { + auto next = now->next; + now->next = pre; + pre = now; + now = next; + } + return pre; + } + return head; + } +}; diff --git a/cpp/257.BinaryTreePaths/recursion-6ms.cpp b/cpp/257.BinaryTreePaths/recursion-6ms.cpp deleted file mode 100644 index fa2ac6d..0000000 --- a/cpp/257.BinaryTreePaths/recursion-6ms.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector binaryTreePaths(TreeNode* root) { - vectorresult; - if(root==NULL) - return result; - if(root->left==NULL&&root->right==NULL){ - result.push_back(to_string(root->val)); - return result; - } - preOrder(result,root->left,to_string(root->val)); - preOrder(result,root->right,to_string(root->val)); - return result; - } - void preOrder(vector&result,TreeNode*root,string str){ - if(root==NULL) - return; - str+="->"+to_string(root->val); - if(root->left==NULL&&root->right==NULL) - result.push_back(str); - preOrder(result,root->left,str); - preOrder(result,root->right,str); - } -}; \ No newline at end of file diff --git a/cpp/257.cpp b/cpp/257.cpp new file mode 100644 index 0000000..50804d6 --- /dev/null +++ b/cpp/257.cpp @@ -0,0 +1,34 @@ +// recursion-6ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector binaryTreePaths(TreeNode *root) { + vector result; + if (root == NULL) + return result; + if (root->left == NULL && root->right == NULL) { + result.push_back(to_string(root->val)); + return result; + } + preOrder(result, root->left, to_string(root->val)); + preOrder(result, root->right, to_string(root->val)); + return result; + } + void preOrder(vector &result, TreeNode *root, string str) { + if (root == NULL) + return; + str += "->" + to_string(root->val); + if (root->left == NULL && root->right == NULL) + result.push_back(str); + preOrder(result, root->left, str); + preOrder(result, root->right, str); + } +}; \ No newline at end of file diff --git a/cpp/258.AddDigits/O1.cpp b/cpp/258.AddDigits/O1.cpp deleted file mode 100644 index f43c2c2..0000000 --- a/cpp/258.AddDigits/O1.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - int addDigits(int num) { - return 1+(num-1)%9; - } -}; diff --git a/cpp/258.cpp b/cpp/258.cpp new file mode 100644 index 0000000..7321720 --- /dev/null +++ b/cpp/258.cpp @@ -0,0 +1,5 @@ +// O1.cpp +class Solution { +public: + int addDigits(int num) { return 1 + (num - 1) % 9; } +}; diff --git a/cpp/26.RemoveDuplicatesFromSortedArray/onepass-28ms.cpp b/cpp/26.RemoveDuplicatesFromSortedArray/onepass-28ms.cpp deleted file mode 100644 index 72c044c..0000000 --- a/cpp/26.RemoveDuplicatesFromSortedArray/onepass-28ms.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int removeDuplicates(vector& nums) { - int i=0,j,len=nums.size(); - if(len==0)return 0; - for(j=1;j& nums) { - return unique(nums.begin(),nums.end())-nums.begin(); - } -}; \ No newline at end of file diff --git a/cpp/26.cpp b/cpp/26.cpp new file mode 100644 index 0000000..305d9e8 --- /dev/null +++ b/cpp/26.cpp @@ -0,0 +1,19 @@ +// onepass-28ms.cpp +class Solution { +public: + int removeDuplicates(vector& nums) { + int i = 0, j, len = nums.size(); + if (len == 0) + return 0; + for (j = 1; j < len; ++j) + if (nums[i] != nums[j]) + nums[++i] = nums[j]; + return i + 1; + } +}; +class Solution2 { // using stl, 24ms +public: + int removeDuplicates(vector& nums) { + return unique(nums.begin(), nums.end()) - nums.begin(); + } +}; diff --git a/cpp/260.SingleNumberIII/xor-13ms.cpp b/cpp/260.SingleNumberIII/xor-13ms.cpp deleted file mode 100644 index cd2210a..0000000 --- a/cpp/260.SingleNumberIII/xor-13ms.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - vector singleNumber(vector& nums) { - vectorresult(2); - int sum=0,len=nums.size(),off=0,temp; - for(int i=0;i>=1); - temp=sum; - for(int i=0;i singleNumber(vector &nums) { + vector result(2); + int sum = 0, len = nums.size(), off = 0, temp; + for (int i = 0; i < len; ++i) + sum ^= nums[i]; + for (temp = sum; (temp & 1) != 1; ++off, temp >>= 1) + ; + temp = sum; + for (int i = 0; i < len; ++i) + if (nums[i] & (1 << off)) + temp ^= nums[i]; + result[0] = temp; + result[1] = sum ^ temp; + return result; + } +}; diff --git a/cpp/263.UglyNumber/simple-6ms.cpp b/cpp/263.UglyNumber/simple-6ms.cpp deleted file mode 100644 index b3226f3..0000000 --- a/cpp/263.UglyNumber/simple-6ms.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - bool isUgly(int num) { - if(num<=0)return 0; - while(num!=1){ - if(num%2==0) - num/=2; - else if(num%3==0) - num/=3; - else if(num%5==0) - num/=5; - else - return 0; - } - return 1; - } -}; diff --git a/cpp/263.cpp b/cpp/263.cpp new file mode 100644 index 0000000..f070286 --- /dev/null +++ b/cpp/263.cpp @@ -0,0 +1,19 @@ +// simple-6ms.cpp +class Solution { +public: + bool isUgly(int num) { + if (num <= 0) + return 0; + while (num != 1) { + if (num % 2 == 0) + num /= 2; + else if (num % 3 == 0) + num /= 3; + else if (num % 5 == 0) + num /= 5; + else + return 0; + } + return 1; + } +}; diff --git a/cpp/264.UglyNumberII/dp.cpp b/cpp/264.UglyNumberII/dp.cpp deleted file mode 100644 index 1b3beb3..0000000 --- a/cpp/264.UglyNumberII/dp.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int nthUglyNumber(int n) { - int a=0,b=0,c=0; - vectornums(n,1); - for(int i=1;is; - s.insert(1); - auto it=s.begin(); - for(int i=1;i nums(n, 1); + for (int i = 1; i < n; ++i) { + nums[i] = min(nums[a] * 2, min(nums[b] * 3, nums[c] * 5)); + if (nums[i] == nums[a] * 2) + ++a; + if (nums[i] == nums[b] * 3) + ++b; + if (nums[i] == nums[c] * 5) + ++c; + } + return nums[n - 1]; + } +}; +// set.cpp +class Solution2 { +public: + int nthUglyNumber(int n) { + set s; + s.insert(1); + auto it = s.begin(); + for (int i = 1; i < n; ++i, ++it) { + s.insert(*it * 2); + s.insert(*it * 3); + s.insert(*it * 5); + } + return *it; + } +}; diff --git a/cpp/268.MissingNumber/accumulate.cpp b/cpp/268.MissingNumber/accumulate.cpp deleted file mode 100644 index ff841cc..0000000 --- a/cpp/268.MissingNumber/accumulate.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - int missingNumber(vector& nums) { - int len=nums.size(); - int sum=(0+len)*(len+1)/2; - for(int i=0;i &nums) { + int len = nums.size(); + int sum = (0 + len) * (len + 1) / 2; + for (int i = 0; i < len; i++) + sum -= nums[i]; + return sum; + } +}; diff --git a/cpp/27.RemoveElement/onepass-3ms.cpp b/cpp/27.RemoveElement/onepass-3ms.cpp deleted file mode 100644 index ff37adb..0000000 --- a/cpp/27.RemoveElement/onepass-3ms.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - int removeElement(vector& nums, int val) { - int i=0,j=0,len=nums.size(); - for(;j& nums, int val) { + int i = 0, j = 0, len = nums.size(); + for (; j < len; ++j) + if (nums[j] != val) + nums[i++] = nums[j]; + return i; + } +}; diff --git a/cpp/274.H-Index/OnTimeOnSpace.cpp b/cpp/274.H-Index/OnTimeOnSpace.cpp deleted file mode 100644 index f79e06f..0000000 --- a/cpp/274.H-Index/OnTimeOnSpace.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int hIndex(vector& citations) { - int n=citations.size(); - vectorarr(n+1,0); - for(auto num:citations) - if(num>=n) - arr[n]+=1; - else - arr[num]+=1; - int total=0; - for(int i=0;i<=n;++i){ - total+=arr[n-i]; - if(total>=n-i) - return n-i; - } - return 0; - } -}; diff --git a/cpp/274.cpp b/cpp/274.cpp new file mode 100644 index 0000000..6fc0b66 --- /dev/null +++ b/cpp/274.cpp @@ -0,0 +1,20 @@ +// OnTimeOnSpace.cpp +class Solution { +public: + int hIndex(vector &citations) { + int n = citations.size(); + vector arr(n + 1, 0); + for (auto num : citations) + if (num >= n) + arr[n] += 1; + else + arr[num] += 1; + int total = 0; + for (int i = 0; i <= n; ++i) { + total += arr[n - i]; + if (total >= n - i) + return n - i; + } + return 0; + } +}; diff --git a/cpp/275.H-IndexII/binarySearch.cpp b/cpp/275.H-IndexII/binarySearch.cpp deleted file mode 100644 index c636a78..0000000 --- a/cpp/275.H-IndexII/binarySearch.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int hIndex(vector& citations) { - int l=0,r=citations.size()-1,n=citations.size(),res=0; - while(l<=r){ - int mid=(l+r)/2; - int num=n-mid,h=citations[mid]; - if(num>h){ - res=max(h,res); - l=mid+1; - } - else{ - res=max(num,res); - r=mid-1; - } - } - return res; - } -}; diff --git a/cpp/275.cpp b/cpp/275.cpp new file mode 100644 index 0000000..0882294 --- /dev/null +++ b/cpp/275.cpp @@ -0,0 +1,19 @@ +// binarySearch.cpp +class Solution { +public: + int hIndex(vector &citations) { + int l = 0, r = citations.size() - 1, n = citations.size(), res = 0; + while (l <= r) { + int mid = (l + r) / 2; + int num = n - mid, h = citations[mid]; + if (num > h) { + res = max(h, res); + l = mid + 1; + } else { + res = max(num, res); + r = mid - 1; + } + } + return res; + } +}; diff --git a/cpp/278.FirstBadVersion/BinarySearch-0ms.cpp b/cpp/278.FirstBadVersion/BinarySearch-0ms.cpp deleted file mode 100644 index 94350b2..0000000 --- a/cpp/278.FirstBadVersion/BinarySearch-0ms.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// Forward declaration of isBadVersion API. -bool isBadVersion(int version); - -class Solution { -public: - int firstBadVersion(int n) { - int i=1,j=n,mid; - while(j<=j){ - mid=i+(j-i)/2; - if(isBadVersion(mid)) - if(!isBadVersion(mid-1)) - return mid; - else - j=mid-1; - else - i=mid+1; - } - return mid; - } -}; diff --git a/cpp/278.cpp b/cpp/278.cpp new file mode 100644 index 0000000..c6c6ca0 --- /dev/null +++ b/cpp/278.cpp @@ -0,0 +1,21 @@ +// BinarySearch-0ms.cpp +// Forward declaration of isBadVersion API. +bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + int i = 1, j = n, mid; + while (j <= j) { + mid = i + (j - i) / 2; + if (isBadVersion(mid)) + if (!isBadVersion(mid - 1)) + return mid; + else + j = mid - 1; + else + i = mid + 1; + } + return mid; + } +}; diff --git a/cpp/279.PerfectSquares/bfs.cpp b/cpp/279.PerfectSquares/bfs.cpp deleted file mode 100644 index 03ffede..0000000 --- a/cpp/279.PerfectSquares/bfs.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { -public: - int numSquares(int n) { - vectorstep; - for(int i=1;i*i<=n;++i) - step.push_back(i*i); - queueqe; - vectorvisited(n+1,0); - qe.push(0); - int level=0,last=1,cur; - while(visited[n]==0){ - cur=qe.front(); - qe.pop(); - for(int i=0;i step; + for (int i = 1; i * i <= n; ++i) + step.push_back(i * i); + queue qe; + vector visited(n + 1, 0); + qe.push(0); + int level = 0, last = 1, cur; + while (visited[n] == 0) { + cur = qe.front(); + qe.pop(); + for (int i = 0; i < step.size() && cur + step[i] <= n; ++i) + if (visited[cur + step[i]] == 0) { + qe.push(cur + step[i]); + visited[cur + step[i]] = 1; + } + if (--last == 0 && visited[n] == 0) { + last += qe.size(); + ++level; + } + } + return level + 1; + } +}; diff --git a/cpp/28.ImplementStrstr/bruteForce.cpp b/cpp/28.ImplementStrstr/bruteForce.cpp deleted file mode 100644 index 5f32c27..0000000 --- a/cpp/28.ImplementStrstr/bruteForce.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int strStr(string haystack, string needle) { - for(int i=0;i<=(int)haystack.size()-(int)needle.size();++i) - for(int j=0;;++j){ - if(j==needle.size()) - return i; - if(needle[j]!=haystack[i+j]) - break; - } - return -1; - } -}; diff --git a/cpp/28.cpp b/cpp/28.cpp new file mode 100644 index 0000000..e87ac79 --- /dev/null +++ b/cpp/28.cpp @@ -0,0 +1,58 @@ +// bruteForce.cpp +class Solution { +public: + int strStr(string haystack, string needle) { + for (int i = 0; i <= (int)haystack.size() - (int)needle.size(); ++i) + for (int j = 0;; ++j) { + if (j == needle.size()) + return i; + if (needle[j] != haystack[i + j]) + break; + } + return -1; + } +}; +class Solution2 { // my fake kmp + vector getNext(string p) { + vector res(p.size(), 0); + for(int i = 0, j = 1; j < p.size();) {// i for suffix and j for prefix + if (p[i] == p[j]) { + if (res[j] < i + 1) { + res[j] = i + 1; + } + ++i; + ++j; + } else { + j = j - i + 1; + i = 0; + } + } + return res; + } +public: + int strStr(string haystack, string needle) { + auto next = getNext(needle); + for(int i = 0, j = 0; i < haystack.size(); ++i) { + bool match = false; + bool fail = false; + for(; j < needle.size();) { + if (haystack[i] == needle[j]) { + match = true; + ++i; + ++j; + } else { + fail = true; + int n = j > 0 ? next[j-1] : 0; + j = n; + if(j==0) break; + } + } + if(j == needle.size()) + return i - j; + if (match && fail) { + --i; + } + } + return -1; + } +}; \ No newline at end of file diff --git a/cpp/283.MoveZeroes/On.cpp b/cpp/283.MoveZeroes/On.cpp deleted file mode 100644 index 9f06817..0000000 --- a/cpp/283.MoveZeroes/On.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - void moveZeroes(vector& nums) { - int count=0; - int len=nums.size(); - for(int i=0;i &nums) { + int count = 0; + int len = nums.size(); + for (int i = 0; i < len; i++) + if (nums[i] == 0) + count++; + else + nums[i - count] = nums[i]; + for (int i = len - count; i < len; i++) + nums[i] = 0; + } +}; diff --git "a/cpp/284.PeekingIterator/\357\200\277.cpp" "b/cpp/284.PeekingIterator/\357\200\277.cpp" deleted file mode 100644 index 0ff7828..0000000 --- "a/cpp/284.PeekingIterator/\357\200\277.cpp" +++ /dev/null @@ -1,40 +0,0 @@ -// Below is the interface for Iterator, which is already defined for you. -// **DO NOT** modify the interface for Iterator. -class Iterator { - struct Data; - Data* data; -public: - Iterator(const vector& nums); - Iterator(const Iterator& iter); - virtual ~Iterator(); - // Returns the next element in the iteration. - int next(); - // Returns true if the iteration has more elements. - bool hasNext() const; -}; - - -class PeekingIterator : public Iterator { -public: - PeekingIterator(const vector& nums) : Iterator(nums) { - // Initialize any member here. - // **DO NOT** save a copy of nums and manipulate it directly. - // You should only use the Iterator interface methods. - - } - - // Returns the next element in the iteration without advancing the iterator. - int peek() { - return Iterator(*this).next(); - } - - // hasNext() and next() should behave the same as in the Iterator interface. - // Override them if needed. - int next() { - return Iterator::next(); - } - - bool hasNext() const { - return Iterator::hasNext(); - } -}; diff --git a/cpp/284.cpp b/cpp/284.cpp new file mode 100644 index 0000000..bdd15b8 --- /dev/null +++ b/cpp/284.cpp @@ -0,0 +1,34 @@ +// .cpp +// Below is the interface for Iterator, which is already defined for you. +// **DO NOT** modify the interface for Iterator. +class Iterator { + struct Data; + Data *data; + +public: + Iterator(const vector &nums); + Iterator(const Iterator &iter); + virtual ~Iterator(); + // Returns the next element in the iteration. + int next(); + // Returns true if the iteration has more elements. + bool hasNext() const; +}; + +class PeekingIterator : public Iterator { +public: + PeekingIterator(const vector &nums) : Iterator(nums) { + // Initialize any member here. + // **DO NOT** save a copy of nums and manipulate it directly. + // You should only use the Iterator interface methods. + } + + // Returns the next element in the iteration without advancing the iterator. + int peek() { return Iterator(*this).next(); } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + int next() { return Iterator::next(); } + + bool hasNext() const { return Iterator::hasNext(); } +}; diff --git a/cpp/287.FindTheDuplicateNumber.cpp b/cpp/287.FindTheDuplicateNumber.cpp deleted file mode 100644 index e32887a..0000000 --- a/cpp/287.FindTheDuplicateNumber.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -//Runtime: 8 ms, faster than 98.62% of C++ online submissions for Find the Duplicate Number. -//Memory Usage: 10.1 MB, less than 16.02% of C++ online submissions for Find the Duplicate Number. -public: - int findDuplicate(vector& nums) { - int slow = nums[0]; - int fast = nums[nums[0]]; - while (slow != fast){ - slow = nums[slow]; - fast = nums[nums[fast]]; - } - for (fast = 0;fast != slow;){ - fast = nums[fast]; - slow = nums[slow]; - } - return slow; - } -}; \ No newline at end of file diff --git a/cpp/287.cpp b/cpp/287.cpp new file mode 100644 index 0000000..a666af4 --- /dev/null +++ b/cpp/287.cpp @@ -0,0 +1,19 @@ +class Solution { + // Runtime: 8 ms, faster than 98.62% of C++ online submissions for Find the + // Duplicate Number. Memory Usage: 10.1 MB, less than 16.02% of C++ online + // submissions for Find the Duplicate Number. +public: + int findDuplicate(vector &nums) { + int slow = nums[0]; + int fast = nums[nums[0]]; + while (slow != fast) { + slow = nums[slow]; + fast = nums[nums[fast]]; + } + for (fast = 0; fast != slow;) { + fast = nums[fast]; + slow = nums[slow]; + } + return slow; + } +}; \ No newline at end of file diff --git a/cpp/289.GameOfLife.cpp b/cpp/289.GameOfLife.cpp deleted file mode 100644 index 53a956e..0000000 --- a/cpp/289.GameOfLife.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 83.08% of C++ online submissions for Game of Life. -//Memory Usage: 8.5 MB, less than 97.14% of C++ online submissions for Game of Life. -public: -void gameOfLife(vector>& board) { - int m = board.size(), n = m ? board[0].size() : 0; - for (int i=0; i>= 1; -} -}; \ No newline at end of file diff --git a/cpp/289.cpp b/cpp/289.cpp new file mode 100644 index 0000000..cb5205e --- /dev/null +++ b/cpp/289.cpp @@ -0,0 +1,22 @@ +class Solution { + // Runtime: 4 ms, faster than 83.08% of C++ online submissions for Game of + // Life. Memory Usage: 8.5 MB, less than 97.14% of C++ online submissions for + // Game of Life. +public: + void gameOfLife(vector> &board) { + int m = board.size(), n = m ? board[0].size() : 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int count = 0; + for (int I = max(i - 1, 0); I < min(i + 2, m); ++I) + for (int J = max(j - 1, 0); J < min(j + 2, n); ++J) + count += board[I][J] & 1; + if (count == 3 || count - board[i][j] == 3) + board[i][j] |= 2; + } + } + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + board[i][j] >>= 1; + } +}; \ No newline at end of file diff --git a/cpp/29.DivideTwoIntegers.cpp b/cpp/29.DivideTwoIntegers.cpp deleted file mode 100644 index 797dc44..0000000 --- a/cpp/29.DivideTwoIntegers.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Divide Two Integers. -//Memory Usage: 8.2 MB, less than 47.58% of C++ online submissions for Divide Two Integers. -public: - int divide(int dividend, int divisor) { - if(divisor==0) - return 0x7fffffff; - if(dividend==0) - return 0; - auto res = [](long long dividend,long long divisor)->long long{ - auto res=0ll; - while(dividend>=divisor){ - auto level=1ll; - for(;(divisor<0 and divisor>0)or(dividend<0 and divisor<0)?1:-1); - if(res>2147483647ll) - return 0x7fffffff; - if(res<-2147483648ll) - return -2146483648; - return res; - } -}; \ No newline at end of file diff --git a/cpp/29.cpp b/cpp/29.cpp new file mode 100644 index 0000000..d70d78c --- /dev/null +++ b/cpp/29.cpp @@ -0,0 +1,32 @@ +class Solution { + // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Divide Two + // Integers. Memory Usage: 8.2 MB, less than 47.58% of C++ online submissions + // for Divide Two Integers. +public: + int divide(int dividend, int divisor) { + if (divisor == 0) + return 0x7fffffff; + if (dividend == 0) + return 0; + auto res = [](long long dividend, long long divisor) + -> long long { + auto res = 0ll; + while (dividend >= divisor) { + auto level = 1ll; + for (; (divisor << level) < dividend; ++level) + ; + res += 1ll << (level - 1ll); + dividend -= divisor << (level - 1ll); + } + return res; + }(abs((long long)dividend), abs((long long)divisor)) * + ((dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) + ? 1 + : -1); + if (res > 2147483647ll) + return 0x7fffffff; + if (res < -2147483648ll) + return -2146483648; + return res; + } +}; \ No newline at end of file diff --git a/cpp/290.WordPattern/doubleMap-0ms.cpp b/cpp/290.WordPattern/doubleMap-0ms.cpp deleted file mode 100644 index f3e2faa..0000000 --- a/cpp/290.WordPattern/doubleMap-0ms.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - bool wordPattern(string pattern, string str) { - unordered_mapp; - unordered_maps; - istringstream in(str); - vectorsv; - string ss; - while(in>>ss) - sv.push_back(ss); - if(pattern.size()!=sv.size())return 0; - for(int i=0;i p; + unordered_map s; + istringstream in(str); + vector sv; + string ss; + while (in >> ss) + sv.push_back(ss); + if (pattern.size() != sv.size()) + return 0; + for (int i = 0; i < pattern.size(); ++i) { + if (p[pattern[i]] != s[sv[i]]) + return 0; + p[pattern[i]] = i + 1; + s[sv[i]] = i + 1; + } + return 1; + } +}; diff --git a/cpp/292.NimGame/O1.cpp b/cpp/292.NimGame/O1.cpp deleted file mode 100644 index e7ec13f..0000000 --- a/cpp/292.NimGame/O1.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - bool canWinNim(int n) { - return (n%4); - } -}; diff --git a/cpp/292.cpp b/cpp/292.cpp new file mode 100644 index 0000000..8d06d28 --- /dev/null +++ b/cpp/292.cpp @@ -0,0 +1,5 @@ +// O1.cpp +class Solution { +public: + bool canWinNim(int n) { return (n % 4); } +}; diff --git a/cpp/295.FindMedianFromDataStream/usingTwoPriority_queue.cpp b/cpp/295.FindMedianFromDataStream/usingTwoPriority_queue.cpp deleted file mode 100644 index 37a94c9..0000000 --- a/cpp/295.FindMedianFromDataStream/usingTwoPriority_queue.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class MedianFinder { - int count,mid; - priority_queue,greater>minHeap; - priority_queue,less>maxHeap; -public: - /** initialize your data structure here. */ - MedianFinder() { - count=0; - minHeap.push(0x7fffffff); - maxHeap.push(0x80000000); - } - - void addNum(int num) { - ++count; - if(count&1) - mid=num; - else{ - minHeap.push( max(mid,num) ); - maxHeap.push( min(mid,num) ); - } - } - - double findMedian() { - while(minHeap.top()=minHeap.top()){ - minHeap.push(mid); - mid=minHeap.top(); - minHeap.pop(); - } - else if(mid<=maxHeap.top()){ - maxHeap.push(mid); - mid=maxHeap.top(); - maxHeap.pop(); - } - return mid; - } -}; - -/** - * Your MedianFinder object will be instantiated and called as such: - * MedianFinder obj = new MedianFinder(); - * obj.addNum(num); - * double param_2 = obj.findMedian(); - */ diff --git a/cpp/295.cpp b/cpp/295.cpp new file mode 100644 index 0000000..6f567a2 --- /dev/null +++ b/cpp/295.cpp @@ -0,0 +1,52 @@ +// usingTwoPriority_queue.cpp +class MedianFinder { + int count, mid; + priority_queue, greater> minHeap; + priority_queue, less> maxHeap; + +public: + /** initialize your data structure here. */ + MedianFinder() { + count = 0; + minHeap.push(0x7fffffff); + maxHeap.push(0x80000000); + } + + void addNum(int num) { + ++count; + if (count & 1) + mid = num; + else { + minHeap.push(max(mid, num)); + maxHeap.push(min(mid, num)); + } + } + + double findMedian() { + while (minHeap.top() < maxHeap.top()) { + minHeap.push(maxHeap.top()); + maxHeap.push(minHeap.top()); + minHeap.pop(); + maxHeap.pop(); + } + if ((count & 1) == 0) + return (double)(minHeap.top() + maxHeap.top()) / 2; + if (mid >= minHeap.top()) { + minHeap.push(mid); + mid = minHeap.top(); + minHeap.pop(); + } else if (mid <= maxHeap.top()) { + maxHeap.push(mid); + mid = maxHeap.top(); + maxHeap.pop(); + } + return mid; + } +}; + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder obj = new MedianFinder(); + * obj.addNum(num); + * double param_2 = obj.findMedian(); + */ diff --git a/cpp/297.SerializeAndDeserializeBinaryTree/preorder.cpp b/cpp/297.SerializeAndDeserializeBinaryTree/preorder.cpp deleted file mode 100644 index 29a9ad5..0000000 --- a/cpp/297.SerializeAndDeserializeBinaryTree/preorder.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Codec { - TreeNode* de_preorder(vector&arr,int &index){ - if(arr[index]=="#") - return nullptr; - TreeNode* root=new TreeNode(stoi(arr[index])); - root->left=de_preorder(arr,++index); - root->right=de_preorder(arr,++index); - return root; - } -public: - - // Encodes a tree to a single string. - string serialize(TreeNode* root) { - if(root==NULL) - return "#\n"; - return to_string(root->val)+"\n"+serialize(root->left)+serialize(root->right); - } - - // Decodes your encoded data to tree. - TreeNode* deserialize(string data) { - stringstream ss(data); - vectorarr; - string str; - while(!ss.eof()){ - ss>>str; - arr.push_back(str); - } - int index=0; - return de_preorder(arr,index); - } -}; - -// Your Codec object will be instantiated and called as such: -// Codec codec; -// codec.deserialize(codec.serialize(root)); diff --git a/cpp/297.cpp b/cpp/297.cpp new file mode 100644 index 0000000..27773cd --- /dev/null +++ b/cpp/297.cpp @@ -0,0 +1,46 @@ +// preorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { + TreeNode *de_preorder(vector &arr, int &index) { + if (arr[index] == "#") + return nullptr; + TreeNode *root = new TreeNode(stoi(arr[index])); + root->left = de_preorder(arr, ++index); + root->right = de_preorder(arr, ++index); + return root; + } + +public: + // Encodes a tree to a single string. + string serialize(TreeNode *root) { + if (root == NULL) + return "#\n"; + return to_string(root->val) + "\n" + serialize(root->left) + + serialize(root->right); + } + + // Decodes your encoded data to tree. + TreeNode *deserialize(string data) { + stringstream ss(data); + vector arr; + string str; + while (!ss.eof()) { + ss >> str; + arr.push_back(str); + } + int index = 0; + return de_preorder(arr, index); + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); diff --git a/cpp/299.BullsAndCows.cpp b/cpp/299.BullsAndCows.cpp deleted file mode 100644 index ae0b35b..0000000 --- a/cpp/299.BullsAndCows.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 97.05% of C++ online submissions for Bulls and Cows. -//Memory Usage: 9 MB, less than 33.22% of C++ online submissions for Bulls and Cows. -public: - string getHint(string secret, string guess) { - int A=0,B=0; - unordered_mapm; - for(int i=0;isecond==0) - m.erase(it); - } - } - return to_string(A)+"A"+to_string(B)+"B"; - } -}; \ No newline at end of file diff --git a/cpp/299.cpp b/cpp/299.cpp new file mode 100644 index 0000000..09b6a29 --- /dev/null +++ b/cpp/299.cpp @@ -0,0 +1,24 @@ +class Solution { + // Runtime: 4 ms, faster than 97.05% of C++ online submissions for Bulls and + // Cows. Memory Usage: 9 MB, less than 33.22% of C++ online submissions for + // Bulls and Cows. +public: + string getHint(string secret, string guess) { + int A = 0, B = 0; + unordered_map m; + for (int i = 0; i < secret.size(); ++i) + if (secret[i] == guess[i]) + ++A; + else + ++m[secret[i]]; + for (int i = 0; i < secret.size(); ++i) + if (secret[i] != guess[i]) { + if (auto it = m.find(guess[i]); it != end(m)) { + ++B; + if (--it->second == 0) + m.erase(it); + } + } + return to_string(A) + "A" + to_string(B) + "B"; + } +}; \ No newline at end of file diff --git a/cpp/3.LongestSubstringWithoutRepeatingCharacters.cpp b/cpp/3.LongestSubstringWithoutRepeatingCharacters.cpp deleted file mode 100644 index 6e5ee96..0000000 --- a/cpp/3.LongestSubstringWithoutRepeatingCharacters.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int lengthOfLongestSubstring(string s) { - bool hash[256]={}; - int ret=0,l=0,r=0; - while(r findSubstring(string SS, vector &L) { - vector ans; - if (SS.size() == 0 || L.size() == 0) - return ans; - string_view S=SS; - unordered_map dict; - for (const auto&s:L) - ++dict[s]; - const int wl = L[0].size(); - const int totalLength = L.size() * wl; - auto slideLeftWindow = [wl](auto& tdict,auto& S,auto& left,auto&count){ - --tdict[S.substr(left, wl)]; - --count; - left += wl; - }; - for (int i = 0; i < wl; ++i) { - int left = i, count = 0; - unordered_map tdict; - for (int j = i; left + totalLength <= S.size(); j += wl) - if (auto str = S.substr(j, wl);dict.count(str)) { - ++tdict[str]; - ++count; - if (tdict[str] <= dict[str] && count == L.size()) { - ans.push_back(left); - slideLeftWindow(tdict,S,left,count); - } - else while (tdict[str] > dict[str]) - slideLeftWindow(tdict,S,left,count); - } - else { - tdict.clear(); - count = 0; - left = j + wl; - } - } - return ans; - } -}; \ No newline at end of file diff --git a/cpp/30.cpp b/cpp/30.cpp new file mode 100644 index 0000000..4b278e6 --- /dev/null +++ b/cpp/30.cpp @@ -0,0 +1,38 @@ +class Solution { // 10ms Beats 97.71% +public: + vector findSubstring(string s, vector& L) { + vector ans; + if (s.size() == 0 || L.size() == 0) + return ans; + string_view sv = s; + unordered_map dict; + for (const auto& s : L) + ++dict[s]; + const int wl = L[0].size(), totalLength = L.size() * wl; + auto moveLWin = [wl](auto& tdict, auto& sv, auto& left, auto& count) { + --tdict[sv.substr(left, wl)]; + --count; + left += wl; + }; + for (int i = 0; i < wl; ++i) { + int left = i, count = 0; + unordered_map tdict; + for (int j = i; left + totalLength <= sv.size(); j += wl) + if (auto str = sv.substr(j, wl); dict.contains(str)) { + ++tdict[str]; + ++count; + if (count == L.size() && tdict[str] == dict[str]) { + ans.push_back(left); + moveLWin(tdict, sv, left, count); + } else + while (tdict[str] > dict[str]) + moveLWin(tdict, sv, left, count); + } else { + tdict.clear(); + count = 0; + left = j + wl; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/cpp/300.LongestIncreasingSubsequence/dp+binarySearch.cpp b/cpp/300.LongestIncreasingSubsequence/dp+binarySearch.cpp deleted file mode 100644 index a226708..0000000 --- a/cpp/300.LongestIncreasingSubsequence/dp+binarySearch.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int lengthOfLIS(vector& nums) { - if(nums.size()==0) - return 0; - vectordp(1,nums[0]); - for(int i=1;idp.back()) - dp.push_back(nums[i]); - else - *lower_bound(dp.begin(),dp.end(),nums[i])=nums[i]; - return dp.size(); - } -}; diff --git a/cpp/300.cpp b/cpp/300.cpp new file mode 100644 index 0000000..83835be --- /dev/null +++ b/cpp/300.cpp @@ -0,0 +1,15 @@ +// dp+binarySearch.cpp +class Solution { +public: + int lengthOfLIS(vector &nums) { + if (nums.size() == 0) + return 0; + vector dp(1, nums[0]); + for (int i = 1; i < nums.size(); ++i) + if (nums[i] > dp.back()) + dp.push_back(nums[i]); + else + *lower_bound(dp.begin(), dp.end(), nums[i]) = nums[i]; + return dp.size(); + } +}; diff --git a/cpp/301.RemoveInvalidParentheses.cpp b/cpp/301.RemoveInvalidParentheses.cpp deleted file mode 100644 index 7da66a1..0000000 --- a/cpp/301.RemoveInvalidParentheses.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution { -//Runtime: 124 ms, faster than 15.73% of C++ online submissions for Remove Invalid Parentheses. -//Memory Usage: 10.9 MB, less than 64.65% of C++ online submissions for Remove Invalid Parentheses. -public: - vector removeInvalidParentheses(string_view s) { - unordered_set ret; - using itr=string_view::iterator; - function dfs=[&ret,&dfs](auto first,auto last,auto remain,auto &now){ - if(ret.size() and last-first+now.size() < begin(ret)->size()) - return; - if(first==last){ - if(remain) - return; - if(not ret.size() or begin(ret)->size()==now.size()) - ret.insert(now); - if(begin(ret)->size()=0){ - now.push_back(*first); - dfs(first+1,last,remainIfPush,now); - now.pop_back(); - } - dfs(first+1,last,remain,now); - }; - string now; - dfs(begin(s),end(s),0,now); - return {begin(ret),end(ret)}; - } -}; \ No newline at end of file diff --git a/cpp/301.cpp b/cpp/301.cpp new file mode 100644 index 0000000..ce8fa88 --- /dev/null +++ b/cpp/301.cpp @@ -0,0 +1,44 @@ +class Solution { + // Runtime: 124 ms, faster than 15.73% of C++ online submissions for Remove + // Invalid Parentheses. Memory Usage: 10.9 MB, less than 64.65% of C++ online + // submissions for Remove Invalid Parentheses. +public: + vector removeInvalidParentheses(string_view s) { + unordered_set ret; + using itr = string_view::iterator; + function dfs = + [&ret, &dfs](auto first, auto last, auto remain, auto &now) { + if (ret.size() and last - first + now.size() < begin(ret)->size()) + return; + if (first == last) { + if (remain) + return; + if (not ret.size() or begin(ret)->size() == now.size()) + ret.insert(now); + if (begin(ret)->size() < now.size()) + ret = {now}; + return; + } + int remainIfPush; + switch (*first) { + case '(': + remainIfPush = remain + 1; + break; + case ')': + remainIfPush = remain - 1; + break; + default: + remainIfPush = remain; + } + if (remainIfPush >= 0) { + now.push_back(*first); + dfs(first + 1, last, remainIfPush, now); + now.pop_back(); + } + dfs(first + 1, last, remain, now); + }; + string now; + dfs(begin(s), end(s), 0, now); + return {begin(ret), end(ret)}; + } +}; \ No newline at end of file diff --git a/cpp/303.RangeSumQuery-Immutable/onepass-179ms.cpp b/cpp/303.RangeSumQuery-Immutable/onepass-179ms.cpp deleted file mode 100644 index 4cb0ea4..0000000 --- a/cpp/303.RangeSumQuery-Immutable/onepass-179ms.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class NumArray { - vectordp; -public: - NumArray(vector nums) { - int len=nums.size(); - if(len==0)return; - dp.assign(len,nums[0]); - for(int i=1;ij){ - int temp=i; - i=j; - j=temp; - } - if(i==0) - return dp[j]; - return dp[j]-dp[i-1]; - } -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray obj = new NumArray(nums); - * int param_1 = obj.sumRange(i,j); - */ diff --git a/cpp/303.cpp b/cpp/303.cpp new file mode 100644 index 0000000..6ecccb6 --- /dev/null +++ b/cpp/303.cpp @@ -0,0 +1,31 @@ +// onepass-179ms.cpp +class NumArray { + vector dp; + +public: + NumArray(vector nums) { + int len = nums.size(); + if (len == 0) + return; + dp.assign(len, nums[0]); + for (int i = 1; i < len; ++i) + dp[i] = dp[i - 1] + nums[i]; + } + + int sumRange(int i, int j) { + if (i > j) { + int temp = i; + i = j; + j = temp; + } + if (i == 0) + return dp[j]; + return dp[j] - dp[i - 1]; + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * int param_1 = obj.sumRange(i,j); + */ diff --git a/cpp/304.RangeSumQuery2D-Immutable/dp.cpp b/cpp/304.RangeSumQuery2D-Immutable/dp.cpp deleted file mode 100644 index 64503db..0000000 --- a/cpp/304.RangeSumQuery2D-Immutable/dp.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class NumMatrix { -vector>dp; -public: -NumMatrix(vector> matrix) { - int row=matrix.size(); - if(row==0)return; - int col=matrix[0].size(); - dp=matrix; - for(int i=1;i0&&col1>0?dp[row1-1][col1-1]:0,c=col1>0?dp[row2][col1-1]:0,d=row1>0?dp[row1-1][col2]:0; - return dp[row2][col2]+b-c-d; -} -}; - -/** -* Your NumMatrix object will be instantiated and called as such: -* NumMatrix obj = new NumMatrix(matrix); -* int param_1 = obj.sumRegion(row1,col1,row2,col2); -*/ diff --git a/cpp/304.cpp b/cpp/304.cpp new file mode 100644 index 0000000..fc0382d --- /dev/null +++ b/cpp/304.cpp @@ -0,0 +1,32 @@ +// dp.cpp +class NumMatrix { + vector> dp; + +public: + NumMatrix(vector> matrix) { + int row = matrix.size(); + if (row == 0) + return; + int col = matrix[0].size(); + dp = matrix; + for (int i = 1; i < row; ++i) + for (int j = 0; j < col; ++j) + dp[i][j] += dp[i - 1][j]; + for (int i = 0; i < row; ++i) + for (int j = 1; j < col; ++j) + dp[i][j] += dp[i][j - 1]; + } + + int sumRegion(int row1, int col1, int row2, int col2) { + int b = row1 > 0 && col1 > 0 ? dp[row1 - 1][col1 - 1] : 0, + c = col1 > 0 ? dp[row2][col1 - 1] : 0, + d = row1 > 0 ? dp[row1 - 1][col2] : 0; + return dp[row2][col2] + b - c - d; + } +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix obj = new NumMatrix(matrix); + * int param_1 = obj.sumRegion(row1,col1,row2,col2); + */ diff --git a/cpp/306.AdditiveNumber/tooMuchTrap-4ms.cpp b/cpp/306.AdditiveNumber/tooMuchTrap-4ms.cpp deleted file mode 100644 index 8879aad..0000000 --- a/cpp/306.AdditiveNumber/tooMuchTrap-4ms.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { - bool search(long long val,long long lastVal,string &str,int offset){ - auto s=to_string(val); - if(str.size()-offset>=s.size()&&str.substr(offset,s.size())==s) - return offset+s.size()==str.size()?true:search(lastVal+val,val,str,offset+s.size()); - return false; - } -public: - bool isAdditiveNumber(string num) { - for(int i=1;i+i= s.size() && str.substr(offset, s.size()) == s) + return offset + s.size() == str.size() + ? true + : search(lastVal + val, val, str, offset + s.size()); + return false; + } + +public: + bool isAdditiveNumber(string num) { + for (int i = 1; i + i < num.size(); ++i) { // i is the length of num1 + auto a = stol(num.substr(0, i)); + for (int j = 1; i + j + j <= num.size(); ++j) { // j is the length of num1 + auto b = stol(num.substr(i, j)); + if (search(a + b, b, num, i + j)) + return true; + if (num[i] == '0') + break; + } + if (num[0] == '0') + break; + } + return false; + } +}; // uint64, leading 0,num2 < num1 diff --git a/cpp/307.RangeSumQuery-Mutable.cpp b/cpp/307.RangeSumQuery-Mutable.cpp deleted file mode 100644 index 9341df6..0000000 --- a/cpp/307.RangeSumQuery-Mutable.cpp +++ /dev/null @@ -1,87 +0,0 @@ -class NumArray { -//Runtime: 176 ms, faster than 17.29% of C++ online submissions for Range Sum Query - Mutable. -//Memory Usage: 19.1 MB, less than 63.13% of C++ online submissions for Range Sum Query - Mutable. - vectordp; - vectorm_nums; -public: - NumArray(vector& nums):m_nums(nums) { - int len=nums.size(); - if(len==0)return; - dp.assign(len,nums[0]); - for(int i=1;ij) - swap(i,j); - if(i==0) - return dp[j]; - return dp[j]-dp[i-1]; - } -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray* obj = new NumArray(nums); - * obj->update(i,val); - * int param_2 = obj->sumRange(i,j); - */ - -class NumArray { -//Runtime: 184 ms, faster than 13.56% of C++ online submissions for Range Sum Query - Mutable. -//Memory Usage: 20 MB, less than 23.38% of C++ online submissions for Range Sum Query - Mutable. - vectordp; - vectorm_nums; - mapcache; - void doUpdate() { - auto it=begin(cache),nxt=next(it); - int diff=0; - while(it!=end(cache)){ - auto [i,val]=*it; - diff+=val-m_nums[i]; - m_nums[i]=val; - for(int idx=i;(nxt==end(cache) or nxt->first!=idx) and idx& nums):m_nums(nums) { - int len=nums.size(); - if(len==0)return; - dp.assign(len,nums[0]); - for(int i=1;ij) - swap(i,j); - if(i==0) - return dp[j]; - return dp[j]-dp[i-1]; - } -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray* obj = new NumArray(nums); - * obj->update(i,val); - * int param_2 = obj->sumRange(i,j); - */ \ No newline at end of file diff --git a/cpp/307.cpp b/cpp/307.cpp new file mode 100644 index 0000000..e0b4a55 --- /dev/null +++ b/cpp/307.cpp @@ -0,0 +1,92 @@ +class NumArray { + // Runtime: 176 ms, faster than 17.29% of C++ online submissions for Range Sum + // Query - Mutable. Memory Usage: 19.1 MB, less than 63.13% of C++ online + // submissions for Range Sum Query - Mutable. + vector dp; + vector m_nums; + +public: + NumArray(vector &nums) : m_nums(nums) { + int len = nums.size(); + if (len == 0) + return; + dp.assign(len, nums[0]); + for (int i = 1; i < len; ++i) + dp[i] = dp[i - 1] + nums[i]; + } + + void update(int i, int val) { + int temp = i; + for (int diff = val - m_nums[i]; i < dp.size(); ++i) + dp[i] += diff; + m_nums[temp] = val; + } + + int sumRange(int i, int j) { + if (i > j) + swap(i, j); + if (i == 0) + return dp[j]; + return dp[j] - dp[i - 1]; + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(i,val); + * int param_2 = obj->sumRange(i,j); + */ + +class NumArray2 { + // Runtime: 184 ms, faster than 13.56% of C++ online submissions for Range Sum + // Query - Mutable. Memory Usage: 20 MB, less than 23.38% of C++ online + // submissions for Range Sum Query - Mutable. + vector dp; + vector m_nums; + map cache; + void doUpdate() { + auto it = begin(cache), nxt = next(it); + int diff = 0; + while (it != end(cache)) { + auto [i, val] = *it; + diff += val - m_nums[i]; + m_nums[i] = val; + for (int idx = i; + (nxt == end(cache) or nxt->first != idx) and idx < dp.size(); ++idx) + dp[idx] += diff; + ++it; + nxt = nxt == end(cache) ? end(cache) : next(nxt); + } + cache.clear(); + } + +public: + NumArray2(vector &nums) : m_nums(nums) { + int len = nums.size(); + if (len == 0) + return; + dp.assign(len, nums[0]); + for (int i = 1; i < len; ++i) + dp[i] = dp[i - 1] + nums[i]; + } + + void update(int i, int val) { cache[i] = val; } + + int sumRange(int i, int j) { + if (cache.size()) + doUpdate(); + if (i > j) + swap(i, j); + if (i == 0) + return dp[j]; + return dp[j] - dp[i - 1]; + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(i,val); + * int param_2 = obj->sumRange(i,j); + */ \ No newline at end of file diff --git a/cpp/31.NextPermutation/simple.cpp b/cpp/31.NextPermutation/simple.cpp deleted file mode 100644 index d31205b..0000000 --- a/cpp/31.NextPermutation/simple.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - void nextPermutation(vector& nums) { - int i=0,j=nums.size()-1,n=nums.size(); - while(j>0&&nums[j]<=nums[j-1])--j; - if(j-1>=0){ - int minIndex=j; - for(int k=j+1;knums[j-1]) - minIndex=nums[j] &nums) { + int i = 0, j = nums.size() - 1, n = nums.size(); + while (j > 0 && nums[j] <= nums[j - 1]) + --j; + if (j - 1 >= 0) { + int minIndex = j; + for (int k = j + 1; k < n; ++k) + if (nums[k] > nums[j - 1]) + minIndex = nums[j] < nums[k] ? j : k; + swap(nums[j - 1], nums[minIndex]); + sort(nums.begin() + j, nums.end()); + } else + sort(nums.begin(), nums.end()); + } +}; diff --git a/cpp/313.SuperUglyNumber/better_priority_queue.cpp b/cpp/313.SuperUglyNumber/better_priority_queue.cpp deleted file mode 100644 index d2b2a8f..0000000 --- a/cpp/313.SuperUglyNumber/better_priority_queue.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution { - struct ugly{ - int base; - int index; - int sum; - bool operator () (ugly&a,ugly&b){ - return a.sum>b.sum; - } - }; -public: - int nthSuperUglyNumber(int n, vector& primes) { - priority_queue,ugly>pq; - vectorres(n,1); - for(int i=0;i& primes) { - priority_queue,greater>pq; - pq.push(1); - long long int last=-1,temp; - while(n){ - long long int cur=pq.top(); - pq.pop(); - if(last!=cur){ - last=cur; - --n; - for(int num:primes) - if( (temp=num*cur)<=(long long int)0x7fffffff) - pq.push(temp); - } - } - return last; - } -}; diff --git a/cpp/313.SuperUglyNumber/usingVector.cpp b/cpp/313.SuperUglyNumber/usingVector.cpp deleted file mode 100644 index ea3a14e..0000000 --- a/cpp/313.SuperUglyNumber/usingVector.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - int nthSuperUglyNumber(int n, vector& primes) { - vectorindex(primes.size(),0),cache(primes),res(n,1); - for(int i=1;i b.sum; } + }; + +public: + int nthSuperUglyNumber(int n, vector &primes) { + priority_queue, ugly> pq; + vector res(n, 1); + for (int i = 0; i < primes.size(); ++i) + pq.push(ugly{primes[i], 0, primes[i]}); + for (int i = 1; i < n; ++i) { + ugly u = pq.top(); + pq.pop(); + if (u.sum <= res[i - 1]) + --i; + else + res[i] = u.sum; + pq.push(ugly{u.base, ++u.index, u.base * res[u.index]}); + } + return res[n - 1]; + } +}; +// priority_queue.cpp +class Solution2 { +public: + int nthSuperUglyNumber(int n, vector &primes) { + priority_queue, greater> pq; + pq.push(1); + long long int last = -1, temp; + while (n) { + long long int cur = pq.top(); + pq.pop(); + if (last != cur) { + last = cur; + --n; + for (int num : primes) + if ((temp = num * cur) <= (long long int)0x7fffffff) + pq.push(temp); + } + } + return last; + } +}; +// usingVector.cpp +class Solution3 { +public: + int nthSuperUglyNumber(int n, vector &primes) { + vector index(primes.size(), 0), cache(primes), res(n, 1); + for (int i = 1; i < n; ++i) { + int minVal = 0x7fffffff, offset; + for (int j = 0; j < primes.size(); ++j) + if (cache[j] < minVal) { + minVal = cache[j]; + offset = j; + } + if (minVal <= res[i - 1]) + --i; + else + res[i] = minVal; + cache[offset] = res[index[offset]++] * primes[offset]; + } + return res[n - 1]; + } +}; diff --git a/cpp/316.RemoveDuplicateLetters.cpp b/cpp/316.RemoveDuplicateLetters.cpp deleted file mode 100644 index be70644..0000000 --- a/cpp/316.RemoveDuplicateLetters.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -//Runtime: 8 ms Your runtime beats 40.32 % of cpp submissions. -//Memory Usage: 10.6 MB -public: - string removeDuplicateLetters(string s) { - array cnt={}; - int pos = 0; // the position for the smallest s[i] - for (auto ch:s) - cnt[ch - 'a']++; - for (int i = 0; i < s.size(); i++) { - if (s[i] < s[pos]) - pos = i; - if (--cnt[s[i] - 'a'] == 0) - break; - } - string next{}; - for(int i=pos+1;i cnt = {}; + int pos = 0; // the position for the smallest s[i] + for (auto ch : s) + cnt[ch - 'a']++; + for (int i = 0; i < s.size(); i++) { + if (s[i] < s[pos]) + pos = i; + if (--cnt[s[i] - 'a'] == 0) + break; + } + string next{}; + for (int i = pos + 1; i < s.size(); ++i) + if (s[i] != s[pos]) + next += s[i]; + return s.size() == 0 ? "" : s[pos] + removeDuplicateLetters(next); + } +}; \ No newline at end of file diff --git a/cpp/318.MaximumProductOfWordLengths/higher-efficient.cpp b/cpp/318.MaximumProductOfWordLengths/higher-efficient.cpp deleted file mode 100644 index 4c2f9e1..0000000 --- a/cpp/318.MaximumProductOfWordLengths/higher-efficient.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int maxProduct(vector& words) { - int len=0; - vectorcomp(words.size(),0); - for(int i=0;i& words) { - int len=0; - for(int i=0;ihashset(words[i].begin(),words[i].end()); - for(int j=i+1;j &words) { + int len = 0; + vector comp(words.size(), 0); + for (int i = 0; i < words.size(); ++i) { + string &str = words[i]; + for (int j = 0; j < str.size(); ++j) + comp[i] |= 1 << (str[j] - 'a'); + } + for (int i = 0; i < words.size(); ++i) + for (int j = i + 1; j < words.size(); ++j) + if ((comp[i] & comp[j]) == 0) + len = max(len, (int)(words[i].size() * words[j].size())); + return len; + } +}; +// lower-efficient.cpp +class Solution2 { +public: + int maxProduct(vector &words) { + int len = 0; + for (int i = 0; i < words.size(); ++i) { + unordered_set hashset(words[i].begin(), words[i].end()); + for (int j = i + 1; j < words.size(); ++j) { + bool withoutCommon = true; + for (int k = 0; k < words[j].size(); ++k) + if (hashset.find(words[j][k]) != hashset.end()) { + withoutCommon = false; + break; + } + len = withoutCommon ? max(len, (int)(words[i].size() * words[j].size())) + : len; + } + } + return len; + } +}; diff --git a/cpp/319.BulbSwitcher/math-4ms.cpp b/cpp/319.BulbSwitcher/math-4ms.cpp deleted file mode 100644 index 1a84daf..0000000 --- a/cpp/319.BulbSwitcher/math-4ms.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - int bulbSwitch(int n) { - return sqrt(n); - } -}; diff --git a/cpp/319.cpp b/cpp/319.cpp new file mode 100644 index 0000000..dd6f56f --- /dev/null +++ b/cpp/319.cpp @@ -0,0 +1,5 @@ +// math-4ms.cpp +class Solution { +public: + int bulbSwitch(int n) { return sqrt(n); } +}; diff --git a/cpp/32.LongestValidParentheses/timeOnspaceOn.cpp b/cpp/32.LongestValidParentheses/timeOnspaceOn.cpp deleted file mode 100644 index 5374b11..0000000 --- a/cpp/32.LongestValidParentheses/timeOnspaceOn.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - int longestValidParentheses(string s) { - int n=s.size(),maxlen=0,count=0; - vectorres(n,0); - stackst; - for(int i=0;i res(n, 0); + stack st; + for (int i = 0; i < n; ++i) + if (s[i] == '(') + st.push(i); + else if (!st.empty()) { + res[st.top()] = res[i] = true; + st.pop(); + } + for (int i = 0; i < n; ++i) + if (res[i] == true) + maxlen = max(++count, maxlen); + else + count = 0; + return maxlen; + } +}; diff --git a/cpp/322.CoinChange/dp-19ms.cpp b/cpp/322.CoinChange/dp-19ms.cpp deleted file mode 100644 index e02d8db..0000000 --- a/cpp/322.CoinChange/dp-19ms.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int coinChange(vector& coins, int amount) { - vectordp(amount+1,-1); - int kind=coins.size(); - if(amount==0)return 0; - dp[0]=0; - for(int i=1;i<=amount;++i){ - int min=INT_MAX,index; - for(int j=0;j=0){ - if( dp[ index=i-coins[j] ]>=0) - min=dp[index] &coins, int amount) { + vector dp(amount + 1, -1); + int kind = coins.size(); + if (amount == 0) + return 0; + dp[0] = 0; + for (int i = 1; i <= amount; ++i) { + int min = INT_MAX, index; + for (int j = 0; j < kind; ++j) + if (i - coins[j] >= 0) { + if (dp[index = i - coins[j]] >= 0) + min = dp[index] < min ? dp[index] : min; + } + dp[i] = min != INT_MAX ? min + 1 : -1; + } + return dp[amount]; + } +}; diff --git a/cpp/324.WiggleSortII/simple.cpp b/cpp/324.WiggleSortII/simple.cpp deleted file mode 100644 index 9668f85..0000000 --- a/cpp/324.WiggleSortII/simple.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - void wiggleSort(vector& nums) { - vectorcopy=nums; - sort(copy.begin(),copy.end()); - int i=nums.size()-1; - for(int k=1;k &nums) { + vector copy = nums; + sort(copy.begin(), copy.end()); + int i = nums.size() - 1; + for (int k = 1; k < nums.size(); k += 2) + nums[k] = copy[i--]; + for (int k = 0; k < nums.size(); k += 2) + nums[k] = copy[i--]; + } +}; diff --git a/cpp/326.PowerOfThree/smart.cpp b/cpp/326.PowerOfThree/smart.cpp deleted file mode 100644 index 69f2874..0000000 --- a/cpp/326.PowerOfThree/smart.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - bool isPowerOfThree(int n) { - return n>0 && (1162261467%n==0); - } -}; diff --git a/cpp/326.cpp b/cpp/326.cpp new file mode 100644 index 0000000..1f76686 --- /dev/null +++ b/cpp/326.cpp @@ -0,0 +1,5 @@ +// smart.cpp +class Solution { +public: + bool isPowerOfThree(int n) { return n > 0 && (1162261467 % n == 0); } +}; diff --git a/cpp/328.OddEvenLinkedList/simple.cpp b/cpp/328.OddEvenLinkedList/simple.cpp deleted file mode 100644 index 97b4062..0000000 --- a/cpp/328.OddEvenLinkedList/simple.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* oddEvenList(ListNode* head) { - if(!head||!head->next) - return head; - ListNode odd(0),even(0); - odd.next=head; - even.next=head->next; - ListNode* odd_tail=odd.next; - ListNode* even_tail=even.next; - head=head->next->next; - while(head){ - odd_tail=odd_tail->next=head; - head=head->next; - if(!head) - break; - even_tail=even_tail->next=head; - head=head->next; - } - odd_tail->next=even.next; - even_tail->next=nullptr; - return odd.next; - } -}; diff --git a/cpp/328.cpp b/cpp/328.cpp new file mode 100644 index 0000000..2fbea01 --- /dev/null +++ b/cpp/328.cpp @@ -0,0 +1,33 @@ +// simple.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *oddEvenList(ListNode *head) { + if (!head || !head->next) + return head; + ListNode odd(0), even(0); + odd.next = head; + even.next = head->next; + ListNode *odd_tail = odd.next; + ListNode *even_tail = even.next; + head = head->next->next; + while (head) { + odd_tail = odd_tail->next = head; + head = head->next; + if (!head) + break; + even_tail = even_tail->next = head; + head = head->next; + } + odd_tail->next = even.next; + even_tail->next = nullptr; + return odd.next; + } +}; diff --git a/cpp/329.LongestIncreasingPathInAMatrix/dp.cpp b/cpp/329.LongestIncreasingPathInAMatrix/dp.cpp deleted file mode 100644 index acc14ba..0000000 --- a/cpp/329.LongestIncreasingPathInAMatrix/dp.cpp +++ /dev/null @@ -1,64 +0,0 @@ -class Solution { -public: - int row; - int col; - vector> dp; - int longestIncreasingPath(vector>& matrix) { - row = matrix.size(); - if(row==0)return 0; - col = matrix[0].size(); - dp.resize(row); - for (int i = 0; imax) - max = dp[i][j]; - return max; - } - int calc(int i, int j, vector>& matrix) { - int max = 1; - int temp; - if (i - 1>=0) - if (matrix[i][j]>matrix[i - 1][j]) - if (dp[i - 1][j]>0) - max = dp[i - 1][j] + 1>max ? dp[i - 1][j] + 1 : max; - else { - temp = calc(i - 1, j, matrix) + 1; - max = temp>max ? temp : max; - } - if (i + 1matrix[i + 1][j]) - if (dp[i + 1][j]>0) - max = dp[i + 1][j] + 1>max ? dp[i + 1][j] + 1 : max; - else { - temp = calc(i + 1, j, matrix) + 1; - max = temp>max ? temp : max; - } - if (j - 1>=0) - if (matrix[i][j]>matrix[i][j - 1]) - if (dp[i][j - 1]>0) - max = dp[i][j - 1] + 1>max ? dp[i][j - 1] + 1 : max; - else { - temp = calc(i, j - 1, matrix) + 1; - max = temp>max ? temp : max; - } - if (j + 1matrix[i][j + 1]) - if (dp[i][j + 1]>0) - max = dp[i][j + 1] + 1>max ? dp[i][j + 1] + 1 : max; - else { - temp = calc(i, j + 1, matrix) + 1; - max = temp>max ? temp : max; - } - dp[i][j] = max; - return max; - } -}; diff --git a/cpp/329.cpp b/cpp/329.cpp new file mode 100644 index 0000000..c001ceb --- /dev/null +++ b/cpp/329.cpp @@ -0,0 +1,66 @@ +// dp.cpp +class Solution { +public: + int row; + int col; + vector> dp; + int longestIncreasingPath(vector> &matrix) { + row = matrix.size(); + if (row == 0) + return 0; + col = matrix[0].size(); + dp.resize(row); + for (int i = 0; i < row; i++) + dp[i].resize(col); + for (int i = 0; i < row; i++) + for (int j = 0; j < col; j++) + dp[i][j] = 0; + for (int i = 0; i < row; i++) + for (int j = 0; j < col; j++) + calc(i, j, matrix); + int max = INT_MIN; + for (int i = 0; i < row; i++) + for (int j = 0; j < col; j++) + if (dp[i][j] > max) + max = dp[i][j]; + return max; + } + int calc(int i, int j, vector> &matrix) { + int max = 1; + int temp; + if (i - 1 >= 0) + if (matrix[i][j] > matrix[i - 1][j]) + if (dp[i - 1][j] > 0) + max = dp[i - 1][j] + 1 > max ? dp[i - 1][j] + 1 : max; + else { + temp = calc(i - 1, j, matrix) + 1; + max = temp > max ? temp : max; + } + if (i + 1 < row) + if (matrix[i][j] > matrix[i + 1][j]) + if (dp[i + 1][j] > 0) + max = dp[i + 1][j] + 1 > max ? dp[i + 1][j] + 1 : max; + else { + temp = calc(i + 1, j, matrix) + 1; + max = temp > max ? temp : max; + } + if (j - 1 >= 0) + if (matrix[i][j] > matrix[i][j - 1]) + if (dp[i][j - 1] > 0) + max = dp[i][j - 1] + 1 > max ? dp[i][j - 1] + 1 : max; + else { + temp = calc(i, j - 1, matrix) + 1; + max = temp > max ? temp : max; + } + if (j + 1 < col) + if (matrix[i][j] > matrix[i][j + 1]) + if (dp[i][j + 1] > 0) + max = dp[i][j + 1] + 1 > max ? dp[i][j + 1] + 1 : max; + else { + temp = calc(i, j + 1, matrix) + 1; + max = temp > max ? temp : max; + } + dp[i][j] = max; + return max; + } +}; diff --git a/cpp/33.SearchInRotatedSortedArray/binarysearch.cpp b/cpp/33.SearchInRotatedSortedArray/binarysearch.cpp deleted file mode 100644 index 77b5857..0000000 --- a/cpp/33.SearchInRotatedSortedArray/binarysearch.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -public: - int search(vector& nums, int target) { - int start=0,end=nums.size()-1; - while(start<=end){ - int mid=start+(end-start)/2; - if(nums[mid]==target) - return mid; - if(nums[mid]>=nums[start]) - if(nums[mid]>=target&&target>=nums[start]) - end=mid-1; - else - start=mid+1; - else if(nums[mid]<=nums[end]) - if(nums[mid]<=target&&target<=nums[end]) - start=mid+1; - else - end=mid-1; - } - return -1; - } -}; diff --git a/cpp/33.cpp b/cpp/33.cpp new file mode 100644 index 0000000..4d0e054 --- /dev/null +++ b/cpp/33.cpp @@ -0,0 +1,23 @@ +// binarysearch.cpp +class Solution { +public: + int search(vector& nums, int target) { + int start = 0, end = nums.size() - 1; + while (start <= end) { + int mid = start + (end - start) / 2; + if (nums[mid] == target) + return mid; + if (nums[mid] >= nums[start]) + if (nums[mid] >= target && target >= nums[start]) + end = mid - 1; + else + start = mid + 1; + else if (nums[mid] <= nums[end]) + if (nums[mid] <= target && target <= nums[end]) + start = mid + 1; + else + end = mid - 1; + } + return -1; + } +}; diff --git a/cpp/331.VerifyPreorderSerializationOfABinaryTree/better.cpp b/cpp/331.VerifyPreorderSerializationOfABinaryTree/better.cpp deleted file mode 100644 index 9e4c3bb..0000000 --- a/cpp/331.VerifyPreorderSerializationOfABinaryTree/better.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - bool isValidSerialization(string preorder) { - stringstream ss(preorder); - string str; - int num=0; - while(!ss.eof()){ - getline(ss,str,','); - num+=str=="#"?-1:1; - if(num==-1) - break; - } - return num==-1&&ss.eof(); - } -}; diff --git a/cpp/331.VerifyPreorderSerializationOfABinaryTree/dfs+stringstream.cpp b/cpp/331.VerifyPreorderSerializationOfABinaryTree/dfs+stringstream.cpp deleted file mode 100644 index 62245c5..0000000 --- a/cpp/331.VerifyPreorderSerializationOfABinaryTree/dfs+stringstream.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { - bool dfs(vector&arr,int &i){ - if(i>=arr.size()) - return false; - if(arr[i]=="#") - return true; - return dfs(arr,++i)&&dfs(arr,++i); - } -public: - bool isValidSerialization(string preorder) { - vectorarr; - stringstream ss(preorder); - string str; - while(!ss.eof()){ - getline(ss,str,','); - arr.emplace_back(str); - } - int i=0; - return dfs(arr,i)&&i==arr.size()-1; - } -}; diff --git a/cpp/331.cpp b/cpp/331.cpp new file mode 100644 index 0000000..73ef7ef --- /dev/null +++ b/cpp/331.cpp @@ -0,0 +1,39 @@ +// better.cpp +class Solution { +public: + bool isValidSerialization(string preorder) { + stringstream ss(preorder); + string str; + int num = 0; + while (!ss.eof()) { + getline(ss, str, ','); + num += str == "#" ? -1 : 1; + if (num == -1) + break; + } + return num == -1 && ss.eof(); + } +}; +// dfs+stringstream.cpp +class Solution2 { + bool dfs(vector &arr, int &i) { + if (i >= arr.size()) + return false; + if (arr[i] == "#") + return true; + return dfs(arr, ++i) && dfs(arr, ++i); + } + +public: + bool isValidSerialization(string preorder) { + vector arr; + stringstream ss(preorder); + string str; + while (!ss.eof()) { + getline(ss, str, ','); + arr.emplace_back(str); + } + int i = 0; + return dfs(arr, i) && i == arr.size() - 1; + } +}; diff --git a/cpp/334.IncreasingTripletSubsequence.cpp b/cpp/334.IncreasingTripletSubsequence.cpp deleted file mode 100644 index d32734e..0000000 --- a/cpp/334.IncreasingTripletSubsequence.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -//Runtime: 8 ms, faster than 87.77% of C++ online submissions for Increasing Triplet Subsequence. -//Memory Usage: 9.2 MB, less than 45.15% of C++ online submissions for Increasing Triplet Subsequence. -public: - bool increasingTriplet(vector& nums) { - int c1 = INT_MAX, c2 = INT_MAX; - for (int x : nums) - if (x <= c1) - c1 = x; - else if (x <= c2) - c2 = x; - else - return true; - return false; - } -}; \ No newline at end of file diff --git a/cpp/334.cpp b/cpp/334.cpp new file mode 100644 index 0000000..04b0738 --- /dev/null +++ b/cpp/334.cpp @@ -0,0 +1,17 @@ +class Solution { + // Runtime: 8 ms, faster than 87.77% of C++ online submissions for Increasing + // Triplet Subsequence. Memory Usage: 9.2 MB, less than 45.15% of C++ online + // submissions for Increasing Triplet Subsequence. +public: + bool increasingTriplet(vector &nums) { + int c1 = INT_MAX, c2 = INT_MAX; + for (int x : nums) + if (x <= c1) + c1 = x; + else if (x <= c2) + c2 = x; + else + return true; + return false; + } +}; \ No newline at end of file diff --git a/cpp/336.PalindromePairs.cpp b/cpp/336.PalindromePairs.cpp deleted file mode 100644 index 074f755..0000000 --- a/cpp/336.PalindromePairs.cpp +++ /dev/null @@ -1,49 +0,0 @@ -class Solution { // Time Limit Exceeded -public: - vector> palindromePairs(vector& words) { - vector> ret; - for(int i=0;i> palindromePairs(vector& words) { - auto palindrome=[](const string_view& s){ - for(int i=0,j=s.size()-1;ihashmap; - for(int i=0;i> ret; - for(int i=0;isecond}); - } - if(palindrome(pre)&&pre.size()){ - auto reverseStr=string(suf.rbegin(),suf.rend()); - if(auto it=hashmap.find(reverseStr);it!=hashmap.end()&&it!=cur) - ret.push_back({it->second,i}); - } - } - } - return ret; - } -}; \ No newline at end of file diff --git a/cpp/336.cpp b/cpp/336.cpp new file mode 100644 index 0000000..29efa9e --- /dev/null +++ b/cpp/336.cpp @@ -0,0 +1,53 @@ +class Solution { // Time Limit Exceeded +public: + vector> palindromePairs(vector &words) { + vector> ret; + for (int i = 0; i < words.size(); ++i) + for (int j = 0; j < words.size(); ++j) + if (i == j) + continue; + else if (auto concat = words[i] + words[j]; + concat == string(rbegin(concat), rend(concat))) + ret.push_back({i, j}); + return ret; + } +}; +class Solution2 { + // Runtime: 152 ms, faster than 94.79% of C++ online submissions for + // Palindrome Pairs. Memory Usage: 28.2 MB, less than 94.95% of C++ online + // submissions for Palindrome Pairs. +public: + vector> palindromePairs(vector &words) { + auto palindrome = [](const string_view &s) { + for (int i = 0, j = s.size() - 1; i < j;) + if (s[i++] != s[j--]) + return false; + return true; + }; + unordered_map hashmap; + for (int i = 0; i < words.size(); ++i) + hashmap[words[i]] = i; + vector> ret; + for (int i = 0; i < words.size(); ++i) { + string_view s = words[i]; + auto cur = hashmap.find(s); + for (int j = 0; j <= s.size(); ++j) { + auto pre = s.substr(0, j); + auto suf = s.substr(j); + if (palindrome(suf)) { + auto reverseStr = string(pre.rbegin(), pre.rend()); + if (auto it = hashmap.find(reverseStr); + it != hashmap.end() && it != cur) + ret.push_back({i, it->second}); + } + if (palindrome(pre) && pre.size()) { + auto reverseStr = string(suf.rbegin(), suf.rend()); + if (auto it = hashmap.find(reverseStr); + it != hashmap.end() && it != cur) + ret.push_back({it->second, i}); + } + } + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/337.HouseRobberIii.cpp b/cpp/337.HouseRobberIii.cpp deleted file mode 100644 index 73b62df..0000000 --- a/cpp/337.HouseRobberIii.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 16 ms, faster than 91.42% of C++ online submissions for House Robber III. -//Memory Usage: 20.3 MB, less than 99.84% of C++ online submissions for House Robber III. -public: - int rob(TreeNode* root) { - function(TreeNode*)>recursion=[&recursion](TreeNode* root)->pair{ - if(not root) - return {0,0}; - auto [takel,notakel]=recursion(root->left); - auto [taker,notaker]=recursion(root->right); - return {max(root->val,0)+notakel+notaker,max(takel,notakel)+max(taker,notaker)}; - }; - const auto[a,b]=recursion(root); - return max(a,b); - } -}; \ No newline at end of file diff --git a/cpp/337.cpp b/cpp/337.cpp new file mode 100644 index 0000000..a5be081 --- /dev/null +++ b/cpp/337.cpp @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 16 ms, faster than 91.42% of C++ online submissions for House + // Robber III. Memory Usage: 20.3 MB, less than 99.84% of C++ online + // submissions for House Robber III. +public: + int rob(TreeNode *root) { + function(TreeNode *)> recursion = + [&recursion](TreeNode *root) -> pair { + if (not root) + return {0, 0}; + auto [takel, notakel] = recursion(root->left); + auto [taker, notaker] = recursion(root->right); + return {max(root->val, 0) + notakel + notaker, + max(takel, notakel) + max(taker, notaker)}; + }; + const auto [a, b] = recursion(root); + return max(a, b); + } +}; \ No newline at end of file diff --git a/cpp/338.CountingBits/dp-72ms.cpp b/cpp/338.CountingBits/dp-72ms.cpp deleted file mode 100644 index c219e4b..0000000 --- a/cpp/338.CountingBits/dp-72ms.cpp +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { -public: - vector countBits(int num) { - vectordp(num+1,0); - for(int i=1;i<=num;++i) - dp[i]=dp[i&(i-1)]+1; - return dp; - } -}; diff --git a/cpp/338.cpp b/cpp/338.cpp new file mode 100644 index 0000000..21f64c8 --- /dev/null +++ b/cpp/338.cpp @@ -0,0 +1,10 @@ +// dp-72ms.cpp +class Solution { +public: + vector countBits(int num) { + vector dp(num + 1, 0); + for (int i = 1; i <= num; ++i) + dp[i] = dp[i & (i - 1)] + 1; + return dp; + } +}; diff --git a/cpp/34.FindFirstandLastPositionofElementinSortedArray.cpp b/cpp/34.FindFirstandLastPositionofElementinSortedArray.cpp deleted file mode 100644 index d63f1a7..0000000 --- a/cpp/34.FindFirstandLastPositionofElementinSortedArray.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { // write at 2017, 15ms -public: - vector searchRange(vector& nums, int target) { - int low=0,high=nums.size()-1; - while(low=target) - high=mid; - else - low=mid+1; - } - if(nums.size()==0||nums[low]!=target) - return vector(2,-1); - vectorres(2,low); - high=nums.size()-1; - while(low searchRange(vector& nums, int target) { - auto l=lower_bound(nums.begin(),nums.end(),target)-nums.begin(); - return l==nums.size()||nums[l]!=target?vector{-1,-1}:vector {l,upper_bound(nums.begin(),nums.end(),target)-nums.begin()-1}; - } -}; \ No newline at end of file diff --git a/cpp/34.cpp b/cpp/34.cpp new file mode 100644 index 0000000..c7eb434 --- /dev/null +++ b/cpp/34.cpp @@ -0,0 +1,34 @@ +class Solution { + int lower_bound(vector& nums, int target) { + int left = 0, right = nums.size(); + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] < target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } + int upper_bound(vector& nums, int target) { + int left = 0, right = nums.size(); + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] <= target) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } + +public: + vector searchRange(vector& nums, int target) { + int left = lower_bound(nums, target); + if (left == nums.size() || nums[left] != target) + return {-1, -1}; + return {left, upper_bound(nums, target) - 1}; + } +}; \ No newline at end of file diff --git a/cpp/342.PowerOfFour/bits-feature-3ms.cpp b/cpp/342.PowerOfFour/bits-feature-3ms.cpp deleted file mode 100644 index b6d2ea6..0000000 --- a/cpp/342.PowerOfFour/bits-feature-3ms.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - bool isPowerOfFour(int num) { - return ( (num&(num-1))==0 ) && ((num&0x55555555)==num) && (num>0); - } -}; diff --git a/cpp/342.cpp b/cpp/342.cpp new file mode 100644 index 0000000..3bb4b4c --- /dev/null +++ b/cpp/342.cpp @@ -0,0 +1,7 @@ +// bits-feature-3ms.cpp +class Solution { +public: + bool isPowerOfFour(int num) { + return ((num & (num - 1)) == 0) && ((num & 0x55555555) == num) && (num > 0); + } +}; diff --git a/cpp/343.IntegerBreak/recursion.cpp b/cpp/343.IntegerBreak/recursion.cpp deleted file mode 100644 index fe63a74..0000000 --- a/cpp/343.IntegerBreak/recursion.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int integerBreak(int n) { - switch(n){ - case 2:return 1; - case 3:return 2; - } - return helper(n); - } - int helper(int n){ - if(n<=2) - return n; - if(n%3==0) - return pow(3,n/3); - return 2*helper(n-2); - } -}; diff --git a/cpp/343.cpp b/cpp/343.cpp new file mode 100644 index 0000000..91a3660 --- /dev/null +++ b/cpp/343.cpp @@ -0,0 +1,20 @@ +// recursion.cpp +class Solution { +public: + int integerBreak(int n) { + switch (n) { + case 2: + return 1; + case 3: + return 2; + } + return helper(n); + } + int helper(int n) { + if (n <= 2) + return n; + if (n % 3 == 0) + return pow(3, n / 3); + return 2 * helper(n - 2); + } +}; diff --git a/cpp/344.ReverseString/reverse.cpp b/cpp/344.ReverseString/reverse.cpp deleted file mode 100644 index 159908f..0000000 --- a/cpp/344.ReverseString/reverse.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - string reverseString(string s) { - int len=s.size(); - if(len==0)return s; - char temp; - for(int i=0;i='A'&&ch<='Z') - ch=ch-'A'+'a'; - return ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'; - } -}; diff --git a/cpp/345.cpp b/cpp/345.cpp new file mode 100644 index 0000000..3d0e737 --- /dev/null +++ b/cpp/345.cpp @@ -0,0 +1,26 @@ +// onepass-9ms.cpp +class Solution { +public: + string reverseVowels(string s) { + int i = 0, j = s.size() - 1; + while (i < j) { + if (!isVowels(s[i])) + ++i; + if (!isVowels(s[j])) + --j; + if (isVowels(s[i]) && isVowels(s[j])) { + char temp = s[j]; + s[j] = s[i]; + s[i] = temp; + ++i; + --j; + } + } + return s; + } + bool isVowels(char ch) { + if (ch >= 'A' && ch <= 'Z') + ch = ch - 'A' + 'a'; + return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; + } +}; diff --git a/cpp/347.TopKFrequentElements/hashmap+bucketsort+29ms.cpp b/cpp/347.TopKFrequentElements/hashmap+bucketsort+29ms.cpp deleted file mode 100644 index b82f8a1..0000000 --- a/cpp/347.TopKFrequentElements/hashmap+bucketsort+29ms.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - vector topKFrequent(vector& nums, int k) { - unordered_maphashmap; - for(auto num:nums) - hashmap[num]++; - int i,j,n=nums.size(); - vector>res(n); - for(auto pairs:hashmap) - res[pairs.second-1].emplace_back(pairs.first); - vectorr(k); - for(i=0,j=n-1;i0){ - r[i++]=res[j].back(); - res[j].pop_back(); - } - else - --j; - return r; - } -}; diff --git a/cpp/347.TopKFrequentElements/hashmap+heap+19ms.cpp b/cpp/347.TopKFrequentElements/hashmap+heap+19ms.cpp deleted file mode 100644 index b790c36..0000000 --- a/cpp/347.TopKFrequentElements/hashmap+heap+19ms.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - vector topKFrequent(vector& nums, int k) { - unordered_maphashmap; - for(auto num:nums) - hashmap[num]++; - vector< pair >res(hashmap.size()); - int i=0; - for(auto pairs:hashmap) - res[i++]=pairs; - vectorr(k); - make_heap(res.begin(),res.end(),[](pair&a,pair&b){return a.second&a,pair&b){return a.second topKFrequent(vector& nums, int k) { - unordered_maphashmap; - vectorres(k); - multimaptreemap; - for(auto num:nums) - hashmap[num]++; - for(auto pairs:hashmap) - treemap.insert(make_pair(pairs.second,pairs.first)); - int i=0; - for(auto it=treemap.rbegin();isecond; - return res; - } -}; diff --git a/cpp/347.cpp b/cpp/347.cpp new file mode 100644 index 0000000..6ac6aa3 --- /dev/null +++ b/cpp/347.cpp @@ -0,0 +1,64 @@ +// hashmap+bucketsort+29ms.cpp +class Solution { +public: + vector topKFrequent(vector &nums, int k) { + unordered_map hashmap; + for (auto num : nums) + hashmap[num]++; + int i, j, n = nums.size(); + vector> res(n); + for (auto pairs : hashmap) + res[pairs.second - 1].emplace_back(pairs.first); + vector r(k); + for (i = 0, j = n - 1; i < k;) + if (res[j].size() > 0) { + r[i++] = res[j].back(); + res[j].pop_back(); + } else + --j; + return r; + } +}; +// hashmap+heap+19ms.cpp +class Solution2 { +public: + vector topKFrequent(vector &nums, int k) { + unordered_map hashmap; + for (auto num : nums) + hashmap[num]++; + vector> res(hashmap.size()); + int i = 0; + for (auto pairs : hashmap) + res[i++] = pairs; + vector r(k); + make_heap(res.begin(), res.end(), [](pair &a, pair &b) { + return a.second < b.second; + }); + for (i = 0; i < k;) { + r[i++] = res.front().first; + pop_heap(res.begin(), res.end(), + [](pair &a, pair &b) { + return a.second < b.second; + }); + res.pop_back(); + } + return r; + } +}; +// hashmap+multimap+22ms.cpp +class Solution3 { +public: + vector topKFrequent(vector &nums, int k) { + unordered_map hashmap; + vector res(k); + multimap treemap; + for (auto num : nums) + hashmap[num]++; + for (auto pairs : hashmap) + treemap.insert(make_pair(pairs.second, pairs.first)); + int i = 0; + for (auto it = treemap.rbegin(); i < k; ++it) + res[i++] = it->second; + return res; + } +}; diff --git a/cpp/349.IntersectionOfTwoArrays/hash.cpp b/cpp/349.IntersectionOfTwoArrays/hash.cpp deleted file mode 100644 index 206c4ed..0000000 --- a/cpp/349.IntersectionOfTwoArrays/hash.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - vector intersection(vector& nums1, vector& nums2) { - unordered_mapmap; - vectorres; - for(int i=0;i intersection(vector &nums1, vector &nums2) { + unordered_map map; + vector res; + for (int i = 0; i < nums1.size(); ++i) + map[nums1[i]] = 1; + for (int i = 0; i < nums2.size(); map[nums2[i]] = 0, ++i) + if (map[nums2[i]] == 1) + res.push_back(nums2[i]); + return res; + } +}; diff --git a/cpp/35.SearchInsertPosition.cpp b/cpp/35.SearchInsertPosition.cpp deleted file mode 100644 index 57b8f87..0000000 --- a/cpp/35.SearchInsertPosition.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { // 8ms -public: - int searchInsert(vector& nums, int target) { - int l=0,r=nums.size(); - while(l& nums, int target) { + int l = 0, r = nums.size(); + while (l < r) { + int m = l + (r - l) / 2; + if (nums[m] == target) + return m; + else if (nums[m] < target) + l = m + 1; + else + r = m; + } + return l; + } +}; +class Solution2 { +public: + int searchInsert(vector& nums, int target) { + auto it = lower_bound(nums.begin(), nums.end(), target); + return it == nums.end() ? nums.size() : it - nums.begin(); + } +}; \ No newline at end of file diff --git a/cpp/350.IntersectionOfTwoArraysII/hash.cpp b/cpp/350.IntersectionOfTwoArraysII/hash.cpp deleted file mode 100644 index 93f4602..0000000 --- a/cpp/350.IntersectionOfTwoArraysII/hash.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - vector intersect(vector& nums1, vector& nums2) { - unordered_mapmap; - for(auto i:nums1) - ++map[i]; - vectorresult; - for(auto i:nums2) - if(map[i]-->0) - result.push_back(i); - return result; - } -}; diff --git a/cpp/350.cpp b/cpp/350.cpp new file mode 100644 index 0000000..b48b512 --- /dev/null +++ b/cpp/350.cpp @@ -0,0 +1,14 @@ +// hash.cpp +class Solution { +public: + vector intersect(vector &nums1, vector &nums2) { + unordered_map map; + for (auto i : nums1) + ++map[i]; + vector result; + for (auto i : nums2) + if (map[i]-- > 0) + result.push_back(i); + return result; + } +}; diff --git a/cpp/355.DesignTwitter/priority_queue.cpp b/cpp/355.DesignTwitter/priority_queue.cpp deleted file mode 100644 index 022da7f..0000000 --- a/cpp/355.DesignTwitter/priority_queue.cpp +++ /dev/null @@ -1,61 +0,0 @@ -class Twitter { - struct ctx{ - int userId; - vector< pair >::reverse_iterator it; - }; - struct comp{ - bool operator ()(ctx &c1,ctx&c2){ - return c1.it->first < c2.it->first; - } - }; - unsigned int time; - unordered_map >>feed;//pair - unordered_map>following; -public: - /** Initialize your data structure here. */ - Twitter():time(0) { - - } - - /** Compose a new tweet. */ - void postTweet(int userId, int tweetId) { - feed[userId].emplace_back( pair(time++,tweetId)); - } - - /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ - vector getNewsFeed(int userId) { - this->follow(userId,userId); - priority_queue,comp>qe; - for(auto &p:following[userId]) - if(feed[p].size()) - qe.push( ctx{p,feed[p].rbegin()}); - vectorres; - for(int i=0;i<10&&qe.size();++i){ - ctx c=qe.top(); - qe.pop(); - res.push_back(c.it->second); - if(++c.it!=feed[c.userId].rend()) - qe.push(ctx{c.userId,c.it}); - } - return res; - } - - /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ - void follow(int followerId, int followeeId) { - following[followerId].insert(followeeId); - } - - /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ - void unfollow(int followerId, int followeeId) { - following[followerId].erase(followeeId); - } -}; - -/** - * Your Twitter object will be instantiated and called as such: - * Twitter obj = new Twitter(); - * obj.postTweet(userId,tweetId); - * vector param_2 = obj.getNewsFeed(userId); - * obj.follow(followerId,followeeId); - * obj.unfollow(followerId,followeeId); - */ diff --git a/cpp/355.cpp b/cpp/355.cpp new file mode 100644 index 0000000..8822106 --- /dev/null +++ b/cpp/355.cpp @@ -0,0 +1,63 @@ +// priority_queue.cpp +class Twitter { + struct ctx { + int userId; + vector>::reverse_iterator it; + }; + struct comp { + bool operator()(ctx &c1, ctx &c2) { return c1.it->first < c2.it->first; } + }; + unsigned int time; + unordered_map>> feed; // pair + unordered_map> following; + +public: + /** Initialize your data structure here. */ + Twitter() : time(0) {} + + /** Compose a new tweet. */ + void postTweet(int userId, int tweetId) { + feed[userId].emplace_back(pair(time++, tweetId)); + } + + /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item + * in the news feed must be posted by users who the user followed or by the + * user herself. Tweets must be ordered from most recent to least recent. */ + vector getNewsFeed(int userId) { + this->follow(userId, userId); + priority_queue, comp> qe; + for (auto &p : following[userId]) + if (feed[p].size()) + qe.push(ctx{p, feed[p].rbegin()}); + vector res; + for (int i = 0; i < 10 && qe.size(); ++i) { + ctx c = qe.top(); + qe.pop(); + res.push_back(c.it->second); + if (++c.it != feed[c.userId].rend()) + qe.push(ctx{c.userId, c.it}); + } + return res; + } + + /** Follower follows a followee. If the operation is invalid, it should be a + * no-op. */ + void follow(int followerId, int followeeId) { + following[followerId].insert(followeeId); + } + + /** Follower unfollows a followee. If the operation is invalid, it should be a + * no-op. */ + void unfollow(int followerId, int followeeId) { + following[followerId].erase(followeeId); + } +}; + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter obj = new Twitter(); + * obj.postTweet(userId,tweetId); + * vector param_2 = obj.getNewsFeed(userId); + * obj.follow(followerId,followeeId); + * obj.unfollow(followerId,followeeId); + */ diff --git a/cpp/357.CountNumbersWithUniqueDigits/NotTheBest.cpp b/cpp/357.CountNumbersWithUniqueDigits/NotTheBest.cpp deleted file mode 100644 index bb665f9..0000000 --- a/cpp/357.CountNumbersWithUniqueDigits/NotTheBest.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int countNumbersWithUniqueDigits(int n) { - if(n>10) - n=0; - int res=0; - for(int i=0;i 10) + n = 0; + int res = 0; + for (int i = 0; i < n; ++i) { + long long int r = 9; + for (int j = 0; j < i; ++j) + r *= 9 - j; + res += r; + } + return res + 1; + } +}; diff --git a/cpp/36.ValidSudoku/timeO243_spaceO9.cpp b/cpp/36.ValidSudoku/timeO243_spaceO9.cpp deleted file mode 100644 index 5f3aee9..0000000 --- a/cpp/36.ValidSudoku/timeO243_spaceO9.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { -public: - bool isValidSudoku(vector>& board) { - vectornine(9,0); - for(int i=0;i<9;++i){ - nine.assign(9,0); - for(int j=0;j<9;++j) - if(board[i][j]!='.') - if(nine[board[i][j]-'1']++>0) - return 0; - } - for(int i=0;i<9;++i){ - nine.assign(9,0); - for(int j=0;j<9;++j) - if(board[j][i]!='.') - if(nine[board[j][i]-'1']++>0) - return 0; - } - for(int m=0;m<9;++m){ - nine.assign(9,0); - for(int i=m/3*3;i0) - return 0; - } - return 1; - } -}; diff --git a/cpp/36.ValidSudoku/timeO81_spaceO243.cpp b/cpp/36.ValidSudoku/timeO81_spaceO243.cpp deleted file mode 100644 index db8f1af..0000000 --- a/cpp/36.ValidSudoku/timeO81_spaceO243.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - bool isValidSudoku(vector>& board) { - int ver[9][9]={0},hor[9][9]={0},chunk[9][9]={0},num; - for(int i=0;i<9;++i) - for(int j=0;j<9;++j) - if((num=board[i][j])!='.') - if(ver[i][num-'1']++>0||hor[j][num-'1']++>0||chunk[i/3*3+j/3][num-'1']++>0) - return 0; - return 1; - } -}; diff --git a/cpp/36.cpp b/cpp/36.cpp new file mode 100644 index 0000000..565d809 --- /dev/null +++ b/cpp/36.cpp @@ -0,0 +1,44 @@ +// timeO243_spaceO9.cpp +class Solution { +public: + bool isValidSudoku(vector>& board) { + for (int i = 0; i < 9; ++i) { + int nine[9] = {}; + for (int j = 0; j < 9; ++j) + if (board[i][j] != '.') + if (nine[board[i][j] - '1']++ > 0) + return 0; + } + for (int i = 0; i < 9; ++i) { + int nine[9] = {}; + for (int j = 0; j < 9; ++j) + if (board[j][i] != '.') + if (nine[board[j][i] - '1']++ > 0) + return 0; + } + for (int m = 0; m < 9; ++m) { + int nine[9] = {}; + for (int i = m / 3 * 3; i < m / 3 * 3 + 3; ++i) + for (int j = 3 * (m % 3); j < 3 * (m % 3) + 3; ++j) + if (board[i][j] != '.') + if (nine[board[i][j] - '1']++ > 0) + return 0; + } + return 1; + } +}; +// timeO81_spaceO243.cpp +class Solution2 { +public: + bool isValidSudoku(vector>& board) { + int ver[9][9] = {}, hor[9][9] = {}, chunk[9][9] = {}; + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 9; ++j) + if (board[i][j] != '.') + if (int num = board[i][j] - '1'; + ver[i][num]++ > 0 || hor[j][num]++ > 0 || + chunk[i / 3 * 3 + j / 3][num]++ > 0) + return 0; + return 1; + } +}; diff --git a/cpp/365.WaterAndJugProblem.cpp b/cpp/365.WaterAndJugProblem.cpp deleted file mode 100644 index d932d90..0000000 --- a/cpp/365.WaterAndJugProblem.cpp +++ /dev/null @@ -1,46 +0,0 @@ -class Solution { -//Runtime: 984 ms, faster than 5.08% of C++ online submissions for Water and Jug Problem. -//Memory Usage: 152.6 MB, less than 5.31% of C++ online submissions for Water and Jug Problem. -public: - bool canMeasureWater(int x, int y, int z) { - array,6>ops={ - [&](int &a,int &){ - a=x; - }, - [&](int &,int &b){ - b=y; - }, - [&](int &a,int &){ - a=0; - }, - [&](int &,int &b){ - b=0; - }, - [&](int &a,int &b){ - auto diff=min(y-b,a); - a-=diff; - b+=diff; - }, - [&](int &a,int &b){ - auto diff=min(x-a,b); - a+=diff; - b-=diff; - } - }; - unordered_setseen{0}; - deque> dq{{0,0}}; - while(dq.size()){ - for(auto &op:ops){ - auto [a,b]=dq.front(); - op(a,b); - if(a==z or b==z or a+b==z) - return true; - auto [it,ok]=seen.insert(((long long)a<<32)+b); - if(ok) - dq.push_back({a,b}); - } - dq.pop_front(); - } - return false; - } -}; \ No newline at end of file diff --git a/cpp/365.cpp b/cpp/365.cpp new file mode 100644 index 0000000..ce1c594 --- /dev/null +++ b/cpp/365.cpp @@ -0,0 +1,37 @@ +class Solution { + // Runtime: 984 ms, faster than 5.08% of C++ online submissions for Water and + // Jug Problem. Memory Usage: 152.6 MB, less than 5.31% of C++ online + // submissions for Water and Jug Problem. +public: + bool canMeasureWater(int x, int y, int z) { + array, 6> ops = {[&](int &a, int &) { a = x; }, + [&](int &, int &b) { b = y; }, + [&](int &a, int &) { a = 0; }, + [&](int &, int &b) { b = 0; }, + [&](int &a, int &b) { + auto diff = min(y - b, a); + a -= diff; + b += diff; + }, + [&](int &a, int &b) { + auto diff = min(x - a, b); + a += diff; + b -= diff; + }}; + unordered_set seen{0}; + deque> dq{{0, 0}}; + while (dq.size()) { + for (auto &op : ops) { + auto [a, b] = dq.front(); + op(a, b); + if (a == z or b == z or a + b == z) + return true; + auto [it, ok] = seen.insert(((long long)a << 32) + b); + if (ok) + dq.push_back({a, b}); + } + dq.pop_front(); + } + return false; + } +}; \ No newline at end of file diff --git a/cpp/367.ValidPerfectSquare/1-0ms.cpp b/cpp/367.ValidPerfectSquare/1-0ms.cpp deleted file mode 100644 index 9652155..0000000 --- a/cpp/367.ValidPerfectSquare/1-0ms.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - bool isPerfectSquare(int num) { - if(num==0)return 0; - int i=1; - while(num>0){ - num-=i; - i+=2; - } - return num==0; - } -}; diff --git a/cpp/367.ValidPerfectSquare/2-0ms.cpp b/cpp/367.ValidPerfectSquare/2-0ms.cpp deleted file mode 100644 index a350eda..0000000 --- a/cpp/367.ValidPerfectSquare/2-0ms.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - bool isPerfectSquare(int num) { - int i=1,j=num; - while(i<=j){ - long long mid=(i+j)>>1; - if(mid*mid==num) - return 1; - else if(mid*mid>num) - j=mid-1; - else - i=mid+1; - } - return 0; - } -}; diff --git a/cpp/367.cpp b/cpp/367.cpp new file mode 100644 index 0000000..9574027 --- /dev/null +++ b/cpp/367.cpp @@ -0,0 +1,31 @@ +// 1-0ms.cpp +class Solution { +public: + bool isPerfectSquare(int num) { + if (num == 0) + return 0; + int i = 1; + while (num > 0) { + num -= i; + i += 2; + } + return num == 0; + } +}; +// 2-0ms.cpp +class Solution2 { +public: + bool isPerfectSquare(int num) { + int i = 1, j = num; + while (i <= j) { + long long mid = (i + j) >> 1; + if (mid * mid == num) + return 1; + else if (mid * mid > num) + j = mid - 1; + else + i = mid + 1; + } + return 0; + } +}; diff --git a/cpp/37.SudokuSolver/hashset+preprocess+dfs+3ms.cpp b/cpp/37.SudokuSolver/hashset+preprocess+dfs+3ms.cpp deleted file mode 100644 index 343b897..0000000 --- a/cpp/37.SudokuSolver/hashset+preprocess+dfs+3ms.cpp +++ /dev/null @@ -1,58 +0,0 @@ -class Solution { - bool valid(int i, int j, char val, vector>&board) { - for (int k = 0; k < 9; ++k) - if (board[k][j] == val || board[i][k] == val) - return false; - int x = i / 3 * 3; - int y = j / 3 * 3; - for (i = x; i < x + 3; ++i) - for (j = y; j < y + 3; ++j) - if (board[i][j] == val) - return false; - return true; - } - void init(vector>&board, unordered_sethashset[][9]) { - for (int i = 0; i<9; ++i) - for (int j = 0; j < 9; ++j) - if (board[i][j] != '.') { - char ch = board[i][j]; - for (int k = 0; k < 9; ++k) { - hashset[k][j].erase(ch); - hashset[i][k].erase(ch); - } - int x = i / 3 * 3; - int y = j / 3 * 3; - for (int a = x; a < x + 3; ++a) - for (int b = y; b < y + 3; ++b) - hashset[a][b].erase(ch); - } - } - bool dfs(int i, int j, vector>&board, unordered_sethashset[][9]) { - if (j == 9) { - return i == 8 ? true : dfs(i + 1, 0, board, hashset); - } - if (hashset[i][j].size() == 0) - return dfs(i, j + 1, board, hashset); - else { - for (auto it = hashset[i][j].begin(); it != hashset[i][j].end(); ++it) { - if (valid(i, j, *it, board)) { - board[i][j] = *it; - if (dfs(i, j + 1, board, hashset)) - return true; - board[i][j] = 0; - } - } - return false; - } - } -public: - void solveSudoku(vector>& board) { - unordered_sethashset[9][9]; - for (int i = 0; i < 9; ++i) - for (int j = 0; j < 9; ++j) - if (board[i][j] == '.') - hashset[i][j] = { '1','2','3','4','5','6','7','8','9' }; - init(board, hashset); - dfs(0, 0, board, hashset); - } -}; diff --git a/cpp/37.cpp b/cpp/37.cpp new file mode 100644 index 0000000..619204e --- /dev/null +++ b/cpp/37.cpp @@ -0,0 +1,62 @@ +// hashset+preprocess+dfs+3ms.cpp +class Solution { + bool valid(int i, int j, char val, vector>& board) { + for (int k = 0; k < 9; ++k) + if (board[k][j] == val || board[i][k] == val) + return false; + int x = i / 3 * 3; + int y = j / 3 * 3; + for (i = x; i < x + 3; ++i) + for (j = y; j < y + 3; ++j) + if (board[i][j] == val) + return false; + return true; + } + void init(vector>& board, unordered_set hashset[][9]) { + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 9; ++j) + if (board[i][j] != '.') { + char ch = board[i][j]; + for (int k = 0; k < 9; ++k) { + hashset[k][j].erase(ch); + hashset[i][k].erase(ch); + } + int x = i / 3 * 3; + int y = j / 3 * 3; + for (int a = x; a < x + 3; ++a) + for (int b = y; b < y + 3; ++b) + hashset[a][b].erase(ch); + } + } + bool dfs(int i, int j, vector>& board, + unordered_set hashset[][9]) { + if (j == 9) { + return i == 8 ? true : dfs(i + 1, 0, board, hashset); + } + if (hashset[i][j].size() == 0) + return dfs(i, j + 1, board, hashset); + else { + for (auto ch : hashset[i][j]) { + if (valid(i, j, ch, board)) { + board[i][j] = ch; + if (dfs(i, j + 1, board, hashset)) + return true; + board[i][j] = '.'; + } + } + return false; + } + } + +public: + void solveSudoku(vector>& board) { + unordered_set hashset[9][9]; + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 9; ++j) + if (board[i][j] == '.') + hashset[i][j] = {'1', '2', '3', '4', '5', + '6', '7', '8', '9'}; + init(board, hashset); + dfs(0, 0, board, hashset); + } +}; diff --git a/cpp/371.SumOfTwoIntegers/O32.cpp b/cpp/371.SumOfTwoIntegers/O32.cpp deleted file mode 100644 index 2d31ac4..0000000 --- a/cpp/371.SumOfTwoIntegers/O32.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int getSum(unsigned int a,unsigned int b) { - if(a==0||b==0)return a|b; - int sum=0,c=0; - for(int i=0;(a!=0||b!=0||c!=0)&&i<32;++i,a>>=1,b>>=1){ - int aa=a&1,bb=b&1; - if( (aa^bb^c)==1)//1 or 3 one - sum=sum|(1<>= 1, b >>= 1) { + int aa = a & 1, bb = b & 1; + if ((aa ^ bb ^ c) == 1) // 1 or 3 one + sum = sum | (1 << i); + if ((aa == 1 && bb == 1) || (aa == 1 && c == 1) || + (bb == 1 && c == 1)) // 2 or 3 one + c = 1; + else + c = 0; + } + return sum; + } +}; diff --git a/cpp/374.GuessNumberHigherorLower/BinarySearch-0ms.cpp b/cpp/374.GuessNumberHigherorLower/BinarySearch-0ms.cpp deleted file mode 100644 index 2c149fd..0000000 --- a/cpp/374.GuessNumberHigherorLower/BinarySearch-0ms.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// Forward declaration of guess API. -// @param num, your guess -// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 -int guess(int num); - -class Solution { -public: - int guessNumber(int n) { - int i=1,j=n,mid; - while(i<=j){ - mid=i+(j-i)/2; - if(guess(mid)==-1) - j=mid-1; - else if(guess(mid)==1) - i=mid+1; - else if(guess(mid)==0) - return mid; - } - return 0; - } -}; diff --git a/cpp/374.cpp b/cpp/374.cpp new file mode 100644 index 0000000..336fc58 --- /dev/null +++ b/cpp/374.cpp @@ -0,0 +1,23 @@ +// BinarySearch-0ms.cpp +// Forward declaration of guess API. +// @param num, your guess +// @return -1 if my number is lower, 1 if my number is higher, otherwise return +// 0 +int guess(int num); + +class Solution { +public: + int guessNumber(int n) { + int i = 1, j = n, mid; + while (i <= j) { + mid = i + (j - i) / 2; + if (guess(mid) == -1) + j = mid - 1; + else if (guess(mid) == 1) + i = mid + 1; + else if (guess(mid) == 0) + return mid; + } + return 0; + } +}; diff --git a/cpp/376.WiggleSubsequence.cpp b/cpp/376.WiggleSubsequence.cpp deleted file mode 100644 index ecebe62..0000000 --- a/cpp/376.WiggleSubsequence.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 86.10% of C++ online submissions for Wiggle Subsequence. -//Memory Usage: 8.8 MB, less than 7.24% of C++ online submissions for Wiggle Subsequence. -public: - int wiggleMaxLength(vector& nums) { - if (nums.size() == 0) return 0; - int up = 1, down = 1; - for (int i = 1; i < nums.size(); ++i) - if (nums[i] > nums[i-1]) - up = down + 1; - else if (nums[i] < nums[i-1]) - down = up + 1; - return max(up, down); - } -}; \ No newline at end of file diff --git a/cpp/376.cpp b/cpp/376.cpp new file mode 100644 index 0000000..9f19613 --- /dev/null +++ b/cpp/376.cpp @@ -0,0 +1,17 @@ +class Solution { + // Runtime: 4 ms, faster than 86.10% of C++ online submissions for Wiggle + // Subsequence. Memory Usage: 8.8 MB, less than 7.24% of C++ online + // submissions for Wiggle Subsequence. +public: + int wiggleMaxLength(vector &nums) { + if (nums.size() == 0) + return 0; + int up = 1, down = 1; + for (int i = 1; i < nums.size(); ++i) + if (nums[i] > nums[i - 1]) + up = down + 1; + else if (nums[i] < nums[i - 1]) + down = up + 1; + return max(up, down); + } +}; \ No newline at end of file diff --git a/cpp/377.CombinationSumIV/dp.cpp b/cpp/377.CombinationSumIV/dp.cpp deleted file mode 100644 index e16f166..0000000 --- a/cpp/377.CombinationSumIV/dp.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int combinationSum4(vector& nums, int target) { - vectordp(target+1,0); - dp[0]=1; - sort(nums.begin(),nums.end()); - for(int i=1;i<=target;++i) - for(int j=0;j=nums[j];++j) - dp[i]+=dp[i-nums[j]]; - return dp[target]; - } -}; diff --git a/cpp/377.cpp b/cpp/377.cpp new file mode 100644 index 0000000..dbd3c40 --- /dev/null +++ b/cpp/377.cpp @@ -0,0 +1,13 @@ +// dp.cpp +class Solution { +public: + int combinationSum4(vector &nums, int target) { + vector dp(target + 1, 0); + dp[0] = 1; + sort(nums.begin(), nums.end()); + for (int i = 1; i <= target; ++i) + for (int j = 0; j < nums.size() && i >= nums[j]; ++j) + dp[i] += dp[i - nums[j]]; + return dp[target]; + } +}; diff --git a/cpp/378.KthSmallestElementInASortedMatrix/priority_queue.cpp b/cpp/378.KthSmallestElementInASortedMatrix/priority_queue.cpp deleted file mode 100644 index 43378f1..0000000 --- a/cpp/378.KthSmallestElementInASortedMatrix/priority_queue.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { - struct Node{ - int x,y; - int val; - }; - struct compare{ - bool operator()(Node& a, Node& b){ - return a.val>b.val; - } - }; -public: - int kthSmallest(vector>& matrix, int k) { - int row=matrix.size(),col=matrix[0].size(); - vector< vector >visited(row,vector(col,0)); - priority_queue,compare>qe; - qe.push( Node{0,0,matrix[0][0]}); - visited[0][0]=1; - while(--k){ - Node cur=qe.top(); - if(cur.x+1>& matrix, int k) { - multisetres; - for(auto &arr:matrix) - res.insert(arr.begin(),arr.end()); - auto it=res.begin(); - for(int i=1;i>& matrix, int k) { - vectorres; - for(auto &arr:matrix) - res.insert(res.end(),arr.begin(),arr.end()); - sort(res.begin(),res.end()); - return res[k-1]; - } -}; diff --git a/cpp/378.cpp b/cpp/378.cpp new file mode 100644 index 0000000..4a1d87e --- /dev/null +++ b/cpp/378.cpp @@ -0,0 +1,55 @@ +// priority_queue.cpp +class Solution { + struct Node { + int x, y; + int val; + }; + struct compare { + bool operator()(Node &a, Node &b) { return a.val > b.val; } + }; + +public: + int kthSmallest(vector> &matrix, int k) { + int row = matrix.size(), col = matrix[0].size(); + vector> visited(row, vector(col, 0)); + priority_queue, compare> qe; + qe.push(Node{0, 0, matrix[0][0]}); + visited[0][0] = 1; + while (--k) { + Node cur = qe.top(); + if (cur.x + 1 < row && visited[cur.x + 1][cur.y] == 0) { + qe.push(Node{cur.x + 1, cur.y, matrix[cur.x + 1][cur.y]}); + visited[cur.x + 1][cur.y] = 1; + } + if (cur.y + 1 < col && visited[cur.x][cur.y + 1] == 0) { + qe.push(Node{cur.x, cur.y + 1, matrix[cur.x][cur.y + 1]}); + visited[cur.x][cur.y + 1] = 1; + } + qe.pop(); + } + return qe.top().val; + } +}; +// sort.cpp +class Solution2 { +public: + int kthSmallest(vector> &matrix, int k) { + multiset res; + for (auto &arr : matrix) + res.insert(arr.begin(), arr.end()); + auto it = res.begin(); + for (int i = 1; i < k; ++i) + ++it; + return *it; + } +}; +class Solution3 { +public: + int kthSmallest(vector> &matrix, int k) { + vector res; + for (auto &arr : matrix) + res.insert(res.end(), arr.begin(), arr.end()); + sort(res.begin(), res.end()); + return res[k - 1]; + } +}; diff --git a/cpp/38.CountAndSay.cpp b/cpp/38.CountAndSay.cpp deleted file mode 100644 index d6de933..0000000 --- a/cpp/38.CountAndSay.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { // 4ms -public: - string countAndSay(int n) { - auto next=[](const string &s){ - int i=0,j=1,n=s.size(); - string ss; - for(;j nums; - unordered_map m; -public: - /** Initialize your data structure here. */ - RandomizedSet() { - - } - - /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ - bool insert(int val) { - if (m.find(val) != m.end()) return false; - nums.emplace_back(val); - m[val] = nums.size() - 1; - return true; - } - - /** Removes a value from the set. Returns true if the set contained the specified element. */ - bool remove(int val) { - if (auto it=m.find(val);it == m.end()) - return false; - else{ - m[nums.back()] = it->second; - nums[it->second] = nums.back(); - nums.pop_back(); - m.erase(it); - return true; - } - } - - /** Get a random element from the set. */ - int getRandom() { - return nums[rand() % nums.size()]; - } -}; - -/** - * Your RandomizedSet object will be instantiated and called as such: - * RandomizedSet* obj = new RandomizedSet(); - * bool param_1 = obj->insert(val); - * bool param_2 = obj->remove(val); - * int param_3 = obj->getRandom(); - */ \ No newline at end of file diff --git a/cpp/380.cpp b/cpp/380.cpp new file mode 100644 index 0000000..53a0fe6 --- /dev/null +++ b/cpp/380.cpp @@ -0,0 +1,43 @@ +class RandomizedSet { + vector nums; + unordered_map m; + +public: + /** Initialize your data structure here. */ + RandomizedSet() {} + + /** Inserts a value to the set. Returns true if the set did not already + * contain the specified element. */ + bool insert(int val) { + if (m.find(val) != m.end()) + return false; + nums.emplace_back(val); + m[val] = nums.size() - 1; + return true; + } + + /** Removes a value from the set. Returns true if the set contained the + * specified element. */ + bool remove(int val) { + if (auto it = m.find(val); it == m.end()) + return false; + else { + m[nums.back()] = it->second; + nums[it->second] = nums.back(); + nums.pop_back(); + m.erase(it); + return true; + } + } + + /** Get a random element from the set. */ + int getRandom() { return nums[rand() % nums.size()]; } +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet* obj = new RandomizedSet(); + * bool param_1 = obj->insert(val); + * bool param_2 = obj->remove(val); + * int param_3 = obj->getRandom(); + */ \ No newline at end of file diff --git a/cpp/382.LinkedListRandomNode/WTF.cpp b/cpp/382.LinkedListRandomNode/WTF.cpp deleted file mode 100644 index 2cdb809..0000000 --- a/cpp/382.LinkedListRandomNode/WTF.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - vectorarr; -public: - /** @param head The linked list's head. - Note that the head is guaranteed to be not null, so it contains at least one node. */ - Solution(ListNode* head) { - while(head!=nullptr){ - arr.push_back(head); - head=head->next; - } - } - - /** Returns a random node's value. */ - int getRandom() { - return arr[(rand()%arr.size())]->val; - } -}; - -/** - * Your Solution object will be instantiated and called as such: - * Solution obj = new Solution(head); - * int param_1 = obj.getRandom(); - */ diff --git a/cpp/382.cpp b/cpp/382.cpp new file mode 100644 index 0000000..e46def3 --- /dev/null +++ b/cpp/382.cpp @@ -0,0 +1,32 @@ +// WTF.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { + vector arr; + +public: + /** @param head The linked list's head. + Note that the head is guaranteed to be not null, so it contains at least + one node. */ + Solution(ListNode *head) { + while (head != nullptr) { + arr.push_back(head); + head = head->next; + } + } + + /** Returns a random node's value. */ + int getRandom() { return arr[(rand() % arr.size())]->val; } +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(head); + * int param_1 = obj.getRandom(); + */ diff --git a/cpp/383.RansomNote/hash-25ms.cpp b/cpp/383.RansomNote/hash-25ms.cpp deleted file mode 100644 index 5ab9eb6..0000000 --- a/cpp/383.RansomNote/hash-25ms.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - bool canConstruct(string ransomNote, string magazine) { - int a[58]={},b[58]={}; - for(int i=0;ib[i])return 0; - return 1; - } -}; diff --git a/cpp/383.cpp b/cpp/383.cpp new file mode 100644 index 0000000..6408996 --- /dev/null +++ b/cpp/383.cpp @@ -0,0 +1,15 @@ +// hash-25ms.cpp +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + int a[58] = {}, b[58] = {}; + for (int i = 0; i < ransomNote.size(); ++i) + ++a[ransomNote[i] - 'A']; + for (int i = 0; i < magazine.size(); ++i) + ++b[magazine[i] - 'A']; + for (int i = 0; i < 58; ++i) + if (a[i] > b[i]) + return 0; + return 1; + } +}; diff --git a/cpp/384.ShuffleAnArray/WTF.cpp b/cpp/384.ShuffleAnArray/WTF.cpp deleted file mode 100644 index 794091b..0000000 --- a/cpp/384.ShuffleAnArray/WTF.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution { - vectorarr; -public: - Solution(vector nums) { - arr=nums; - } - - /** Resets the array to its original configuration and return it. */ - vector reset() { - return arr; - } - - /** Returns a random shuffling of the array. */ - vector shuffle() { - vector result(arr); - int n=result.size(); - for (int i = 0;i < n;i++) { - int pos = rand()%n; - swap(result[pos], result[i]); - } - return result; - } -}; - -/** - * Your Solution object will be instantiated and called as such: - * Solution obj = new Solution(nums); - * vector param_1 = obj.reset(); - * vector param_2 = obj.shuffle(); - */ diff --git a/cpp/384.cpp b/cpp/384.cpp new file mode 100644 index 0000000..6858f50 --- /dev/null +++ b/cpp/384.cpp @@ -0,0 +1,28 @@ +// WTF.cpp +class Solution { + vector arr; + +public: + Solution(vector nums) { arr = nums; } + + /** Resets the array to its original configuration and return it. */ + vector reset() { return arr; } + + /** Returns a random shuffling of the array. */ + vector shuffle() { + vector result(arr); + int n = result.size(); + for (int i = 0; i < n; i++) { + int pos = rand() % n; + swap(result[pos], result[i]); + } + return result; + } +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(nums); + * vector param_1 = obj.reset(); + * vector param_2 = obj.shuffle(); + */ diff --git a/cpp/386.LexicographicalNumbers.cpp b/cpp/386.LexicographicalNumbers.cpp deleted file mode 100644 index 4c24571..0000000 --- a/cpp/386.LexicographicalNumbers.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -//Runtime: 72 ms, faster than 75.46% of C++ online submissions for Lexicographical Numbers. -//Memory Usage: 11 MB, less than 94.00% of C++ online submissions for Lexicographical Numbers. -public: - vector lexicalOrder(int n) { - if(n<=0) - return {}; - vectorret(n); - int i=0; - functiondfs=[&](int now){ - ret[i++]=now; - if(now*10<=n) - dfs(now*10); - if(now+1<=n and now%10<9) - dfs(now+1); - }; - dfs(1); - return ret; - } -}; \ No newline at end of file diff --git a/cpp/386.LexicographicalNumbers/TLE-to_string+sort.cpp b/cpp/386.LexicographicalNumbers/TLE-to_string+sort.cpp deleted file mode 100644 index c5cb973..0000000 --- a/cpp/386.LexicographicalNumbers/TLE-to_string+sort.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - vector lexicalOrder(int n) { - vectorres; - vectortemp; - for(int i=1;i<=n;++i){ - temp.emplace_back(std::move(to_string(i))); - } - sort(temp.begin(),temp.end()); - for(auto &str:temp) - res.emplace_back(stoi(str)); - return res; - } -}; diff --git a/cpp/386.cpp b/cpp/386.cpp new file mode 100644 index 0000000..6196395 --- /dev/null +++ b/cpp/386.cpp @@ -0,0 +1,21 @@ +class Solution { + // Runtime: 72 ms, faster than 75.46% of C++ online submissions for + // Lexicographical Numbers. Memory Usage: 11 MB, less than 94.00% of C++ + // online submissions for Lexicographical Numbers. +public: + vector lexicalOrder(int n) { + if (n <= 0) + return {}; + vector ret(n); + int i = 0; + function dfs = [&](int now) { + ret[i++] = now; + if (now * 10 <= n) + dfs(now * 10); + if (now + 1 <= n and now % 10 < 9) + dfs(now + 1); + }; + dfs(1); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/387.FirstUniqueCharacterInAString/hash.cpp b/cpp/387.FirstUniqueCharacterInAString/hash.cpp deleted file mode 100644 index 23ed223..0000000 --- a/cpp/387.FirstUniqueCharacterInAString/hash.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int firstUniqChar(string s) { - unordered_mapmap; - for(int i=0;i map; + for (int i = 0; i < s.size(); ++i) + map[s[i]]++; + for (int i = 0; i < s.size(); ++i) + if (map[s[i]] == 1) + return i; + return -1; + } +}; diff --git a/cpp/388.LongestAbsoluteFilePath/singleScan.cpp b/cpp/388.LongestAbsoluteFilePath/singleScan.cpp deleted file mode 100644 index 72ddb66..0000000 --- a/cpp/388.LongestAbsoluteFilePath/singleScan.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - int lengthLongestPath(string input) { - stringstream ss(input); - string str; - vectorlens; - int maxlen=0,curtotal=0; - while(ss){ - getline(ss,str); - int tcount=0; - while(str[tcount]=='\t') - ++tcount; - int curlen=str.size()-tcount+1; - for(;tcount lens; + int maxlen = 0, curtotal = 0; + while (ss) { + getline(ss, str); + int tcount = 0; + while (str[tcount] == '\t') + ++tcount; + int curlen = str.size() - tcount + 1; + for (; tcount < lens.size(); lens.pop_back()) + curtotal -= lens.back(); + lens.push_back(curlen); + curtotal += curlen; + if (str.find('.') != string::npos) + maxlen = max(maxlen, curtotal); + } + return maxlen == 0 ? 0 : maxlen - 1; + } +}; diff --git a/cpp/389.FindTheDifference/hash-3ms.cpp b/cpp/389.FindTheDifference/hash-3ms.cpp deleted file mode 100644 index bf7c703..0000000 --- a/cpp/389.FindTheDifference/hash-3ms.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - char findTheDifference(string s, string t) { - int *a=new int[26](); - int *b=new int[26](); - for(int i=0;i>res; -public: - vector> combinationSum(vector& candidates, int target) { - this->target=target; - vectorcur; - dfs(candidates,cur,0,0); - return res; - } - void dfs(vector&nums,vector&cur,int i,int sum){ - if(sum==target){ - res.push_back(cur); - return ; - } - if(i==nums.size()||sum>target) - return; - cur.push_back(nums[i]); - dfs(nums,cur,i,sum+nums[i]); - cur.pop_back(); - dfs(nums,cur,i+1,sum); - } -}; diff --git a/cpp/39.CombinationSum/sort_dfs.cpp b/cpp/39.CombinationSum/sort_dfs.cpp deleted file mode 100644 index e5ea448..0000000 --- a/cpp/39.CombinationSum/sort_dfs.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { - vector>res; -public: - vector> combinationSum(vector& candidates, int target) { - sort(candidates.begin(),candidates.end()); - vectorcur; - dfs(candidates,cur,0,target); - return res; - } - void dfs(vector&nums,vector&cur,int i,int sum){ - if(0==sum){ - res.push_back(cur); - return; - } - for(;i=nums[i];++i){ - cur.push_back(nums[i]); - dfs(nums,cur,i,sum-nums[i]); - cur.pop_back(); - } - } -}; diff --git a/cpp/39.cpp b/cpp/39.cpp new file mode 100644 index 0000000..8018e24 --- /dev/null +++ b/cpp/39.cpp @@ -0,0 +1,22 @@ +class Solution { + vector> res; + void dfs(vector& nums, vector& cur, int i, int sum) { + if (0 == sum) { + res.push_back(cur); + return; + } + for (; i < nums.size() && sum >= nums[i]; ++i) { + cur.push_back(nums[i]); + dfs(nums, cur, i, sum - nums[i]); + cur.pop_back(); + } + } + +public: + vector> combinationSum(vector& candidates, int target) { + ranges::sort(candidates); + vector cur; + dfs(candidates, cur, 0, target); + return res; + } +}; diff --git a/cpp/390.EliminationGame.cpp b/cpp/390.EliminationGame.cpp deleted file mode 100644 index c7fa4ce..0000000 --- a/cpp/390.EliminationGame.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -//Runtime: 8 ms, faster than 80.71% of C++ online submissions for Elimination Game. -//Memory Usage: 8.3 MB, less than 36.46% of C++ online submissions for Elimination Game. -public: - int lastRemaining(int n) { - functiondfs=[&dfs](int n,bool left){ - if(n==1) - return 1; - if(left) - return 2*dfs(n/2,!left); - else - return (n%2?0:-1)+2*dfs(n/2,!left); - }; - return dfs(n,true); - } -}; \ No newline at end of file diff --git a/cpp/390.cpp b/cpp/390.cpp new file mode 100644 index 0000000..4509a68 --- /dev/null +++ b/cpp/390.cpp @@ -0,0 +1,17 @@ +class Solution { + // Runtime: 8 ms, faster than 80.71% of C++ online submissions for Elimination + // Game. Memory Usage: 8.3 MB, less than 36.46% of C++ online submissions for + // Elimination Game. +public: + int lastRemaining(int n) { + function dfs = [&dfs](int n, bool left) { + if (n == 1) + return 1; + if (left) + return 2 * dfs(n / 2, !left); + else + return (n % 2 ? 0 : -1) + 2 * dfs(n / 2, !left); + }; + return dfs(n, true); + } +}; \ No newline at end of file diff --git a/cpp/392.IsSubsequence/onepass-106ms.cpp b/cpp/392.IsSubsequence/onepass-106ms.cpp deleted file mode 100644 index 0e5da61..0000000 --- a/cpp/392.IsSubsequence/onepass-106ms.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - bool isSubsequence(string s, string t) { - int i=0,j=0,slen=s.size(),tlen=t.size(); - for(;i& data) { - int status=0; - for(auto val:data){ - auto d=val&0xff; - if(status){ - if(not((d>>6)==0b10)) return false; - --status; - } - else{ - if((d>>7)==0); - else if((d>>5)==0b110) - status+=1; - else if((d>>4)==0b1110) - status+=2; - else if((d>>3)==0b11110) - status+=3; - else return false; - } - } - return status==0; - } -}; \ No newline at end of file diff --git a/cpp/393.cpp b/cpp/393.cpp new file mode 100644 index 0000000..a45d32e --- /dev/null +++ b/cpp/393.cpp @@ -0,0 +1,29 @@ +class Solution { + // Runtime: 16 ms, faster than 79.20% of C++ online submissions for UTF-8 + // Validation. Memory Usage: 9.5 MB, less than 59.65% of C++ online + // submissions for UTF-8 Validation. +public: + bool validUtf8(vector &data) { + int status = 0; + for (auto val : data) { + auto d = val & 0xff; + if (status) { + if (not((d >> 6) == 0b10)) + return false; + --status; + } else { + if ((d >> 7) == 0) + ; + else if ((d >> 5) == 0b110) + status += 1; + else if ((d >> 4) == 0b1110) + status += 2; + else if ((d >> 3) == 0b11110) + status += 3; + else + return false; + } + } + return status == 0; + } +}; \ No newline at end of file diff --git a/cpp/394.DecodeString.cpp b/cpp/394.DecodeString.cpp deleted file mode 100644 index bb4047e..0000000 --- a/cpp/394.DecodeString.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -//Runtime: 4 ms, faster than 84.37% of C++ online submissions for Decode String. -//Memory Usage: 8.7 MB, less than 91.46% of C++ online submissions for Decode String. -public: - string decodeString(string s) { - function recursion=[&recursion](auto s){ - string res; - for (int i=0;i recursion = [&recursion](auto s) { + string res; + for (int i = 0; i < s.length();) + if (!isdigit(s[i])) + res += s[i++]; + else { + int n = 0; + while (i < s.length() && isdigit(s[i])) + n = n * 10 + s[i++] - '0'; + int j = i + 1; + for (int count = 1; count; ++j) + if (s[j] == '[') + ++count; + else if (s[j] == ']') + --count; + for (auto t = + recursion(s.substr(i + 1, (j - 2) - (i + 1) + 1)); + n; --n) + res += t; + i = j; + } + return res; + }; + return recursion(s); + } + }; \ No newline at end of file diff --git a/cpp/395.LongestSubstringWithAtLeastKRepeatingCharacters.cpp b/cpp/395.LongestSubstringWithAtLeastKRepeatingCharacters.cpp deleted file mode 100644 index 36e732c..0000000 --- a/cpp/395.LongestSubstringWithAtLeastKRepeatingCharacters.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Longest Substring with At Least K Repeating Characters. -//Memory Usage: 8.8 MB, less than 74.27% of C++ online submissions for Longest Substring with At Least K Repeating Characters. -public: - int longestSubstring(string s, int k) { - int ret=0; - function dfs=[&](string_view ss){ - if(not ss.size()) return; - unordered_mapcounter; - for(auto ch:ss) - ++counter[ch]; - for(auto it=counter.begin();it!=counter.end();) - if(it->second>=k) - counter.erase(it++); - else - ++it; - if(counter.size()){ - int start=0; - for(int i=0;iret) - dfs(ss.substr(start,i-start)); - start=i+1; - } - dfs(ss.substr(start)); - } - else - ret=max(ret,(int)ss.size()); - }; - dfs(s); - return ret; - } -}; \ No newline at end of file diff --git a/cpp/395.cpp b/cpp/395.cpp new file mode 100644 index 0000000..441b19e --- /dev/null +++ b/cpp/395.cpp @@ -0,0 +1,35 @@ +class Solution { + // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Longest + // Substring with At Least K Repeating Characters. Memory Usage: 8.8 MB, less + // than 74.27% of C++ online submissions for Longest Substring with At Least K + // Repeating Characters. +public: + int longestSubstring(string s, int k) { + int ret = 0; + function dfs = [&](string_view ss) { + if (not ss.size()) + return; + unordered_map counter; + for (auto ch : ss) + ++counter[ch]; + for (auto it = counter.begin(); it != counter.end();) + if (it->second >= k) + counter.erase(it++); + else + ++it; + if (counter.size()) { + int start = 0; + for (int i = 0; i < ss.size(); ++i) + if (counter.count(ss[i])) { + if (i - start > ret) + dfs(ss.substr(start, i - start)); + start = i + 1; + } + dfs(ss.substr(start)); + } else + ret = max(ret, (int)ss.size()); + }; + dfs(s); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/396.RotateFunction.cpp b/cpp/396.RotateFunction.cpp deleted file mode 100644 index 9b08e3f..0000000 --- a/cpp/396.RotateFunction.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -//Runtime: 8 ms, faster than 96.67% of C++ online submissions for Rotate Function. -//Memory Usage: 9.7 MB, less than 14.48% of C++ online submissions for Rotate Function. -public: - int maxRotateFunction(vector& A) { - auto sum=0ll; - for(auto num:A) - sum+=num; - auto f0=0ll; - for(auto i=0ll;i &A) { + auto sum = 0ll; + for (auto num : A) + sum += num; + auto f0 = 0ll; + for (auto i = 0ll; i < A.size(); ++i) + f0 += i * A[i]; + auto ret = f0; + for (int i = 1; i < A.size(); ++i) + ret = max(ret, f0 = f0 + sum - (long long)A.size() * A[A.size() - i]); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/397.IntegerReplacement.cpp b/cpp/397.IntegerReplacement.cpp deleted file mode 100644 index 7bb9bcf..0000000 --- a/cpp/397.IntegerReplacement.cpp +++ /dev/null @@ -1,87 +0,0 @@ -class Solution { -//Memory Limit Exceeded -//Last executed input 100000000 -public: - int integerReplacement(int n) { - if(n==1) - return 0; - deque>dq{{1,0}}; - vectorvisited(2*n); - visited[0]=visited[1]=1; - array,3>ops={ - [](int a){return a*2;}, - [](int a){return a+1;}, - [](int a){return a-1;}, - }; - while(dq.size()){ - auto [k,count]=dq.front(); - for(auto &op:ops){ - auto nextk=op(k); - if(nextk>k and k>n) - continue; - if(nextk==n) - return count+1; - if(not visited[nextk]){ - visited[nextk]=1; - dq.push_back({nextk,count+1}); - } - } - dq.pop_front(); - } - return 0; - } -}; -class Solution { -//Time Limit Exceeded -//Last executed input 100000000 -public: - int integerReplacement(int n) { - if(n==1) - return 0; - deque>dq{{1,0}}; - vectorvisited(n+1); - unordered_setvisited2; - visited[0]=visited[1]=1; - array,3>ops={ - [](int a){return a*2;}, - [](int a){return a+1;}, - [](int a){return a-1;}, - }; - while(dq.size()){ - auto [k,count]=dq.front(); - for(auto &op:ops){ - auto nextk=op(k); - if(nextk>k and k>n) - continue; - if(nextk==n) - return count+1; - if(nextk<=n and not visited[nextk]){ - visited[nextk]=1; - dq.push_back({nextk,count+1}); - } - if(nextk>n and not visited2.count(nextk)){ - visited2.insert(nextk); - dq.push_back({nextk,count+1}); - } - } - dq.pop_front(); - } - return 0; - } -}; -class Solution { -//Runtime: 4 ms, faster than 88.22% of C++ online submissions for Integer Replacement. -//Memory Usage: 13 MB, less than 5.34% of C++ online submissions for Integer Replacement. - unordered_map visited; - int compute(long long n) { - if (n == 1) return 0; - auto it=visited.find(n); - if (it == end(visited)) - return (n & 1 == 1)?visited[n]=1+min(compute(n+1),compute(n-1)):visited[n]=1+compute(n/2); - return it->second; - } -public: - int integerReplacement(int n) { - return compute(n); - } -}; \ No newline at end of file diff --git a/cpp/397.cpp b/cpp/397.cpp new file mode 100644 index 0000000..e8ceee4 --- /dev/null +++ b/cpp/397.cpp @@ -0,0 +1,89 @@ +class Solution { + // Memory Limit Exceeded + // Last executed input 100000000 +public: + int integerReplacement(int n) { + if (n == 1) + return 0; + deque> dq{{1, 0}}; + vector visited(2 * n); + visited[0] = visited[1] = 1; + array, 3> ops = { + [](int a) { return a * 2; }, + [](int a) { return a + 1; }, + [](int a) { return a - 1; }, + }; + while (dq.size()) { + auto [k, count] = dq.front(); + for (auto &op : ops) { + auto nextk = op(k); + if (nextk > k and k > n) + continue; + if (nextk == n) + return count + 1; + if (not visited[nextk]) { + visited[nextk] = 1; + dq.push_back({nextk, count + 1}); + } + } + dq.pop_front(); + } + return 0; + } +}; +class Solution2 { + // Time Limit Exceeded + // Last executed input 100000000 +public: + int integerReplacement(int n) { + if (n == 1) + return 0; + deque> dq{{1, 0}}; + vector visited(n + 1); + unordered_set visited2; + visited[0] = visited[1] = 1; + array, 3> ops = { + [](int a) { return a * 2; }, + [](int a) { return a + 1; }, + [](int a) { return a - 1; }, + }; + while (dq.size()) { + auto [k, count] = dq.front(); + for (auto &op : ops) { + auto nextk = op(k); + if (nextk > k and k > n) + continue; + if (nextk == n) + return count + 1; + if (nextk <= n and not visited[nextk]) { + visited[nextk] = 1; + dq.push_back({nextk, count + 1}); + } + if (nextk > n and not visited2.count(nextk)) { + visited2.insert(nextk); + dq.push_back({nextk, count + 1}); + } + } + dq.pop_front(); + } + return 0; + } +}; +class Solution3 { + // Runtime: 4 ms, faster than 88.22% of C++ online submissions for Integer + // Replacement. Memory Usage: 13 MB, less than 5.34% of C++ online submissions + // for Integer Replacement. + unordered_map visited; + int compute(long long n) { + if (n == 1) + return 0; + auto it = visited.find(n); + if (it == end(visited)) + return (n & 1 == 1) ? visited[n] = 1 + min(compute(n + 1), compute(n - 1)) + : visited[n] = 1 + compute(n / 2); + return it->second; + } + +public: + int integerReplacement(int n) { return compute(n); } +}; \ No newline at end of file diff --git a/cpp/398.RandomPiclIndex/simple.cpp b/cpp/398.RandomPiclIndex/simple.cpp deleted file mode 100644 index 55cf135..0000000 --- a/cpp/398.RandomPiclIndex/simple.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { - unordered_maphashmap; - vectornums; -public: - Solution(vector nums) { - int n=nums.size(); - for(int i=0;inums=nums; - } - - int pick(int target) { - int index=rand()%hashmap[target]; - for(int i=0;i hashmap; + vector nums; + +public: + Solution(vector nums) { + int n = nums.size(); + for (int i = 0; i < n; ++i) + hashmap[nums[i]]++; + this->nums = nums; + } + + int pick(int target) { + int index = rand() % hashmap[target]; + for (int i = 0; i < nums.size(); ++i) + if (nums[i] == target) + if (index-- == 0) + return i; + } +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(nums); + * int param_1 = obj.pick(target); + */ diff --git a/cpp/399.EvaluateDivision.cpp b/cpp/399.EvaluateDivision.cpp deleted file mode 100644 index ddf9664..0000000 --- a/cpp/399.EvaluateDivision.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -//speed can be improved but it reach 0ms now -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Evaluate Division. -//Memory Usage: 9.3 MB, less than 81.50% of C++ online submissions for Evaluate Division. -public: - vector calcEquation(vector>& equations, vector& values, vector>& queries) { - using pp = pair; - using sv = string_view; - unordered_map>> children; - for (int i = 0; i < equations.size(); i++) { - children[equations[i][0]].push_back({equations[i][1], values[i]}); - children[equations[i][1]].push_back({equations[i][0], 1.0 / values[i]}); - } - unordered_set visited; - function dfs=[&dfs,&visited,&children](sv a, sv b, double val)->pp { - if(!visited.count(a)){ - visited.insert(a); - for (auto &p : children[a]) - if (p.first == b) - return {true, val * p.second}; - else if (auto result=dfs(p.first,b,val*p.second);result.first) - return result; - } - return {false, -1.0}; - }; - vector ans; - for (auto &p : queries) { - ans.push_back(p[0] == p[1] && children.count(p[0]) ? 1.0 : dfs(p[0], p[1], 1.0).second); - visited.clear(); - } - return ans; - } -}; \ No newline at end of file diff --git a/cpp/399.cpp b/cpp/399.cpp new file mode 100644 index 0000000..f37ef6b --- /dev/null +++ b/cpp/399.cpp @@ -0,0 +1,39 @@ +class Solution { + // speed can be improved but it reach 0ms now + // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Evaluate + // Division. Memory Usage: 9.3 MB, less than 81.50% of C++ online submissions + // for Evaluate Division. +public: + vector calcEquation(vector> &equations, + vector &values, + vector> &queries) { + using pp = pair; + using sv = string_view; + unordered_map>> children; + for (int i = 0; i < equations.size(); i++) { + children[equations[i][0]].push_back({equations[i][1], values[i]}); + children[equations[i][1]].push_back({equations[i][0], 1.0 / values[i]}); + } + unordered_set visited; + function dfs = + [&dfs, &visited, &children](sv a, sv b, double val) -> pp { + if (!visited.count(a)) { + visited.insert(a); + for (auto &p : children[a]) + if (p.first == b) + return {true, val * p.second}; + else if (auto result = dfs(p.first, b, val * p.second); result.first) + return result; + } + return {false, -1.0}; + }; + vector ans; + for (auto &p : queries) { + ans.push_back(p[0] == p[1] && children.count(p[0]) + ? 1.0 + : dfs(p[0], p[1], 1.0).second); + visited.clear(); + } + return ans; + } +}; \ No newline at end of file diff --git a/cpp/4.MedianOfTwoSortedArrays/findkthlarge.cpp b/cpp/4.MedianOfTwoSortedArrays/findkthlarge.cpp deleted file mode 100644 index 7333b5b..0000000 --- a/cpp/4.MedianOfTwoSortedArrays/findkthlarge.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - double findMedianSortedArrays(vector& nums1, vector& nums2) { - int n1=nums1.size(),n2=nums2.size(); - if(((n1+n2)&1)==0) - return (findKthBig(nums1,n1,nums2,n2,(n1+n2)/2)+findKthBig(nums1,n1,nums2,n2,(n1+n2)/2+1))/2.0; - return findKthBig(nums1,n1,nums2,n2,(n1+n2)/2+1); - } - int findKthBig(vector&nums1,int end1,vector&nums2,int end2,int k){ - if(end1>end2) - return findKthBig(nums2,end2,nums1,end1,k); - if(end1==0) - return nums2[end2-k]; - if(k==1) - return max(nums1[end1-1],nums2[end2-1]); - int p=min(k/2,end1); - if(nums1[end1-p]>nums2[end2-p]) - return findKthBig(nums1,end1-p,nums2,end2,k-p); - return findKthBig(nums1,end1,nums2,end2-p,k-p); - } -}; diff --git a/cpp/4.cpp b/cpp/4.cpp new file mode 100644 index 0000000..8be9e37 --- /dev/null +++ b/cpp/4.cpp @@ -0,0 +1,97 @@ +// findkthlarge.cpp +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int n1 = nums1.size(), n2 = nums2.size(); + if (((n1 + n2) & 1) == 0) + return (findKthBig(nums1, n1, nums2, n2, (n1 + n2) / 2) + + findKthBig(nums1, n1, nums2, n2, (n1 + n2) / 2 + 1)) / + 2.0; + return findKthBig(nums1, n1, nums2, n2, (n1 + n2) / 2 + 1); + } + int findKthBig(vector& nums1, int end1, vector& nums2, int end2, + int k) { + if (end1 > end2) + return findKthBig(nums2, end2, nums1, end1, k); + if (end1 == 0) + return nums2[end2 - k]; + if (k == 1) + return max(nums1[end1 - 1], nums2[end2 - 1]); + int p = min(k / 2, end1); + if (nums1[end1 - p] > nums2[end2 - p]) + return findKthBig(nums1, end1 - p, nums2, end2, k - p); + return findKthBig(nums1, end1, nums2, end2 - p, k - p); + } +}; +// binary search, remove half of the elements in vector each time +class SolutionCpp20 { + int findNth(span nums, int n) { return nums[n - 1]; } + int findNth(span nums1, span nums2, int n) { + if (nums1.size() == 0) + return findNth(nums2, n); + if (nums2.size() == 0) + return findNth(nums1, n); + if (n == 1) + return min(nums1[0], nums2[0]); + int xval = nums1[nums1.size() / 2], yval = nums2[nums2.size() / 2]; + if (xval <= yval) { + int xlcnt = nums1.size() / 2 + 1, ylcnt = nums2.size() / 2 + 1; + if (xlcnt + ylcnt <= n) { + return findNth(nums1.subspan(xlcnt), nums2, n - xlcnt); + } else { + return findNth(nums1, nums2.subspan(0, ylcnt - 1), n); + } + } else { + return findNth(nums2, nums1, n); + } + } + +public: + double findMedianSortedArrays(vector nums1, vector nums2) { + int c = nums1.size() + nums2.size(); + if (c == 0) + return 0; + if (!(c & 1)) { + return (findNth(nums1, nums2, c / 2 + 1) + + findNth(nums1, nums2, c / 2)) / + 2.0; + } else { + return findNth(nums1, nums2, c / 2 + 1); + } + } +}; +// binary search, remove n/2 elements in vector each time +class SolutionCpp20v2 { + int findNth(span nums, int n) { return nums[n - 1]; } + int findNth(span nums1, span nums2, int n) { + if (nums1.size() == 0) + return findNth(nums2, n); + if (nums2.size() == 0) + return findNth(nums1, n); + if (n == 1) + return min(nums1[0], nums2[0]); + if (nums1.size() > nums2.size()) + return findNth(nums2, nums1, n); + int half = min(n / 2, (int)nums1.size()); + int xval = nums1[half - 1], yval = nums2[half - 1]; + if (xval <= yval) { + return findNth(nums1.subspan(half), nums2, n - half); + } else { + return findNth(nums1, nums2.subspan(half), n - half); + } + } + +public: + double findMedianSortedArrays(vector nums1, vector nums2) { + int c = nums1.size() + nums2.size(); + if (c == 0) + return 0; + if (!(c & 1)) { + return (findNth(nums1, nums2, c / 2 + 1) + + findNth(nums1, nums2, c / 2)) / + 2.0; + } else { + return findNth(nums1, nums2, c / 2 + 1); + } + } +}; \ No newline at end of file diff --git a/cpp/40.CombinationSumII/sort_dfs.cpp b/cpp/40.CombinationSumII/sort_dfs.cpp deleted file mode 100644 index a8fdfc3..0000000 --- a/cpp/40.CombinationSumII/sort_dfs.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { - vector>res; -public: - vector> combinationSum2(vector& candidates, int target) { - sort(candidates.begin(),candidates.end()); - vectorcur; - dfs(candidates,cur,0,target); - return res; - } - void dfs(vector&nums,vector&cur,int i,int sum){ - if(0==sum){ - res.push_back(cur); - return; - } - for(int start=i;i=nums[i];++i){ - if(i>start&&nums[i]==nums[i-1])continue; - cur.push_back(nums[i]); - dfs(nums,cur,i+1,sum-nums[i]); - cur.pop_back(); - } - } -}; diff --git a/cpp/40.cpp b/cpp/40.cpp new file mode 100644 index 0000000..80804f5 --- /dev/null +++ b/cpp/40.cpp @@ -0,0 +1,24 @@ +class Solution { + vector> res; + void dfs(vector& nums, vector& cur, int i, int sum) { + if (0 == sum) { + res.push_back(cur); + return; + } + for (int start = i; i < nums.size() && sum >= nums[i]; ++i) { + if (i > start && nums[i] == nums[i - 1]) + continue; + cur.push_back(nums[i]); + dfs(nums, cur, i + 1, sum - nums[i]); + cur.pop_back(); + } + } + +public: + vector> combinationSum2(vector& candidates, int target) { + ranges::sort(candidates); + vector cur; + dfs(candidates, cur, 0, target); + return res; + } +}; diff --git a/cpp/400.NthDigit/simple.cpp b/cpp/400.NthDigit/simple.cpp deleted file mode 100644 index 099f0ef..0000000 --- a/cpp/400.NthDigit/simple.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - int findNthDigit(int n) { - int len = 1; - for (long long int base = 9; n - base>0; ++len) { - n -= base; - base = base * 10 * (len + 1) / len; - } - int target = pow(10, len - 1); - int off = (n-1)%len; - target = target + (n-1) / len; - for (int i = 0; i 0; ++len) { + n -= base; + base = base * 10 * (len + 1) / len; + } + int target = pow(10, len - 1); + int off = (n - 1) % len; + target = target + (n - 1) / len; + for (int i = 0; i < len - off - 1; ++i) + target /= 10; + return target % 10; + } +}; diff --git a/cpp/401.BinaryWatch/bitset.cpp b/cpp/401.BinaryWatch/bitset.cpp deleted file mode 100644 index fbd8696..0000000 --- a/cpp/401.BinaryWatch/bitset.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - vector readBinaryWatch(int num) { - vector rs; - for (int h = 0; h < 12; h++) - for (int m = 0; m < 60; m++) - if (bitset<10>(h << 6 | m).count() == num) - rs.push_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m)); - return rs; -} -}; diff --git a/cpp/401.cpp b/cpp/401.cpp new file mode 100644 index 0000000..c3884f9 --- /dev/null +++ b/cpp/401.cpp @@ -0,0 +1,12 @@ +// bitset.cpp +class Solution { +public: + vector readBinaryWatch(int num) { + vector rs; + for (int h = 0; h < 12; h++) + for (int m = 0; m < 60; m++) + if (bitset<10>(h << 6 | m).count() == num) + rs.push_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m)); + return rs; + } +}; diff --git a/cpp/402.RemoveKDigits.cpp b/cpp/402.RemoveKDigits.cpp deleted file mode 100644 index c122e2c..0000000 --- a/cpp/402.RemoveKDigits.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -//Runtime: 44 ms, faster than 12.45% of C++ online submissions for Remove K Digits. -//Memory Usage: 180 MB, less than 8.63% of C++ online submissions for Remove K Digits. -public: - string removeKdigits(string num, int k) { - if(k>=num.size()) - return "0"; - if(k==0){ - int i=0; - while(inum[i+1]) - return removeKdigits(num.substr(0,i)+num.substr(i+1),k-1); - return removeKdigits(num.substr(0,num.size()-k),0); - } -}; \ No newline at end of file diff --git a/cpp/402.cpp b/cpp/402.cpp new file mode 100644 index 0000000..0a1b522 --- /dev/null +++ b/cpp/402.cpp @@ -0,0 +1,20 @@ +class Solution { + // Runtime: 44 ms, faster than 12.45% of C++ online submissions for Remove K + // Digits. Memory Usage: 180 MB, less than 8.63% of C++ online submissions for + // Remove K Digits. +public: + string removeKdigits(string num, int k) { + if (k >= num.size()) + return "0"; + if (k == 0) { + int i = 0; + while (i < num.size() and num[i] == '0') + ++i; + return i == num.size() ? "0" : num.substr(i); + } + for (int i = 0; i + 1 < num.size(); ++i) + if (num[i] > num[i + 1]) + return removeKdigits(num.substr(0, i) + num.substr(i + 1), k - 1); + return removeKdigits(num.substr(0, num.size() - k), 0); + } +}; \ No newline at end of file diff --git a/cpp/403.FrogJump.cpp b/cpp/403.FrogJump.cpp deleted file mode 100644 index 27aba3e..0000000 --- a/cpp/403.FrogJump.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -//Runtime: 52 ms, faster than 80.66% of C++ online submissions for Frog Jump. -//Memory Usage: 145.6 MB, less than 5.04% of C++ online submissions for Frog Jump. -public: - bool canCross(vector& stones) { - vector> visited(stones.size(),vector(stones.size())); - function dfs=[&stones,&visited,&dfs](int now,int k){ - for (int i=now+1;i k + 1) - return false; - if (not visited[now][i] and dfs(i, gap)) - return true; - else - visited[now][i]=1; - } - return now==stones.size()-1; - }; - return dfs(0,0); - } -}; \ No newline at end of file diff --git a/cpp/403.cpp b/cpp/403.cpp new file mode 100644 index 0000000..be137db --- /dev/null +++ b/cpp/403.cpp @@ -0,0 +1,24 @@ +class Solution { + // Runtime: 52 ms, faster than 80.66% of C++ online submissions for Frog Jump. + // Memory Usage: 145.6 MB, less than 5.04% of C++ online submissions for Frog + // Jump. +public: + bool canCross(vector &stones) { + vector> visited(stones.size(), vector(stones.size())); + function dfs = [&stones, &visited, &dfs](int now, int k) { + for (int i = now + 1; i < stones.size(); ++i) { + int gap = stones[i] - stones[now]; + if (gap < k - 1) + continue; + if (gap > k + 1) + return false; + if (not visited[now][i] and dfs(i, gap)) + return true; + else + visited[now][i] = 1; + } + return now == stones.size() - 1; + }; + return dfs(0, 0); + } +}; \ No newline at end of file diff --git a/cpp/404.SumOfLeftLeaves/recursion.cpp b/cpp/404.SumOfLeftLeaves/recursion.cpp deleted file mode 100644 index edf47ee..0000000 --- a/cpp/404.SumOfLeftLeaves/recursion.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int sum=0; -public: - int sumOfLeftLeaves(TreeNode* root) { - getSum(root,0); - return sum; - } - void getSum(TreeNode* root,bool isLeft){ - if(root==NULL) - return; - if(isLeft && root->left==NULL && root->right ==NULL) - sum+=root->val; - getSum(root->left,1); - getSum(root->right,0); - } -}; diff --git a/cpp/404.cpp b/cpp/404.cpp new file mode 100644 index 0000000..ea303db --- /dev/null +++ b/cpp/404.cpp @@ -0,0 +1,27 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int sum = 0; + +public: + int sumOfLeftLeaves(TreeNode *root) { + getSum(root, 0); + return sum; + } + void getSum(TreeNode *root, bool isLeft) { + if (root == NULL) + return; + if (isLeft && root->left == NULL && root->right == NULL) + sum += root->val; + getSum(root->left, 1); + getSum(root->right, 0); + } +}; diff --git a/cpp/405.ConvertANumberToHexadecimal/hex.cpp b/cpp/405.ConvertANumberToHexadecimal/hex.cpp deleted file mode 100644 index 83ca041..0000000 --- a/cpp/405.ConvertANumberToHexadecimal/hex.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - string toHex(int num) { - if(num==0) - return "0"; - const char hex[17]={"0123456789abcdef"}; - unsigned int number=num; - string str=""; - while(number>0){ - str=hex[number&0xf]+str; - number>>=4; - } - return str; - } -}; diff --git a/cpp/405.cpp b/cpp/405.cpp new file mode 100644 index 0000000..24a0319 --- /dev/null +++ b/cpp/405.cpp @@ -0,0 +1,16 @@ +// hex.cpp +class Solution { +public: + string toHex(int num) { + if (num == 0) + return "0"; + const char hex[17] = {"0123456789abcdef"}; + unsigned int number = num; + string str = ""; + while (number > 0) { + str = hex[number & 0xf] + str; + number >>= 4; + } + return str; + } +}; diff --git a/cpp/406.QueueReconstructionByHeight.cpp b/cpp/406.QueueReconstructionByHeight.cpp deleted file mode 100644 index 75f80cb..0000000 --- a/cpp/406.QueueReconstructionByHeight.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution { -//Runtime: 76 ms, faster than 42.25% of C++ online submissions for Queue Reconstruction by Height. -//https://leetcode.com/problems/queue-reconstruction-by-height/discuss/89348/6-lines-Concise-C%2B%2B -public: - vector> reconstructQueue(vector>& people) { - sort(people.begin(), people.end(), [](const auto& p1, const auto& p2){ - return p1[0] > p2[0] || (p1[0] == p2[0] && p1[1] < p2[1]); - }); - vector> res; - for (auto& p : people) - res.insert(res.begin() + p[1], p); - return res; - } -}; -class Solution { // better than first one because of the use of list -//Runtime: 40 ms, faster than 94.96% of C++ online submissions for Queue Reconstruction by Height. -public: - vector> reconstructQueue(vector>& people) { - sort(people.begin(), people.end(), [](const auto& p1, const auto& p2){ - return p1[0] > p2[0] || (p1[0] == p2[0] && p1[1] < p2[1]); - }); - list> res; - for (auto& p : people) - res.insert(next(res.begin(),p[1]), p); - return {make_move_iterator(res.begin()),make_move_iterator(res.end())}; - } -}; \ No newline at end of file diff --git a/cpp/406.cpp b/cpp/406.cpp new file mode 100644 index 0000000..d44e0c3 --- /dev/null +++ b/cpp/406.cpp @@ -0,0 +1,29 @@ +class Solution { + // Runtime: 76 ms, faster than 42.25% of C++ online submissions for Queue + // Reconstruction by Height. + // https://leetcode.com/problems/queue-reconstruction-by-height/discuss/89348/6-lines-Concise-C%2B%2B +public: + vector> reconstructQueue(vector> &people) { + sort(people.begin(), people.end(), [](const auto &p1, const auto &p2) { + return p1[0] > p2[0] || (p1[0] == p2[0] && p1[1] < p2[1]); + }); + vector> res; + for (auto &p : people) + res.insert(res.begin() + p[1], p); + return res; + } +}; +class Solution2 { // better than first one because of the use of list + // Runtime: 40 ms, faster than 94.96% of C++ online submissions for Queue + // Reconstruction by Height. +public: + vector> reconstructQueue(vector> &people) { + sort(people.begin(), people.end(), [](const auto &p1, const auto &p2) { + return p1[0] > p2[0] || (p1[0] == p2[0] && p1[1] < p2[1]); + }); + list> res; + for (auto &p : people) + res.insert(next(res.begin(), p[1]), p); + return {make_move_iterator(res.begin()), make_move_iterator(res.end())}; + } +}; \ No newline at end of file diff --git a/cpp/409.LongestPalindrome/hash-6ms.cpp b/cpp/409.LongestPalindrome/hash-6ms.cpp deleted file mode 100644 index 97c690d..0000000 --- a/cpp/409.LongestPalindrome/hash-6ms.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { -public: - int longestPalindrome(string s) { - int a[58]={}; - int len=s.size(); - for(int i=0;i0){ - if(a[i]%2==0){ - result+=a[i]; - a[i]=0; - } - else{ - result+=a[i]-1; - a[i]=1; - flag=1; - } - } - if(flag==1) - return result+1; - return result; - } -}; diff --git a/cpp/409.cpp b/cpp/409.cpp new file mode 100644 index 0000000..7facff7 --- /dev/null +++ b/cpp/409.cpp @@ -0,0 +1,26 @@ +// hash-6ms.cpp +class Solution { +public: + int longestPalindrome(string s) { + int a[58] = {}; + int len = s.size(); + for (int i = 0; i < len; ++i) + ++a[s[i] - 'A']; + int result = 0; + bool flag = 0; + for (int i = 0; i < 58; ++i) + if (a[i] > 0) { + if (a[i] % 2 == 0) { + result += a[i]; + a[i] = 0; + } else { + result += a[i] - 1; + a[i] = 1; + flag = 1; + } + } + if (flag == 1) + return result + 1; + return result; + } +}; diff --git a/cpp/41.FirstMissingPositive/O1Space.cpp b/cpp/41.FirstMissingPositive/O1Space.cpp deleted file mode 100644 index ebef4e1..0000000 --- a/cpp/41.FirstMissingPositive/O1Space.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int firstMissingPositive(vector& nums) { - int n=nums.size(); - for(int i=0;i0&&nums[i]<=n&&nums[i]!=nums[nums[i]-1]) - swap(nums[i],nums[nums[i]-1]); - for(int i=0;i& nums) { - int n=nums.size(); - int *exist=new int[n](); - for(int i=0;i0&&nums[i]<=n) - exist[nums[i]-1]=1; - for(int i=0;i& nums) { + int n = nums.size(); + for (int i = 0; i < n; ++i) + while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) + swap(nums[i], nums[nums[i] - 1]); + for (int i = 0; i < n; ++i) + if (nums[i] != i + 1) + return i + 1; + return n + 1; + } +}; diff --git a/cpp/410.SplitArrayLargestSum.cpp b/cpp/410.SplitArrayLargestSum.cpp deleted file mode 100644 index 53a2501..0000000 --- a/cpp/410.SplitArrayLargestSum.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { -//Runtime: 4 ms -//Memory Usage: 8.6 MB -public: - int splitArray(vector& nums, int m) { - long long left = 0, right = 0; - for (auto num : nums) { - left = max(left, (long long)num); - right += num; - } - while (left < right) { - auto mid = left + (right - left) / 2; - if ([](const vector& nums, int cuts, long long max) { - long long acc = 0; - for (auto num : nums) { - if (acc + num <= max) - acc += num; - else { - --cuts; - acc = num; - if (cuts < 0) return false; - } - } - return true; - }(nums, m - 1, mid)) - right = mid; - else - left = mid + 1; - } - return left; - } -}; \ No newline at end of file diff --git a/cpp/410.cpp b/cpp/410.cpp new file mode 100644 index 0000000..899d3dd --- /dev/null +++ b/cpp/410.cpp @@ -0,0 +1,33 @@ +class Solution { + // Runtime: 4 ms + // Memory Usage: 8.6 MB +public: + int splitArray(vector &nums, int m) { + long long left = 0, right = 0; + for (auto num : nums) { + left = max(left, (long long)num); + right += num; + } + while (left < right) { + auto mid = left + (right - left) / 2; + if ([](const vector &nums, int cuts, long long max) { + long long acc = 0; + for (auto num : nums) { + if (acc + num <= max) + acc += num; + else { + --cuts; + acc = num; + if (cuts < 0) + return false; + } + } + return true; + }(nums, m - 1, mid)) + right = mid; + else + left = mid + 1; + } + return left; + } +}; \ No newline at end of file diff --git a/cpp/412.FizzBuzz/iteration.cpp b/cpp/412.FizzBuzz/iteration.cpp deleted file mode 100644 index c972f7f..0000000 --- a/cpp/412.FizzBuzz/iteration.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - vector fizzBuzz(int n) { - vector result; - for(int i=1;i<=n;++i){ - if(i%15==0) - result.push_back("FizzBuzz"); - else if(i%3==0) - result.push_back("Fizz"); - else if(i%5==0) - result.push_back("Buzz"); - else - result.push_back(to_string(i)); - - } - return result; - } -}; diff --git a/cpp/412.cpp b/cpp/412.cpp new file mode 100644 index 0000000..1603d90 --- /dev/null +++ b/cpp/412.cpp @@ -0,0 +1,18 @@ +// iteration.cpp +class Solution { +public: + vector fizzBuzz(int n) { + vector result; + for (int i = 1; i <= n; ++i) { + if (i % 15 == 0) + result.push_back("FizzBuzz"); + else if (i % 3 == 0) + result.push_back("Fizz"); + else if (i % 5 == 0) + result.push_back("Buzz"); + else + result.push_back(to_string(i)); + } + return result; + } +}; diff --git a/cpp/413.ArithmeticSlices/easyMath.cpp b/cpp/413.ArithmeticSlices/easyMath.cpp deleted file mode 100644 index 67ba9a2..0000000 --- a/cpp/413.ArithmeticSlices/easyMath.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - int numberOfArithmeticSlices(vector& A) { - int n=A.size()-1; - if(n<2) - return 0; - for(int i=0;i &A) { + int n = A.size() - 1; + if (n < 2) + return 0; + for (int i = 0; i < n; ++i) + A[i] = A[i + 1] - A[i]; + int count = 0, res = 0; + for (int i = 1; i < n; ++i) + if (A[i] == A[i - 1]) + ++count; + else { + res += (1 + count) * count / 2; + count = 0; + } + res += (1 + count) * count / 2; + return res; + } +}; diff --git a/cpp/414.ThirdMaximumNumber/On.cpp b/cpp/414.ThirdMaximumNumber/On.cpp deleted file mode 100644 index e281ced..0000000 --- a/cpp/414.ThirdMaximumNumber/On.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { -public: - int thirdMax(vector& nums) { - long long min=LLONG_MIN; - long long max1 = nums[0], max2 = min, max3 = min, len = nums.size(); - for (int i = 1; imax1) { - max3 = max2; - max2 = max1; - max1 = nums[i]; - } - else if (nums[i]>max2) { - max3 = max2; - max2 = nums[i]; - } - else if (nums[i]>max3) { - max3 = nums[i]; - } - } - if (min==max3) - return max1; - else - return max3; - } -}; diff --git a/cpp/414.cpp b/cpp/414.cpp new file mode 100644 index 0000000..ef32248 --- /dev/null +++ b/cpp/414.cpp @@ -0,0 +1,26 @@ +// On.cpp +class Solution { +public: + int thirdMax(vector &nums) { + long long min = LLONG_MIN; + long long max1 = nums[0], max2 = min, max3 = min, len = nums.size(); + for (int i = 1; i < len; i++) { + if (nums[i] == max1 || nums[i] == max2) + continue; + if (nums[i] > max1) { + max3 = max2; + max2 = max1; + max1 = nums[i]; + } else if (nums[i] > max2) { + max3 = max2; + max2 = nums[i]; + } else if (nums[i] > max3) { + max3 = nums[i]; + } + } + if (min == max3) + return max1; + else + return max3; + } +}; diff --git a/cpp/415.AddStrings/simple.cpp b/cpp/415.AddStrings/simple.cpp deleted file mode 100644 index a7b40d9..0000000 --- a/cpp/415.AddStrings/simple.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - string addStrings(string num1, string num2) { - int n1=num1.size()-1,n2=num2.size()-1,c=0; - string res=""; - while(n1>=0||n2>=0||c>0){ - if(n1>=0)c+=num1[n1--]-'0'; - if(n2>=0)c+=num2[n2--]-'0'; - res=char(c%10+'0')+res; - c/=10; - } - return res; - } -}; diff --git a/cpp/415.cpp b/cpp/415.cpp new file mode 100644 index 0000000..5092fa6 --- /dev/null +++ b/cpp/415.cpp @@ -0,0 +1,17 @@ +// simple.cpp +class Solution { +public: + string addStrings(string num1, string num2) { + int n1 = num1.size() - 1, n2 = num2.size() - 1, c = 0; + string res = ""; + while (n1 >= 0 || n2 >= 0 || c > 0) { + if (n1 >= 0) + c += num1[n1--] - '0'; + if (n2 >= 0) + c += num2[n2--] - '0'; + res = char(c % 10 + '0') + res; + c /= 10; + } + return res; + } +}; diff --git a/cpp/416.PartitionEqualSubsetSum/1-13ms.cpp b/cpp/416.PartitionEqualSubsetSum/1-13ms.cpp deleted file mode 100644 index a68a9c5..0000000 --- a/cpp/416.PartitionEqualSubsetSum/1-13ms.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - bool canPartition(vector& nums) { - bitset<10001>bits(1); - int sum=0,n=nums.size(); - for(auto i:nums){ - sum+=i; - bits|=bits<& nums) { - int sum=0,n=nums.size(); - for(auto i:nums) - sum+=i; - if( (sum&1)==1)return 0; - sum/=2; - vectordp(sum+1,0); - dp[0]=1; - for(int i=0;i=nums[i];--j) - dp[j]=dp[j]||dp[j-nums[i]]; - return dp[sum]; - } -}; \ No newline at end of file diff --git a/cpp/416.cpp b/cpp/416.cpp new file mode 100644 index 0000000..3214c8e --- /dev/null +++ b/cpp/416.cpp @@ -0,0 +1,33 @@ +// 1-13ms.cpp +class Solution { +public: + bool canPartition(vector &nums) { + bitset<10001> bits(1); + int sum = 0, n = nums.size(); + for (auto i : nums) { + sum += i; + bits |= bits << i; + } + if ((sum & 1) == 1) + return 0; + return bits[sum / 2]; + } +}; +// 2-29ms.cpp +class Solution2 { +public: + bool canPartition(vector &nums) { + int sum = 0, n = nums.size(); + for (auto i : nums) + sum += i; + if ((sum & 1) == 1) + return 0; + sum /= 2; + vector dp(sum + 1, 0); + dp[0] = 1; + for (int i = 0; i < n; ++i) + for (int j = sum; j >= nums[i]; --j) + dp[j] = dp[j] || dp[j - nums[i]]; + return dp[sum]; + } +}; \ No newline at end of file diff --git a/cpp/419.BattleshipsInABoard/onepass.cpp b/cpp/419.BattleshipsInABoard/onepass.cpp deleted file mode 100644 index 0784dea..0000000 --- a/cpp/419.BattleshipsInABoard/onepass.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int countBattleships(vector>& board) { - int count=0,row=board.size(); - if(row==0)return 0; - int col=board[0].size(); - for(int i=0;i> &board) { + int count = 0, row = board.size(); + if (row == 0) + return 0; + int col = board[0].size(); + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + count += board[i][j] == 'X' && (j == 0 || board[i][j - 1] != 'X') && + (i == 0 || board[i - 1][j] != 'X'); + return count; + } +}; diff --git a/cpp/42.TrappingRainWater/onepass.cpp b/cpp/42.TrappingRainWater/onepass.cpp deleted file mode 100644 index 2045f1a..0000000 --- a/cpp/42.TrappingRainWater/onepass.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - int trap(vector& height) { - int low=0,high=height.size()-1,sum=0; - while(low=height[low]) - sum+=v1-height[low++]; - else - while(low=height[high]) - sum+=v2-height[high--]; - } - return sum; - } -}; diff --git a/cpp/42.cpp b/cpp/42.cpp new file mode 100644 index 0000000..9f519cd --- /dev/null +++ b/cpp/42.cpp @@ -0,0 +1,21 @@ +// onepass.cpp +class Solution { +public: + int trap(vector& height) { + int low = 0, high = height.size() - 1, sum = 0; + while (low < high) { + while (low < high && height[low] < height[low + 1]) + low++; + while (low < high && height[high] < height[high - 1]) + high--; + int v1 = height[low], v2 = height[high]; + if (v1 < v2) + while (low < high && v1 >= height[low]) + sum += v1 - height[low++]; + else + while (low < high && v2 >= height[high]) + sum += v2 - height[high--]; + } + return sum; + } +}; diff --git a/cpp/421.MaximumXORofTwoNumbersInAnArray/O32n.cpp b/cpp/421.MaximumXORofTwoNumbersInAnArray/O32n.cpp deleted file mode 100644 index 43f0fcf..0000000 --- a/cpp/421.MaximumXORofTwoNumbersInAnArray/O32n.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int findMaximumXOR(vector& nums) { - int maxVal=0,mask=0; - for(int i=31;i>=0;i--){ - mask|=1<hashset; - for(auto num:nums) - hashset.insert(num&mask); - int target=maxVal|(1< &nums) { + int maxVal = 0, mask = 0; + for (int i = 31; i >= 0; i--) { + mask |= 1 << i; + unordered_set hashset; + for (auto num : nums) + hashset.insert(num & mask); + int target = maxVal | (1 << i); + for (auto num : hashset) + if (hashset.find(num ^ target) != hashset.end()) { + maxVal = target; + break; + } + } + return maxVal; + } +}; diff --git a/cpp/423.ReconstructOriginalDigitsFromEnglish/ugly.cpp b/cpp/423.ReconstructOriginalDigitsFromEnglish/ugly.cpp deleted file mode 100644 index 22bc102..0000000 --- a/cpp/423.ReconstructOriginalDigitsFromEnglish/ugly.cpp +++ /dev/null @@ -1,78 +0,0 @@ -class Solution { -public: - string originalDigits(string s) { - unordered_maphashmap; - for(auto ch:s) - hashmap[ch]++; - string res; - int count; - - count=hashmap['z']; - res.append(count,'0'); -// hashmap['z']-=count; - hashmap['e']-=count; - hashmap['r']-=count; - hashmap['o']-=count; - - count=hashmap['g']; - res.append(count,'8'); - hashmap['e']-=count; - hashmap['i']-=count; -// hashmap['g']-=count; - hashmap['h']-=count; - hashmap['t']-=count; - - count=hashmap['x']; - res.append(count,'6'); - hashmap['s']-=count; - hashmap['i']-=count; -// hashmap['x']-=count; - - count=hashmap['w']; - res.append(count,'2'); - hashmap['t']-=count; -// hashmap['w']-=count; - hashmap['o']-=count; - - count=hashmap['u']; - res.append(count,'4'); - hashmap['f']-=count; - hashmap['o']-=count; -// hashmap['u']-=count; - hashmap['r']-=count; - - count=hashmap['s']; - res.append(count,'7'); -// hashmap['s']-=count; - hashmap['e']-=count; - hashmap['v']-=count; - hashmap['e']-=count; - hashmap['n']-=count; - - count=hashmap['v']; - res.append(count,'5'); - hashmap['f']-=count; - hashmap['i']-=count; -// hashmap['v']-=count; - hashmap['e']-=count; - - count=hashmap['h']; - res.append(count,'3'); - hashmap['t']-=count; -// hashmap['h']-=count; - hashmap['r']-=count; - hashmap['e']-=count; - hashmap['e']-=count; - - count=hashmap['o']; - res.append(count,'1'); -// hashmap['o']-=count; - hashmap['n']-=count; - hashmap['e']-=count; - - count=hashmap['i']; - res.append(count,'9'); - sort(res.begin(),res.end()); - return res; - } -}; diff --git a/cpp/423.cpp b/cpp/423.cpp new file mode 100644 index 0000000..e0e203a --- /dev/null +++ b/cpp/423.cpp @@ -0,0 +1,79 @@ +// ugly.cpp +class Solution { +public: + string originalDigits(string s) { + unordered_map hashmap; + for (auto ch : s) + hashmap[ch]++; + string res; + int count; + + count = hashmap['z']; + res.append(count, '0'); + // hashmap['z']-=count; + hashmap['e'] -= count; + hashmap['r'] -= count; + hashmap['o'] -= count; + + count = hashmap['g']; + res.append(count, '8'); + hashmap['e'] -= count; + hashmap['i'] -= count; + // hashmap['g']-=count; + hashmap['h'] -= count; + hashmap['t'] -= count; + + count = hashmap['x']; + res.append(count, '6'); + hashmap['s'] -= count; + hashmap['i'] -= count; + // hashmap['x']-=count; + + count = hashmap['w']; + res.append(count, '2'); + hashmap['t'] -= count; + // hashmap['w']-=count; + hashmap['o'] -= count; + + count = hashmap['u']; + res.append(count, '4'); + hashmap['f'] -= count; + hashmap['o'] -= count; + // hashmap['u']-=count; + hashmap['r'] -= count; + + count = hashmap['s']; + res.append(count, '7'); + // hashmap['s']-=count; + hashmap['e'] -= count; + hashmap['v'] -= count; + hashmap['e'] -= count; + hashmap['n'] -= count; + + count = hashmap['v']; + res.append(count, '5'); + hashmap['f'] -= count; + hashmap['i'] -= count; + // hashmap['v']-=count; + hashmap['e'] -= count; + + count = hashmap['h']; + res.append(count, '3'); + hashmap['t'] -= count; + // hashmap['h']-=count; + hashmap['r'] -= count; + hashmap['e'] -= count; + hashmap['e'] -= count; + + count = hashmap['o']; + res.append(count, '1'); + // hashmap['o']-=count; + hashmap['n'] -= count; + hashmap['e'] -= count; + + count = hashmap['i']; + res.append(count, '9'); + sort(res.begin(), res.end()); + return res; + } +}; diff --git a/cpp/424.LongestRepeatingCharacterReplacement.cpp b/cpp/424.LongestRepeatingCharacterReplacement.cpp deleted file mode 100644 index 5a983bb..0000000 --- a/cpp/424.LongestRepeatingCharacterReplacement.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -//Runtime: 20 ms, faster than 41.40% of C++ online submissions for Longest Repeating Character Replacement. -public: - int characterReplacement(string s, int k) { - int i = 0, j = 0; - vectorm(26); - while (j < s.size()) { - m[s[j++]-'A']++; - if (j-i - *max_element(begin(m),end(m)) > k) - m[s[i++]-'A']--; - } - return j - i; - } -}; \ No newline at end of file diff --git a/cpp/424.cpp b/cpp/424.cpp new file mode 100644 index 0000000..3a25cf9 --- /dev/null +++ b/cpp/424.cpp @@ -0,0 +1,15 @@ +class Solution { + // Runtime: 20 ms, faster than 41.40% of C++ online submissions for Longest + // Repeating Character Replacement. +public: + int characterReplacement(string s, int k) { + int i = 0, j = 0; + vector m(26); + while (j < s.size()) { + m[s[j++] - 'A']++; + if (j - i - *max_element(begin(m), end(m)) > k) + m[s[i++] - 'A']--; + } + return j - i; + } +}; \ No newline at end of file diff --git a/cpp/429.N-aryTreeLevelOrderTraversal.cpp b/cpp/429.N-aryTreeLevelOrderTraversal.cpp deleted file mode 100644 index e9bbb53..0000000 --- a/cpp/429.N-aryTreeLevelOrderTraversal.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ -class Solution { // 136ms 99.81% -public: - vector> levelOrder(Node* root) - { - if (root == nullptr) - return {}; - vector> res; - queue q; - q.push(root); - while (!q.empty()) - { - int size = q.size(); - vector curLevel; - while(size--) - { - auto tmp = q.front(); - q.pop(); - curLevel.push_back(tmp -> val); - for (auto &n : tmp -> children) - q.push(n); - } - res.push_back(curLevel); - } - return res; - } -}; \ No newline at end of file diff --git a/cpp/429.cpp b/cpp/429.cpp new file mode 100644 index 0000000..f8974dd --- /dev/null +++ b/cpp/429.cpp @@ -0,0 +1,35 @@ +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +class Solution { // 136ms 99.81% +public: + vector> levelOrder(Node *root) { + if (root == nullptr) + return {}; + vector> res; + queue q; + q.push(root); + while (!q.empty()) { + int size = q.size(); + vector curLevel; + while (size--) { + auto tmp = q.front(); + q.pop(); + curLevel.push_back(tmp->val); + for (auto &n : tmp->children) + q.push(n); + } + res.push_back(curLevel); + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/43.MultiplyStrings/smartidea.cpp b/cpp/43.MultiplyStrings/smartidea.cpp deleted file mode 100644 index 597180b..0000000 --- a/cpp/43.MultiplyStrings/smartidea.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - string multiply(string num1, string num2) { - int m=num1.size(),n=num2.size(); - string res(m+n,0); - for(int i=m-1;i>=0;--i) - for(int j=n-1;j>=0;--j){ - int mul=(num1[i]-'0')*(num2[j]-'0'); - int p1=i+j,p2=i+j+1; - int sum=mul+res[p2]; - res[p2]=sum%10; - res[p1]+=sum/10; - } - int off; - for(off=0;off= 0; --i) + for (int j = n - 1; j >= 0; --j) { + int mul = (num1[i] - '0') * (num2[j] - '0'); + int p1 = i + j, p2 = i + j + 1; + int sum = mul + res[p2]; + res[p2] = sum % 10; + res[p1] += sum / 10; + } + int off; + for (off = 0; off < res.size() && res[off] == 0; ++off) + ; + res = res.substr(off); + for (int i = 0; i < res.size(); ++i) + res[i] += '0'; + return res.size() == 0 ? "0" : res; + } +}; diff --git a/cpp/434.NumberOfSegmentInAString/onepass-0ms.cpp b/cpp/434.NumberOfSegmentInAString/onepass-0ms.cpp deleted file mode 100644 index 41ffe26..0000000 --- a/cpp/434.NumberOfSegmentInAString/onepass-0ms.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int countSegments(string s) { - int n = s.size(); - int count = 0; - bool word=0; - for(int i=0;imap; - int count=0; -public: - int pathSum(TreeNode* root, int sum) { - map[0]=1; - preOrder(root,0,sum); - return count; - } - void preOrder(TreeNode* root,int cur, int sum){ - if(root==NULL) - return; - cur+=root->val; - count+=map[cur-sum]; - ++map[cur]; - preOrder(root->left,cur,sum); - preOrder(root->right,cur,sum); - --map[cur]; - } -}; diff --git a/cpp/437.cpp b/cpp/437.cpp new file mode 100644 index 0000000..8ae32cc --- /dev/null +++ b/cpp/437.cpp @@ -0,0 +1,31 @@ +// hash.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + unordered_map map; + int count = 0; + +public: + int pathSum(TreeNode *root, int sum) { + map[0] = 1; + preOrder(root, 0, sum); + return count; + } + void preOrder(TreeNode *root, int cur, int sum) { + if (root == NULL) + return; + cur += root->val; + count += map[cur - sum]; + ++map[cur]; + preOrder(root->left, cur, sum); + preOrder(root->right, cur, sum); + --map[cur]; + } +}; diff --git a/cpp/438.FindAllAnagramsInAString/myidea.cpp b/cpp/438.FindAllAnagramsInAString/myidea.cpp deleted file mode 100644 index 7fab1db..0000000 --- a/cpp/438.FindAllAnagramsInAString/myidea.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { -public: - vector findAnagrams(string s, string p) { - vectorres; - vectorletter(26,0); - int total=p.size(),start=0; - for(int i=0;i0){ - letter[s[i]-'a']--; - ++i; - if(--total==0){ - total=1; - letter[s[start]-'a']++; - res.push_back(start++); - } - } - else{ - if(i>start){ - letter[s[start]-'a']++; - start++; - total++; - } - else{ - ++i; - ++start; - } - } - return res; - } -}; diff --git a/cpp/438.cpp b/cpp/438.cpp new file mode 100644 index 0000000..125f1d6 --- /dev/null +++ b/cpp/438.cpp @@ -0,0 +1,31 @@ +// myidea.cpp +class Solution { +public: + vector findAnagrams(string s, string p) { + vector res; + vector letter(26, 0); + int total = p.size(), start = 0; + for (int i = 0; i < p.size(); ++i) + letter[p[i] - 'a']++; + for (int i = 0; i < s.size();) + if (letter[s[i] - 'a'] > 0) { + letter[s[i] - 'a']--; + ++i; + if (--total == 0) { + total = 1; + letter[s[start] - 'a']++; + res.push_back(start++); + } + } else { + if (i > start) { + letter[s[start] - 'a']++; + start++; + total++; + } else { + ++i; + ++start; + } + } + return res; + } +}; diff --git a/cpp/44.WildcardMatching.cpp b/cpp/44.WildcardMatching.cpp deleted file mode 100644 index 47c2ad9..0000000 --- a/cpp/44.WildcardMatching.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class Solution { -//Runtime: 42 ms.Your runtime beats 60.10 % of cpp submissions. -public: - bool isMatch(string s, string p) { - int i=0,j=0,star=-1,ii; - while(i> f(m + 1, vector(n + 1, 0)); - f[0][0] = 1; - for (int j = 1; j <= n; j++) - if('*' == p[j - 1]) - f[0][j] = 1; - else break; - int jstart=1; - for (int i = 1; i <= m; i++) - for (int j = jstart; j <= n; j++) - if (p[j - 1] != '*') - f[i][j] = f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || '?' == p[j - 1]); - else{ - if(f[i-1][j-1] or f[i-1][j] or f[i][j-1]){ - jstart=j+1; - for(int x=i;x<=m;++x) - f[x][j]=1; - } - } - return f[m][n]; - } -}; \ No newline at end of file diff --git a/cpp/44.cpp b/cpp/44.cpp new file mode 100644 index 0000000..ba65c4e --- /dev/null +++ b/cpp/44.cpp @@ -0,0 +1,51 @@ +class Solution { + // Runtime: 42 ms.Your runtime beats 60.10 % of cpp submissions. +public: + bool isMatch(string s, string p) { + int i = 0, j = 0, star = -1, ii; + while (i < s.size()) { + bool pNotOver = j < p.size(); + if (pNotOver && (p[j] == '?' || s[i] == p[j])) { + i++, j++; + } else if (pNotOver && p[j] == '*') { + star = ++j; + ii = i; + } else if (star != -1) { + j = star; + i = ++ii; + } else + return false; + } + return j == p.size() || p.find_first_not_of("*", j) == string::npos; + } +}; +class Solution2 { + // Runtime: 32 ms, faster than 69.51% of C++ online submissions for Wildcard + // Matching. Memory Usage: 30.2 MB, less than 9.17% of C++ online submissions + // for Wildcard Matching. +public: + bool isMatch(string s, string p) { + int m = s.size(), n = p.size(); + vector> f(m + 1, vector(n + 1, 0)); + f[0][0] = 1; + for (int j = 1; j <= n; j++) + if ('*' == p[j - 1]) + f[0][j] = 1; + else + break; + int jstart = 1; + for (int i = 1; i <= m; i++) + for (int j = jstart; j <= n; j++) + if (p[j - 1] != '*') + f[i][j] = + f[i - 1][j - 1] && (s[i - 1] == p[j - 1] || '?' == p[j - 1]); + else { + if (f[i - 1][j - 1] or f[i - 1][j] or f[i][j - 1]) { + jstart = j + 1; + for (int x = i; x <= m; ++x) + f[x][j] = 1; + } + } + return f[m][n]; + } +}; \ No newline at end of file diff --git a/cpp/441.ArrangingCoins/fast-25ms.cpp b/cpp/441.ArrangingCoins/fast-25ms.cpp deleted file mode 100644 index 2d0ef10..0000000 --- a/cpp/441.ArrangingCoins/fast-25ms.cpp +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { -public: - int arrangeCoins(int n) { - int i=1; - while(n>=0) - n-=i++; - return i-2; - } -}; diff --git a/cpp/441.cpp b/cpp/441.cpp new file mode 100644 index 0000000..4ebe699 --- /dev/null +++ b/cpp/441.cpp @@ -0,0 +1,10 @@ +// fast-25ms.cpp +class Solution { +public: + int arrangeCoins(int n) { + int i = 1; + while (n >= 0) + n -= i++; + return i - 2; + } +}; diff --git a/cpp/442.FindAllDuplicatesInAnArray/smart-146ms.cpp b/cpp/442.FindAllDuplicatesInAnArray/smart-146ms.cpp deleted file mode 100644 index b854579..0000000 --- a/cpp/442.FindAllDuplicatesInAnArray/smart-146ms.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - vector findDuplicates(vector& nums) { - int len=nums.size(); - vectorresult; - for(int i=0;i findDuplicates(vector &nums) { + int len = nums.size(); + vector result; + for (int i = 0; i < len; ++i) { + if (nums[abs(nums[i]) - 1] < 0) + result.push_back(abs(nums[i])); + else + nums[abs(nums[i]) - 1] = -nums[abs(nums[i]) - 1]; + } + return result; + } +}; diff --git a/cpp/443.StringCompression/cleanerCode.cpp b/cpp/443.StringCompression/cleanerCode.cpp deleted file mode 100644 index c1d45b8..0000000 --- a/cpp/443.StringCompression/cleanerCode.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int compress(vector& chars) { - int anchor = 0, write = 0; - for (int read = 0; read < chars.size(); read++) { - if (read + 1 == chars.size() || chars[read + 1] != chars[read]) { - chars[write++] = chars[anchor]; - if (read > anchor) { - string num=to_string(read-anchor+1); - memcpy(&chars[write],&num[0],num.size()); - write+=num.size(); - } - anchor = read + 1; - } - } - return write; - } -}; diff --git a/cpp/443.StringCompression/singleScan.cpp b/cpp/443.StringCompression/singleScan.cpp deleted file mode 100644 index 289fed9..0000000 --- a/cpp/443.StringCompression/singleScan.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { -public: - int compress(vector& chars) { - int res=0; - int count=1; - char last=chars[0]; - for(int i=1;i1){ - string num=to_string(count); - memcpy(&chars[res],&num[0],num.size()); - res+=num.size(); - } - last=chars[i]; - count=1; - } - } - chars[res++]=last; - if(count>1){ - string num=to_string(count); - memcpy(&chars[res],&num[0],num.size()); - res+=num.size(); - } - return res; - } -}; diff --git a/cpp/443.cpp b/cpp/443.cpp new file mode 100644 index 0000000..5c0c940 --- /dev/null +++ b/cpp/443.cpp @@ -0,0 +1,49 @@ +// cleanerCode.cpp +class Solution { +public: + int compress(vector &chars) { + int anchor = 0, write = 0; + for (int read = 0; read < chars.size(); read++) { + if (read + 1 == chars.size() || chars[read + 1] != chars[read]) { + chars[write++] = chars[anchor]; + if (read > anchor) { + string num = to_string(read - anchor + 1); + memcpy(&chars[write], &num[0], num.size()); + write += num.size(); + } + anchor = read + 1; + } + } + return write; + } +}; +// singleScan.cpp +class Solution2 { +public: + int compress(vector &chars) { + int res = 0; + int count = 1; + char last = chars[0]; + for (int i = 1; i < chars.size(); ++i) { + if (chars[i] == last) + ++count; + else { + chars[res++] = last; + if (count > 1) { + string num = to_string(count); + memcpy(&chars[res], &num[0], num.size()); + res += num.size(); + } + last = chars[i]; + count = 1; + } + } + chars[res++] = last; + if (count > 1) { + string num = to_string(count); + memcpy(&chars[res], &num[0], num.size()); + res += num.size(); + } + return res; + } +}; diff --git a/cpp/445.AddTwoNumbersII/vector.cpp b/cpp/445.AddTwoNumbersII/vector.cpp deleted file mode 100644 index 52962ce..0000000 --- a/cpp/445.AddTwoNumbersII/vector.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { - vectorarr1,arr2; - while(l1){ - arr1.emplace_back(l1->val); - l1=l1->next; - } - while(l2){ - arr2.emplace_back(l2->val); - l2=l2->next; - } - ListNode* p=new ListNode(0); - int i,j,c=0,val; - for(i=arr1.size()-1,j=arr2.size()-1;i>=0||j>=0||c>0;c=val/10){ - val=(i>=0?arr1[i--]:0) + (j>=0?arr2[j--]:0)+c; - ListNode*node=new ListNode( val%10 ); - node->next=p->next; - p->next=node; - } - return p->next; - } -}; diff --git a/cpp/445.cpp b/cpp/445.cpp new file mode 100644 index 0000000..2935cc5 --- /dev/null +++ b/cpp/445.cpp @@ -0,0 +1,33 @@ +// vector.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { + vector arr1, arr2; + while (l1) { + arr1.emplace_back(l1->val); + l1 = l1->next; + } + while (l2) { + arr2.emplace_back(l2->val); + l2 = l2->next; + } + ListNode *p = new ListNode(0); + int i, j, c = 0, val; + for (i = arr1.size() - 1, j = arr2.size() - 1; i >= 0 || j >= 0 || c > 0; + c = val / 10) { + val = (i >= 0 ? arr1[i--] : 0) + (j >= 0 ? arr2[j--] : 0) + c; + ListNode *node = new ListNode(val % 10); + node->next = p->next; + p->next = node; + } + return p->next; + } +}; diff --git a/cpp/447.NumberOfBoomerangs/TLE.cpp b/cpp/447.NumberOfBoomerangs/TLE.cpp deleted file mode 100644 index c91fe9f..0000000 --- a/cpp/447.NumberOfBoomerangs/TLE.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - int numberOfBoomerangs(vector>& points) { - int n=points.size(),count=0; - for(int i=0;i>& points){ - int x=points[i].first-points[j].first; - int y=points[i].second-points[j].second; - return x*x+y*y; - } -}; diff --git a/cpp/447.NumberOfBoomerangs/hashmap+beat97%.cpp b/cpp/447.NumberOfBoomerangs/hashmap+beat97%.cpp deleted file mode 100644 index 47f06a7..0000000 --- a/cpp/447.NumberOfBoomerangs/hashmap+beat97%.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -public: - int numberOfBoomerangs(vector>& points) { - int n=points.size(),count=0; - unordered_mapmap; - for(int i=0;isecond)*(it->second-1); - map.clear(); - } - return count; - } - int dist(pair&i,pair&j){ - int x=i.first-j.first; - int y=i.second-j.second; - return x*x+y*y; - } -}; diff --git a/cpp/447.cpp b/cpp/447.cpp new file mode 100644 index 0000000..f68fe79 --- /dev/null +++ b/cpp/447.cpp @@ -0,0 +1,47 @@ +// hashmap+beat97%.cpp +class Solution { +public: + int numberOfBoomerangs(vector> &points) { + int n = points.size(), count = 0; + unordered_map map; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (j == i) + continue; + map[dist(points[i], points[j])]++; + } + for (auto it = map.begin(); it != map.end(); ++it) + count += (it->second) * (it->second - 1); + map.clear(); + } + return count; + } + int dist(pair &i, pair &j) { + int x = i.first - j.first; + int y = i.second - j.second; + return x * x + y * y; + } +}; +// TLE.cpp +class Solution2 { +public: + int numberOfBoomerangs(vector> &points) { + int n = points.size(), count = 0; + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) + if (j == i) + continue; + else + for (int k = 0; k < n; ++k) + if (k == i || k == j) + continue; + else if (dist(i, j, points) == dist(i, k, points)) + count++; + return count; + } + int dist(int i, int j, vector> &points) { + int x = points[i].first - points[j].first; + int y = points[i].second - points[j].second; + return x * x + y * y; + } +}; diff --git a/cpp/448.FindAllNumbersDisappearedInAnArray/TimeOnSpaceO1.cpp b/cpp/448.FindAllNumbersDisappearedInAnArray/TimeOnSpaceO1.cpp deleted file mode 100644 index 541489d..0000000 --- a/cpp/448.FindAllNumbersDisappearedInAnArray/TimeOnSpaceO1.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - vector findDisappearedNumbers(vector& nums) { - int len=nums.size(); - int value; - for(int i=0;i0){ - nums[value-1]<0?nums[value-1]=nums[value-1]:nums[value-1]=-nums[value-1]; - } - } - vector disappear; - for(int i=0;i0) - disappear.push_back(i+1); - return disappear; - } -}; diff --git a/cpp/448.cpp b/cpp/448.cpp new file mode 100644 index 0000000..ec6319b --- /dev/null +++ b/cpp/448.cpp @@ -0,0 +1,19 @@ +// TimeOnSpaceO1.cpp +class Solution { +public: + vector findDisappearedNumbers(vector &nums) { + int len = nums.size(); + int value; + for (int i = 0; i < len; i++) { + if ((value = abs(nums[i])) > 0) { + nums[value - 1] < 0 ? nums[value - 1] = nums[value - 1] + : nums[value - 1] = -nums[value - 1]; + } + } + vector disappear; + for (int i = 0; i < nums.size(); i++) + if (nums[i] > 0) + disappear.push_back(i + 1); + return disappear; + } +}; diff --git a/cpp/449.SerializeAndDeserializeBst.cpp b/cpp/449.SerializeAndDeserializeBst.cpp deleted file mode 100644 index 06d37b8..0000000 --- a/cpp/449.SerializeAndDeserializeBst.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Codec { -//Runtime: 32 ms, faster than 80.35% of C++ online submissions for Serialize and Deserialize BST. -//Memory Usage: 25.8 MB, less than 39.25% of C++ online submissions for Serialize and Deserialize BST. -public: - - // Encodes a tree to a single string. - string serialize(TreeNode* root) { - if(not root) - return " #"; - return " "+to_string(root->val)+serialize(root->left)+serialize(root->right); - } - - // Decodes your encoded data to tree. - TreeNode* deserialize(string data) { - stringstream ss(data); - string now; - TreeNode fakeRoot(0); - auto p=&fakeRoot; - vector>st{{p,0}}; - while(ss>>now){ - auto &[p,status]=st.back(); - if(now=="#"){ - if(not status) - status=true; - else - st.pop_back(); - } - else{ - auto &node=status?p->right:p->left; - if(not status) - status=true; - else - st.pop_back(); - node=new TreeNode(stoi(now)); - st.push_back({node,false}); - } - } - return fakeRoot.left; - } -}; - -// Your Codec object will be instantiated and called as such: -// Codec codec; -// codec.deserialize(codec.serialize(root)); \ No newline at end of file diff --git a/cpp/449.cpp b/cpp/449.cpp new file mode 100644 index 0000000..5f7ce1d --- /dev/null +++ b/cpp/449.cpp @@ -0,0 +1,53 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { + // Runtime: 32 ms, faster than 80.35% of C++ online submissions for Serialize + // and Deserialize BST. Memory Usage: 25.8 MB, less than 39.25% of C++ online + // submissions for Serialize and Deserialize BST. +public: + // Encodes a tree to a single string. + string serialize(TreeNode *root) { + if (not root) + return " #"; + return " " + to_string(root->val) + serialize(root->left) + + serialize(root->right); + } + + // Decodes your encoded data to tree. + TreeNode *deserialize(string data) { + stringstream ss(data); + string now; + TreeNode fakeRoot(0); + auto p = &fakeRoot; + vector> st{{p, 0}}; + while (ss >> now) { + auto &[p, status] = st.back(); + if (now == "#") { + if (not status) + status = true; + else + st.pop_back(); + } else { + auto &node = status ? p->right : p->left; + if (not status) + status = true; + else + st.pop_back(); + node = new TreeNode(stoi(now)); + st.push_back({node, false}); + } + } + return fakeRoot.left; + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); \ No newline at end of file diff --git a/cpp/45.JumpGameII.cpp b/cpp/45.JumpGameII.cpp deleted file mode 100644 index 45eb24b..0000000 --- a/cpp/45.JumpGameII.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { //Runtime: 12 ms, faster than 93.59% of C++ online submissions for Jump Game II. -public: - int jump(vector& nums) { - queue>qe; - vectorvisited(nums.size(),0); - if(nums.size()==0) - return 0; - qe.push({0,0}); - visited[0] = true; - while(!qe.empty()){ - const auto [pos,depth]=qe.front(); - if(pos >= nums.size()-1) - return depth; - qe.pop(); - for(int i=nums[pos];i>=1;--i) - if(i+pos>=nums.size()-1) - return depth+1; - else if(visited[i+pos]==0){ - visited[i+pos] = 1; - qe.push({i+pos,depth+1}); - } - } - return 0; - } -}; \ No newline at end of file diff --git a/cpp/45.cpp b/cpp/45.cpp new file mode 100644 index 0000000..c049f8e --- /dev/null +++ b/cpp/45.cpp @@ -0,0 +1,57 @@ +class Solution { +public: + int jump(vector& nums) { + if (nums.size() <= 1) + return 0; + int l = 0, r = 1, step = 0, most = 0; + while (l < r) { + ++step; + while (l < r) { + most = max(l + nums[l], most); + ++l; + } + if (most >= nums.size() - 1) + return step; + r = most + 1; + } + return step; + } +}; +class SolutionBFS { +public: + int jump(vector& nums) { + queue> qe; + vector visited(nums.size(), 0); + if (nums.size() <= 1) + return 0; + qe.push({0, 0}); + visited[0] = true; + while (!qe.empty()) { + const auto [pos, depth] = qe.front(); + qe.pop(); + for (int i = nums[pos]; i >= 1; --i) + if (i + pos >= nums.size() - 1) + return depth + 1; + else if (visited[i + pos] == 0) { + visited[i + pos] = 1; + qe.push({i + pos, depth + 1}); + } + } + return 0; + } +}; +class SolutionIterative { +public: + int jump(vector& nums) { + vector res(nums.size(), INT_MAX / 2); + res[0] = 0; + for (int i = 0; i < nums.size(); ++i) { + for (int step = nums[i]; step > 0; --step) { + if (i + step < nums.size()) { + res[i + step] = min(res[i + step], res[i] + 1); + } + } + } + return res.back(); + } +}; \ No newline at end of file diff --git a/cpp/450.DeleteNodeInABst.cpp b/cpp/450.DeleteNodeInABst.cpp deleted file mode 100644 index ad15637..0000000 --- a/cpp/450.DeleteNodeInABst.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 32 ms, faster than 87.87% of C++ online submissions for Delete Node in a BST. -//Memory Usage: 12.8 MB, less than 69.11% of C++ online submissions for Delete Node in a BST. -public: - TreeNode* deleteNode(TreeNode* root, int key) { - if(not root) - return root; - if(root->val>key){ - root->left=deleteNode(root->left,key); - return root; - } - if(root->valright=deleteNode(root->right,key); - return root; - } - static auto leftTreeRightMost=[](auto root){ - auto node=root->left; - while(node&&node->right) - node=node->right; - return node; - }; - static auto rightTreeLeftMost=[](auto root){ - auto node=root->right; - while(node&&node->left) - node=node->left; - return node; - }; - if(auto l=leftTreeRightMost(root);l){ - root->val=l->val; - root->left=deleteNode(root->left,l->val); - return root; - } - if(auto r=rightTreeLeftMost(root);r){ - root->val=r->val; - root->right=deleteNode(root->right,r->val); - return root; - } - return nullptr; - } -}; \ No newline at end of file diff --git a/cpp/450.cpp b/cpp/450.cpp new file mode 100644 index 0000000..31080d3 --- /dev/null +++ b/cpp/450.cpp @@ -0,0 +1,50 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 32 ms, faster than 87.87% of C++ online submissions for Delete + // Node in a BST. Memory Usage: 12.8 MB, less than 69.11% of C++ online + // submissions for Delete Node in a BST. +public: + TreeNode *deleteNode(TreeNode *root, int key) { + if (not root) + return root; + if (root->val > key) { + root->left = deleteNode(root->left, key); + return root; + } + if (root->val < key) { + root->right = deleteNode(root->right, key); + return root; + } + static auto leftTreeRightMost = [](auto root) { + auto node = root->left; + while (node && node->right) + node = node->right; + return node; + }; + static auto rightTreeLeftMost = [](auto root) { + auto node = root->right; + while (node && node->left) + node = node->left; + return node; + }; + if (auto l = leftTreeRightMost(root); l) { + root->val = l->val; + root->left = deleteNode(root->left, l->val); + return root; + } + if (auto r = rightTreeLeftMost(root); r) { + root->val = r->val; + root->right = deleteNode(root->right, r->val); + return root; + } + return nullptr; + } +}; \ No newline at end of file diff --git a/cpp/451.SortCharactersByFrequency/sort-lamda-45ms.cpp b/cpp/451.SortCharactersByFrequency/sort-lamda-45ms.cpp deleted file mode 100644 index eb81172..0000000 --- a/cpp/451.SortCharactersByFrequency/sort-lamda-45ms.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - string frequencySort(string s) { - int counts[256]={}; - for(char ch:s) - ++counts[ch]; - sort(s.begin(),s.end(),[&](char a,char b){ - return counts[a]>counts[b]|| (counts[a]==counts[b]&&a counts[b] || (counts[a] == counts[b] && a < b); + }); + return s; + } +}; diff --git a/cpp/453.MinimumMovesToEqualArrayElements/sort.cpp b/cpp/453.MinimumMovesToEqualArrayElements/sort.cpp deleted file mode 100644 index f743236..0000000 --- a/cpp/453.MinimumMovesToEqualArrayElements/sort.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int minMoves(vector& nums) { - sort(nums.begin(),nums.end()); - int count=0; - for(int i=1;i &nums) { + sort(nums.begin(), nums.end()); + int count = 0; + for (int i = 1; i < nums.size(); i++) { + count += nums[i] - nums[0]; + } + return count; + } +}; diff --git a/cpp/454.4SumII/hash.cpp b/cpp/454.4SumII/hash.cpp deleted file mode 100644 index be2df39..0000000 --- a/cpp/454.4SumII/hash.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int fourSumCount(vector& A, vector& B, vector& C, vector& D) { - unordered_mapab; - int i,j,count=0; - for(i=0;i &A, vector &B, vector &C, + vector &D) { + unordered_map ab; + int i, j, count = 0; + for (i = 0; i < A.size(); ++i) + for (j = 0; j < B.size(); ++j) + ++ab[A[i] + B[j]]; + for (i = 0; i < C.size(); ++i) + for (j = 0; j < D.size(); ++j) + count += ab[-C[i] - D[j]]; + return count; + } +}; diff --git a/cpp/455.AssignCookies/greedy-45ms.cpp b/cpp/455.AssignCookies/greedy-45ms.cpp deleted file mode 100644 index 834f2c4..0000000 --- a/cpp/455.AssignCookies/greedy-45ms.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int findContentChildren(vector& g, vector& s) { - sort(g.begin(),g.end()); - sort(s.begin(),s.end()); - int count=0; - int i=0,j=0; - for(;i &g, vector &s) { + sort(g.begin(), g.end()); + sort(s.begin(), s.end()); + int count = 0; + int i = 0, j = 0; + for (; i < g.size() && j < s.size();) + if (g[i] <= s[j++]) { + ++count; + ++i; + } + return count; + } +}; diff --git a/cpp/456.132Pattern.cpp b/cpp/456.132Pattern.cpp deleted file mode 100644 index ccddf9c..0000000 --- a/cpp/456.132Pattern.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class Solution { -//Runtime: 520 ms, faster than 24.35% of C++ online submissions for 132 Pattern. -//Memory Usage: 9.9 MB, less than 89.07% of C++ online submissions for 132 Pattern. -public: - bool find132pattern(vector& nums) { - if(nums.size()<3) return false; - for(auto i=nums[0],j=1;j+1& nums) { - if(nums.size()<3) return false; - auto k=vector{next(begin(nums),2),end(nums)}; - sort(begin(k),end(k)); - for(auto i=nums[0],j=1;j+1& nums) { - int s3 = INT_MIN; - stack st; - for(auto it=rbegin(nums);it!=rend(nums);++it){ - if( *it < s3 ) return true; - else while( !st.empty() && *it > st.top() ){ - s3 = st.top(); - st.pop(); - } - st.push(*it); - } - return false; - } -}; \ No newline at end of file diff --git a/cpp/456.cpp b/cpp/456.cpp new file mode 100644 index 0000000..38faadc --- /dev/null +++ b/cpp/456.cpp @@ -0,0 +1,64 @@ +class Solution { + // Runtime: 520 ms, faster than 24.35% of C++ online submissions for 132 + // Pattern. Memory Usage: 9.9 MB, less than 89.07% of C++ online submissions + // for 132 Pattern. +public: + bool find132pattern(vector &nums) { + if (nums.size() < 3) + return false; + for (auto i = nums[0], j = 1; j + 1 < nums.size(); j++) { + if (i < nums[j]) { + if (find_if(begin(nums) + j + 1, end(nums), + [l = i, m = nums[j]](auto &a) { + return l < a and a < m; + }) != end(nums)) + return true; + } else + i = nums[j]; + } + return false; + } +}; +class Solution2 { + // Runtime: 292 ms, faster than 34.78% of C++ online submissions for 132 + // Pattern. Memory Usage: 10.6 MB, less than 33.33% of C++ online submissions + // for 132 Pattern. +public: + bool find132pattern(vector &nums) { + if (nums.size() < 3) + return false; + auto k = vector{next(begin(nums), 2), end(nums)}; + sort(begin(k), end(k)); + for (auto i = nums[0], j = 1; j + 1 < nums.size(); j++) { + if (i < nums[j]) { + auto it = upper_bound(begin(k), end(k), i); + if (it != end(k) and *it < nums[j]) + return true; + } else + i = nums[j]; + k.erase(lower_bound(begin(k), end(k), nums[j + 1])); + } + return false; + } +}; +class Solution3 { + // Runtime: 24 ms, faster than 88.49% of C++ online submissions for 132 + // Pattern. Memory Usage: 10.3 MB, less than 60.77% of C++ online submissions + // for 132 Pattern. +public: + bool find132pattern(vector &nums) { + int s3 = INT_MIN; + stack st; + for (auto it = rbegin(nums); it != rend(nums); ++it) { + if (*it < s3) + return true; + else + while (!st.empty() && *it > st.top()) { + s3 = st.top(); + st.pop(); + } + st.push(*it); + } + return false; + } +}; \ No newline at end of file diff --git a/cpp/457.CircularArrayLoop.cpp b/cpp/457.CircularArrayLoop.cpp deleted file mode 100644 index e25a679..0000000 --- a/cpp/457.CircularArrayLoop.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 88.75% of C++ online submissions for Circular Array Loop. -//Memory Usage: 8.4 MB, less than 75.74% of C++ online submissions for Circular Array Loop. -public: - bool circularArrayLoop(vector& nums) { - vectorvisited(nums.size(),0); - auto go=[&](int i)->int{ - if(nums[i]>0) - return (i+nums[i])%nums.size(); - else if(i+nums[i]<0){ - int offset=abs(i+nums[i])%nums.size(); - return offset==0?i:(int)nums.size()-offset; - } - else return i+nums[i]; - }; - for(int i=0;icurCircle(nums.size(),0); - curCircle[i]=1; - for(int start=go(i),dir=nums[i]>0;(nums[start]>0)==dir;){ - if(curCircle[start]) - if(start!=go(start)) - return true; - else break; - curCircle[start]=visited[start]=1; - start=go(start); - } - } - } - return false; - } -}; \ No newline at end of file diff --git a/cpp/457.cpp b/cpp/457.cpp new file mode 100644 index 0000000..64331a1 --- /dev/null +++ b/cpp/457.cpp @@ -0,0 +1,34 @@ +class Solution { + // Runtime: 4 ms, faster than 88.75% of C++ online submissions for Circular + // Array Loop. Memory Usage: 8.4 MB, less than 75.74% of C++ online + // submissions for Circular Array Loop. +public: + bool circularArrayLoop(vector &nums) { + vector visited(nums.size(), 0); + auto go = [&](int i) -> int { + if (nums[i] > 0) + return (i + nums[i]) % nums.size(); + else if (i + nums[i] < 0) { + int offset = abs(i + nums[i]) % nums.size(); + return offset == 0 ? i : (int)nums.size() - offset; + } else + return i + nums[i]; + }; + for (int i = 0; i < nums.size(); ++i) { + if (not visited[i]) { + vector curCircle(nums.size(), 0); + curCircle[i] = 1; + for (int start = go(i), dir = nums[i] > 0; (nums[start] > 0) == dir;) { + if (curCircle[start]) + if (start != go(start)) + return true; + else + break; + curCircle[start] = visited[start] = 1; + start = go(start); + } + } + } + return false; + } +}; \ No newline at end of file diff --git a/cpp/459.RepeatedSubstringPattern/better29ms.cpp b/cpp/459.RepeatedSubstringPattern/better29ms.cpp deleted file mode 100644 index 8a267ca..0000000 --- a/cpp/459.RepeatedSubstringPattern/better29ms.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { -public: - bool repeatedSubstringPattern(string s) { - int n = s.size(); - if(n<=1)return false; - vectorfactors(1,1); - for (int i=2;i*i<=n;++i) - if (n%i==0) { - factors.push_back(i); - factors.push_back(n/i); - } - for (auto it:factors) - if(isRepeated(s,it)) - return 1; - return 0; - } - bool isRepeated(string&s,int len){ - for(int i=len;i0;--i) - if(n%i==0&&isRepeated(s,i)) - return 1; - return 0; - } - bool isRepeated(string&s,int len){ - for(int i=len;i factors(1, 1); + for (int i = 2; i * i <= n; ++i) + if (n % i == 0) { + factors.push_back(i); + factors.push_back(n / i); + } + for (auto it : factors) + if (isRepeated(s, it)) + return 1; + return 0; + } + bool isRepeated(string &s, int len) { + for (int i = len; i < s.size();) + for (int j = 0; j < len; ++j, ++i) + if (s[j] != s[i]) + return 0; + return 1; + } +}; +// simple35ms.cpp +class Solution2 { +public: + bool repeatedSubstringPattern(string s) { + int n = s.size(); + for (int i = n / 2; i > 0; --i) + if (n % i == 0 && isRepeated(s, i)) + return 1; + return 0; + } + bool isRepeated(string &s, int len) { + for (int i = len; i < s.size();) + for (int j = 0; j < len; ++j, ++i) + if (s[j] != s[i]) + return 0; + return 1; + } +}; diff --git a/cpp/46.Permutations/dfs.cpp b/cpp/46.Permutations/dfs.cpp deleted file mode 100644 index 4889b34..0000000 --- a/cpp/46.Permutations/dfs.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { - vector>res; -public: - vector> permute(vector& nums) { - sort(nums.begin(),nums.end()); - vectorused(nums.size(),0); - vectorcur; - dfs(nums,used,cur); - return res; - } - void dfs(vector&nums,vector&used,vector&cur){ - if(cur.size()==nums.size()){ - res.push_back(cur); - return; - } - for(int i=0;i> res; + +public: + vector> permute(vector &nums) { + sort(nums.begin(), nums.end()); + vector used(nums.size(), 0); + vector cur; + dfs(nums, used, cur); + return res; + } + void dfs(vector &nums, vector &used, vector &cur) { + if (cur.size() == nums.size()) { + res.push_back(cur); + return; + } + for (int i = 0; i < nums.size(); ++i) { + if (used[i] == 0) { + used[i] = 1; + cur.push_back(nums[i]); + dfs(nums, used, cur); + cur.pop_back(); + used[i] = 0; + } + } + } +}; +// construct permutation from the first i elements +class Solution2 { +public: + vector> permute(vector& nums) { + vector> res = {{nums[0]}}; + for (int i = 1; i < nums.size(); ++i) { + vector> new_res; + for (auto& v : res) { + for (int j = 0; j <= v.size(); ++j) { + vector new_v = v; + new_v.insert(new_v.begin() + j, nums[i]); + new_res.push_back(new_v); + } + } + res = move(new_res); + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/460.LfuCache.cpp b/cpp/460.LfuCache.cpp deleted file mode 100644 index d3e1b13..0000000 --- a/cpp/460.LfuCache.cpp +++ /dev/null @@ -1,70 +0,0 @@ -class LFUCache { -//Runtime: 108 ms, faster than 97.00% of C++ online submissions for LFU Cache. -//Memory Usage: 40.3 MB, less than 75.85% of C++ online submissions for LFU Cache. - int cap; - int minFreq; - using L = list>;//k,v,count - unordered_mapcount2kv; - unordered_maphashmap; -public: - LFUCache(int capacity):cap(capacity),minFreq(0) { - - } - - int get(int key) { - auto it=hashmap.find(key); - if(it==end(hashmap)) return -1; - auto [k,v,c]=*it->second; - { - auto &target=count2kv[c]; - target.erase(it->second); - if(target.size()==0 and minFreq==c) - ++minFreq; - } - { - auto &target=count2kv[c+1]; - target.emplace_front(k,v,c+1); - it->second=target.begin(); - } - return v; - } - - void put(int key, int value) { - if(cap==0) - return; - auto it=hashmap.find(key); - if(it==end(hashmap)){ - if(hashmap.size()>=cap){ - auto &target=count2kv[minFreq]; - auto [k,v,c]=target.back(); - hashmap.erase(k); - target.pop_back(); - } - auto &target=count2kv[1]; - target.emplace_front(key,value,1); - hashmap[key]=target.begin(); - minFreq=1; - } - else{ - auto [k,v,c]=*it->second; - { - auto &target=count2kv[c]; - target.erase(it->second); - if(target.size()==0 and minFreq==c) - ++minFreq; - } - { - auto &target=count2kv[c+1]; - target.emplace_front(key,value,c+1); - it->second=target.begin(); - } - } - } -}; - -/** - * Your LFUCache object will be instantiated and called as such: - * LFUCache* obj = new LFUCache(capacity); - * int param_1 = obj->get(key); - * obj->put(key,value); - */ \ No newline at end of file diff --git a/cpp/460.cpp b/cpp/460.cpp new file mode 100644 index 0000000..ba05761 --- /dev/null +++ b/cpp/460.cpp @@ -0,0 +1,70 @@ +class LFUCache { + // Runtime: 108 ms, faster than 97.00% of C++ online submissions for LFU + // Cache. Memory Usage: 40.3 MB, less than 75.85% of C++ online submissions + // for LFU Cache. + int cap; + int minFreq; + using L = list>; // k,v,count + unordered_map count2kv; + unordered_map hashmap; + +public: + LFUCache(int capacity) : cap(capacity), minFreq(0) {} + + int get(int key) { + auto it = hashmap.find(key); + if (it == end(hashmap)) + return -1; + auto [k, v, c] = *it->second; + { + auto &target = count2kv[c]; + target.erase(it->second); + if (target.size() == 0 and minFreq == c) + ++minFreq; + } + { + auto &target = count2kv[c + 1]; + target.emplace_front(k, v, c + 1); + it->second = target.begin(); + } + return v; + } + + void put(int key, int value) { + if (cap == 0) + return; + auto it = hashmap.find(key); + if (it == end(hashmap)) { + if (hashmap.size() >= cap) { + auto &target = count2kv[minFreq]; + auto [k, v, c] = target.back(); + hashmap.erase(k); + target.pop_back(); + } + auto &target = count2kv[1]; + target.emplace_front(key, value, 1); + hashmap[key] = target.begin(); + minFreq = 1; + } else { + auto [k, v, c] = *it->second; + { + auto &target = count2kv[c]; + target.erase(it->second); + if (target.size() == 0 and minFreq == c) + ++minFreq; + } + { + auto &target = count2kv[c + 1]; + target.emplace_front(key, value, c + 1); + it->second = target.begin(); + } + } + } +}; + +/** + * Your LFUCache object will be instantiated and called as such: + * LFUCache* obj = new LFUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); + */ \ No newline at end of file diff --git a/cpp/461.HammingDistance/iteration.cpp b/cpp/461.HammingDistance/iteration.cpp deleted file mode 100644 index 8658833..0000000 --- a/cpp/461.HammingDistance/iteration.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - int hammingDistance(int x, int y) { - int result=x^y,sum=0; - for(int i=0;i<32;i++,result>>=1) - if(result%2==1) - sum++; - return sum; - } -}; diff --git a/cpp/461.cpp b/cpp/461.cpp new file mode 100644 index 0000000..0273fb4 --- /dev/null +++ b/cpp/461.cpp @@ -0,0 +1,11 @@ +// iteration.cpp +class Solution { +public: + int hammingDistance(int x, int y) { + int result = x ^ y, sum = 0; + for (int i = 0; i < 32; i++, result >>= 1) + if (result % 2 == 1) + sum++; + return sum; + } +}; diff --git a/cpp/462.MinimunMovesToEqualArrayElementsII/sort-26ms.cpp b/cpp/462.MinimunMovesToEqualArrayElementsII/sort-26ms.cpp deleted file mode 100644 index 0be84a5..0000000 --- a/cpp/462.MinimunMovesToEqualArrayElementsII/sort-26ms.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int minMoves2(vector& nums) { - int n=nums.size(),middle,sum=0; - if(n<=1)return 0; - sort(nums.begin(),nums.end()); - middle=nums[n/2]; - for(int i=0;i &nums) { + int n = nums.size(), middle, sum = 0; + if (n <= 1) + return 0; + sort(nums.begin(), nums.end()); + middle = nums[n / 2]; + for (int i = 0; i < n; ++i) + sum += abs(nums[i] - middle); + return sum; + } +}; diff --git a/cpp/463.IslandPerimeter/1.cpp b/cpp/463.IslandPerimeter/1.cpp deleted file mode 100644 index 977a413..0000000 --- a/cpp/463.IslandPerimeter/1.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { -public: - int islandPerimeter(vector>& grid) { - int row=grid.size(); - if(row==0)return 0; - int col=grid[0].size(); - int sum=0; - for(int i=0;i>& grid){ - if(grid[i][j]==0)return 0; - int len=4; - if(i-1>=0) - if(grid[i-1][j]==1) - len-=2; - if(j-1>=0) - if(grid[i][j-1]==1) - len-=2; - return len; - } -}; diff --git a/cpp/463.cpp b/cpp/463.cpp new file mode 100644 index 0000000..a04ffba --- /dev/null +++ b/cpp/463.cpp @@ -0,0 +1,27 @@ +// 1.cpp +class Solution { +public: + int islandPerimeter(vector> &grid) { + int row = grid.size(); + if (row == 0) + return 0; + int col = grid[0].size(); + int sum = 0; + for (int i = 0; i < row; i++) + for (int j = 0; j < col; j++) + sum += check(i, j, grid); + return sum; + } + int check(int i, int j, vector> &grid) { + if (grid[i][j] == 0) + return 0; + int len = 4; + if (i - 1 >= 0) + if (grid[i - 1][j] == 1) + len -= 2; + if (j - 1 >= 0) + if (grid[i][j - 1] == 1) + len -= 2; + return len; + } +}; diff --git a/cpp/464.CanIWin.cpp b/cpp/464.CanIWin.cpp deleted file mode 100644 index fe3b22a..0000000 --- a/cpp/464.CanIWin.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -//Runtime: 120 ms, faster than 51.55% of C++ online submissions for Can I Win. -//Memory Usage: 25 MB, less than 49.12% of C++ online submissions for Can I Win. -public: - bool canIWin(int maxChoosableInteger, int desiredTotal) { - unordered_map m; - if(maxChoosableInteger >= desiredTotal) return true; - if((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) return false; - function canWin=[&](int target, int visited) { - if(auto it=m.find(visited);it != m.end()) return it->second; - for(int i = 1; i <= maxChoosableInteger; i++) { - int mask = (1 << i); - if((mask & visited) == 0 && (i >= target or not canWin(target - i, mask | visited) )) - return m[visited] = true; - } - return m[visited] = false; - }; - return canWin(desiredTotal, 0); - } - -}; \ No newline at end of file diff --git a/cpp/464.cpp b/cpp/464.cpp new file mode 100644 index 0000000..aef30c0 --- /dev/null +++ b/cpp/464.cpp @@ -0,0 +1,25 @@ +class Solution { + // Runtime: 120 ms, faster than 51.55% of C++ online submissions for Can I + // Win. Memory Usage: 25 MB, less than 49.12% of C++ online submissions for + // Can I Win. +public: + bool canIWin(int maxChoosableInteger, int desiredTotal) { + unordered_map m; + if (maxChoosableInteger >= desiredTotal) + return true; + if ((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) + return false; + function canWin = [&](int target, int visited) { + if (auto it = m.find(visited); it != m.end()) + return it->second; + for (int i = 1; i <= maxChoosableInteger; i++) { + int mask = (1 << i); + if ((mask & visited) == 0 && + (i >= target or not canWin(target - i, mask | visited))) + return m[visited] = true; + } + return m[visited] = false; + }; + return canWin(desiredTotal, 0); + } +}; \ No newline at end of file diff --git a/cpp/47.PermutationsII/dfs.cpp b/cpp/47.PermutationsII/dfs.cpp deleted file mode 100644 index 0146f39..0000000 --- a/cpp/47.PermutationsII/dfs.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution { - int target; - void dfs(vector>&unused,vector>&res,vector&now){ - if(now.size()==target){ - res.push_back(now); - return; - } - for(auto &p:unused){ - if(p.second>0){ - now.push_back(p.first); - --p.second; - dfs(unused,res,now); - ++p.second; - now.pop_back(); - } - } - } -public: - vector> permuteUnique(vector& nums) { - target=nums.size(); - unordered_maphashmap; - for(auto num:nums) - ++hashmap[num]; - vector>arr(hashmap.begin(),hashmap.end()); - sort(arr.begin(),arr.end(),[](const pair&a,const pair&b){return a.first>res; - vectornow; - dfs(arr,res,now); - return res; - } -}; diff --git a/cpp/47.cpp b/cpp/47.cpp new file mode 100644 index 0000000..f5f2dad --- /dev/null +++ b/cpp/47.cpp @@ -0,0 +1,37 @@ +// dfs.cpp +class Solution { + int target; + void dfs(vector> &unused, vector> &res, + vector &now) { + if (now.size() == target) { + res.push_back(now); + return; + } + for (auto &p : unused) { + if (p.second > 0) { + now.push_back(p.first); + --p.second; + dfs(unused, res, now); + ++p.second; + now.pop_back(); + } + } + } + +public: + vector> permuteUnique(vector &nums) { + target = nums.size(); + unordered_map hashmap; + for (auto num : nums) + ++hashmap[num]; + vector> arr(hashmap.begin(), hashmap.end()); + sort(arr.begin(), arr.end(), + [](const pair &a, const pair &b) { + return a.first < b.first; + }); + vector> res; + vector now; + dfs(arr, res, now); + return res; + } +}; diff --git a/cpp/473.MatchsticksToSquare/dfs.cpp b/cpp/473.MatchsticksToSquare/dfs.cpp deleted file mode 100644 index bf3ef12..0000000 --- a/cpp/473.MatchsticksToSquare/dfs.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution { - bool can=0; - int average; - int a=0,b=0,c=0,d=0; -public: - bool makesquare(vector& nums) { - int sum=accumulate(nums.begin(),nums.end(),0); - if(sum%4||nums.size()==0)return 0; - sort(nums.begin(),nums.end(),greater()); - average=sum/4; - if(nums[0]>average)return 0; - dfs(nums,0); - return can; - } - void dfs(vector&nums,int i){ - if(d==average&a==b&&b==c&&c==d){ - can=1; - return; - } - if(i==nums.size()||a>average||b>average||c>average||d>average||can) - return; - a+=nums[i]; - dfs(nums,i+1); - a-=nums[i]; - b+=nums[i]; - dfs(nums,i+1); - b-=nums[i]; - c+=nums[i]; - dfs(nums,i+1); - c-=nums[i]; - d+=nums[i]; - dfs(nums,i+1); - d-=nums[i]; - } -}; diff --git a/cpp/473.cpp b/cpp/473.cpp new file mode 100644 index 0000000..e357edc --- /dev/null +++ b/cpp/473.cpp @@ -0,0 +1,40 @@ +// dfs.cpp +class Solution { + bool can = 0; + int average; + int a = 0, b = 0, c = 0, d = 0; + +public: + bool makesquare(vector &nums) { + int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % 4 || nums.size() == 0) + return 0; + sort(nums.begin(), nums.end(), greater()); + average = sum / 4; + if (nums[0] > average) + return 0; + dfs(nums, 0); + return can; + } + void dfs(vector &nums, int i) { + if (d == average & a == b && b == c && c == d) { + can = 1; + return; + } + if (i == nums.size() || a > average || b > average || c > average || + d > average || can) + return; + a += nums[i]; + dfs(nums, i + 1); + a -= nums[i]; + b += nums[i]; + dfs(nums, i + 1); + b -= nums[i]; + c += nums[i]; + dfs(nums, i + 1); + c -= nums[i]; + d += nums[i]; + dfs(nums, i + 1); + d -= nums[i]; + } +}; diff --git a/cpp/475.Heaters.cpp b/cpp/475.Heaters.cpp deleted file mode 100644 index c9a1bfd..0000000 --- a/cpp/475.Heaters.cpp +++ /dev/null @@ -1,46 +0,0 @@ -class Solution { -//Runtime: 80 ms, faster than 76.32% of C++ online submissions for Heaters. -//Memory Usage: 11.6 MB, less than 17.92% of C++ online submissions for Heaters. -public: - int findRadius(vector& houses, vector& heaters) { - sort(begin(houses), end(houses)); - sort(begin(heaters), end(heaters)); - vector res(houses.size(), INT_MAX); - // For each house, calculate distance to nearest RHS heater - for (int i = 0, h = 0; i < houses.size() && h < heaters.size(); ) - if (houses[i] <= heaters[h]) - res[i++] = heaters[h] - houses[i]; - else - h++; - // For each house, calculate distance to nearest LHS heater - for (int i = houses.size()-1, h = heaters.size()-1; i >= 0 && h >= 0; ) - if (houses[i] >= heaters[h]) - res[i--] = min(res[i], houses[i] - heaters[h]); - else - h--; - return *max_element(begin(res), end(res)); - } -}; -class Solution { -//Runtime: 80 ms, faster than 76.32% of C++ online submissions for Heaters. -//Memory Usage: 11.7 MB, less than 9.44% of C++ online submissions for Heaters. -public: - int findRadius(vector& houses, vector& heaters) { - sort(begin(houses), end(houses)); - sort(begin(heaters), end(heaters)); - vector res(houses.size(), INT_MAX); - // For each house, calculate distance to nearest RHS heater - for (auto i = begin(houses), h = begin(heaters), r = begin(res); i != end(houses) and h != end(heaters); ) - if (*i <= *h) - *r++ = *h - *i++; - else - ++h; - // For each house, calculate distance to nearest LHS heater - for (auto i = rbegin(houses), h = rbegin(heaters), r = rbegin(res); i != rend(houses) and h != rend(heaters); ) - if (*i >= *h) - *r++ = min(*r, *i++ - *h); - else - ++h; - return *max_element(begin(res), end(res)); - } -}; \ No newline at end of file diff --git a/cpp/475.cpp b/cpp/475.cpp new file mode 100644 index 0000000..656072b --- /dev/null +++ b/cpp/475.cpp @@ -0,0 +1,50 @@ +class Solution { + // Runtime: 80 ms, faster than 76.32% of C++ online submissions for Heaters. + // Memory Usage: 11.6 MB, less than 17.92% of C++ online submissions for + // Heaters. +public: + int findRadius(vector &houses, vector &heaters) { + sort(begin(houses), end(houses)); + sort(begin(heaters), end(heaters)); + vector res(houses.size(), INT_MAX); + // For each house, calculate distance to nearest RHS heater + for (int i = 0, h = 0; i < houses.size() && h < heaters.size();) + if (houses[i] <= heaters[h]) + res[i++] = heaters[h] - houses[i]; + else + h++; + // For each house, calculate distance to nearest LHS heater + for (int i = houses.size() - 1, h = heaters.size() - 1; i >= 0 && h >= 0;) + if (houses[i] >= heaters[h]) + res[i--] = min(res[i], houses[i] - heaters[h]); + else + h--; + return *max_element(begin(res), end(res)); + } +}; +class Solution2 { + // Runtime: 80 ms, faster than 76.32% of C++ online submissions for Heaters. + // Memory Usage: 11.7 MB, less than 9.44% of C++ online submissions for + // Heaters. +public: + int findRadius(vector &houses, vector &heaters) { + sort(begin(houses), end(houses)); + sort(begin(heaters), end(heaters)); + vector res(houses.size(), INT_MAX); + // For each house, calculate distance to nearest RHS heater + for (auto i = begin(houses), h = begin(heaters), r = begin(res); + i != end(houses) and h != end(heaters);) + if (*i <= *h) + *r++ = *h - *i++; + else + ++h; + // For each house, calculate distance to nearest LHS heater + for (auto i = rbegin(houses), h = rbegin(heaters), r = rbegin(res); + i != rend(houses) and h != rend(heaters);) + if (*i >= *h) + *r++ = min(*r, *i++ - *h); + else + ++h; + return *max_element(begin(res), end(res)); + } +}; \ No newline at end of file diff --git a/cpp/476.NumberComplement/iteration.cpp b/cpp/476.NumberComplement/iteration.cpp deleted file mode 100644 index 7981dcf..0000000 --- a/cpp/476.NumberComplement/iteration.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int findComplement(int num) { - int count=0,num2=num; - while(num2){ - count++; - num2>>=1; - } - int i=(1<>= 1; + } + int i = (1 << count) - 1; + return i - num; + } +}; diff --git a/cpp/477.TotalHammingDistance/TLE.cpp b/cpp/477.TotalHammingDistance/TLE.cpp deleted file mode 100644 index fc4849f..0000000 --- a/cpp/477.TotalHammingDistance/TLE.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int totalHammingDistance(vector& nums) { - int res=0; - for(int i=0;i>1)+(res&0x55555555); - res=((res&0xcccccccc)>>2)+(res&0x33333333); - res=((res&0xf0f0f0f0)>>4)+(res&0x0f0f0f0f); - res=((res&0xff00ff00)>>8)+(res&0x00ff00ff); - res=((res&0xffff0000)>>16)+(res&0x0000ffff); - return res; - } -}; diff --git a/cpp/477.TotalHammingDistance/better.cpp b/cpp/477.TotalHammingDistance/better.cpp deleted file mode 100644 index f663c64..0000000 --- a/cpp/477.TotalHammingDistance/better.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int totalHammingDistance(vector& nums) { - int res=0; - for(int i=0;i<32;++i){ - int bitCount=0; - for(int num:nums) - bitCount+=(num>>i)&1; - res+=bitCount*(nums.size()-bitCount); - } - return res; - } -}; diff --git a/cpp/477.TotalHammingDistance/more-better.cpp b/cpp/477.TotalHammingDistance/more-better.cpp deleted file mode 100644 index a4da00c..0000000 --- a/cpp/477.TotalHammingDistance/more-better.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int totalHammingDistance(vector& nums) { - vector stack(32); - int res=0; - for(int i=0; i>1; - } - } - for(int i=0; i &nums) { + int res = 0; + for (int i = 0; i < 32; ++i) { + int bitCount = 0; + for (int num : nums) + bitCount += (num >> i) & 1; + res += bitCount * (nums.size() - bitCount); + } + return res; + } +}; +// more-better.cpp +class Solution2 { +public: + int totalHammingDistance(vector &nums) { + vector stack(32); + int res = 0; + for (int i = 0; i < nums.size(); i++) { + int tmp = nums[i]; + for (int j = 0; j < 32; j++) { + stack[j] += tmp & 1; + tmp = tmp >> 1; + } + } + for (int i = 0; i < stack.size(); i++) + res += stack[i] * (nums.size() - stack[i]); + return res; + } +}; +// TLE.cpp +class Solution3 { +public: + int totalHammingDistance(vector &nums) { + int res = 0; + for (int i = 0; i < nums.size(); ++i) + for (int j = i + 1; j < nums.size(); ++j) + res += getHammingDistance(nums[i], nums[j]); + return res; + } + int getHammingDistance(unsigned int num1, unsigned int num2) { + int res = num1 ^ num2; + res = ((res & 0xaaaaaaaa) >> 1) + (res & 0x55555555); + res = ((res & 0xcccccccc) >> 2) + (res & 0x33333333); + res = ((res & 0xf0f0f0f0) >> 4) + (res & 0x0f0f0f0f); + res = ((res & 0xff00ff00) >> 8) + (res & 0x00ff00ff); + res = ((res & 0xffff0000) >> 16) + (res & 0x0000ffff); + return res; + } +}; diff --git a/cpp/48.RotateImage/noExtraSpace.cpp b/cpp/48.RotateImage/noExtraSpace.cpp deleted file mode 100644 index 3193f0d..0000000 --- a/cpp/48.RotateImage/noExtraSpace.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - void rotate(vector>& matrix) { - int n=matrix.size(),times=n/2; - for(int k=0;k>& matrix) { + int n = matrix.size(), times = n / 2; + for (int k = 0; k < times; ++k) + for (int i = k; i < n - k - 1; ++i) { + int temp = matrix[k][i]; + matrix[k][i] = matrix[n - 1 - i][k]; + matrix[n - 1 - i][k] = matrix[n - 1 - k][n - 1 - i]; + matrix[n - 1 - k][n - 1 - i] = matrix[i][n - 1 - k]; + matrix[i][n - 1 - k] = temp; + } + } +}; +class Solution2 { +public: + void rotate(vector>& matrix) { + int n = matrix.size(); + for (int level = 0; level < matrix.size() / 2; ++level) { + for (int i = 0; level + i < n - 1 - level; ++i) { + auto& lt = matrix[level][level + i]; + auto& rt = matrix[level + i][n - level - 1]; + auto& lb = matrix[n - level - 1 - i][level]; + auto& rb = matrix[n - level - 1][n - level - 1 - i]; + auto temp = lt; + lt = lb; + lb = rb; + rb = rt; + rt = temp; + } + } + } +}; \ No newline at end of file diff --git a/cpp/482.LicenseKeyFormatting/smarter-6ms.cpp b/cpp/482.LicenseKeyFormatting/smarter-6ms.cpp deleted file mode 100644 index a207c96..0000000 --- a/cpp/482.LicenseKeyFormatting/smarter-6ms.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - string licenseKeyFormatting(string S, int K) { - string res; - int count=0; - for(auto it=S.rbegin();it!=S.rend();++it) - if(*it!='-'){ - if(count++==K){ - count=1; - res+='-'; - } - res+=toupper(*it); - } - return string(res.rbegin(),res.rend()); - } -}; diff --git a/cpp/482.LicenseKeyFormatting/stupid-9ms.cpp b/cpp/482.LicenseKeyFormatting/stupid-9ms.cpp deleted file mode 100644 index 28ca114..0000000 --- a/cpp/482.LicenseKeyFormatting/stupid-9ms.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { -public: - string licenseKeyFormatting(string S, int K) { - int dashNumber=0; - for(auto ch:S) - if(ch=='-') - ++dashNumber; - int charNumber=S.size()-dashNumber; - int headSize=charNumber%K; - string res; - int i=0,j=0; - for(;i='a'&&S[j]<='z'?S[j]+'A'-'a':S[j]; - ++i; - } - if(headSize) - res+='-'; - for(i=0;j='a'&&S[j]<='z'?S[j]+'A'-'a':S[j]; - if(++i==K){ - i=0; - res+='-'; - } - } - } - if(res.back()=='-') - res.pop_back(); - return res; - } -}; diff --git a/cpp/482.cpp b/cpp/482.cpp new file mode 100644 index 0000000..06c95fb --- /dev/null +++ b/cpp/482.cpp @@ -0,0 +1,50 @@ +// smarter-6ms.cpp +class Solution { +public: + string licenseKeyFormatting(string S, int K) { + string res; + int count = 0; + for (auto it = S.rbegin(); it != S.rend(); ++it) + if (*it != '-') { + if (count++ == K) { + count = 1; + res += '-'; + } + res += toupper(*it); + } + return string(res.rbegin(), res.rend()); + } +}; +// stupid-9ms.cpp +class Solution2 { +public: + string licenseKeyFormatting(string S, int K) { + int dashNumber = 0; + for (auto ch : S) + if (ch == '-') + ++dashNumber; + int charNumber = S.size() - dashNumber; + int headSize = charNumber % K; + string res; + int i = 0, j = 0; + for (; i < headSize; ++j) + if (S[j] != '-') { + res += S[j] >= 'a' && S[j] <= 'z' ? S[j] + 'A' - 'a' : S[j]; + ++i; + } + if (headSize) + res += '-'; + for (i = 0; j < S.size(); ++j) { + if (S[j] != '-') { + res += S[j] >= 'a' && S[j] <= 'z' ? S[j] + 'A' - 'a' : S[j]; + if (++i == K) { + i = 0; + res += '-'; + } + } + } + if (res.back() == '-') + res.pop_back(); + return res; + } +}; diff --git a/cpp/485.MaxConsecutive/onepass.cpp b/cpp/485.MaxConsecutive/onepass.cpp deleted file mode 100644 index 45d9d76..0000000 --- a/cpp/485.MaxConsecutive/onepass.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int findMaxConsecutiveOnes(vector& nums) { - int max=0,count=0; - for(int i=0;imax) - max=count; - } - return max; - } -}; diff --git a/cpp/485.cpp b/cpp/485.cpp new file mode 100644 index 0000000..91825d3 --- /dev/null +++ b/cpp/485.cpp @@ -0,0 +1,13 @@ +// onepass.cpp +class Solution { +public: + int findMaxConsecutiveOnes(vector &nums) { + int max = 0, count = 0; + for (int i = 0; i < nums.size(); i++) { + (nums[i] == 1) ? count++ : count = 0; + if (count > max) + max = count; + } + return max; + } +}; diff --git a/cpp/49.GroupAnagrams/sort_hash.cpp b/cpp/49.GroupAnagrams/sort_hash.cpp deleted file mode 100644 index f9bd3ba..0000000 --- a/cpp/49.GroupAnagrams/sort_hash.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - vector> groupAnagrams(vector& strs) { - unordered_mapmap; - vector>res; - for(int i=0,count=0;i(1,strs[i])); - } - else{ - res[it->second].push_back(strs[i]); - } - } - return res; - } -}; diff --git a/cpp/49.cpp b/cpp/49.cpp new file mode 100644 index 0000000..64ae2ee --- /dev/null +++ b/cpp/49.cpp @@ -0,0 +1,43 @@ +// sort_hash.cpp +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map map; + vector> res; + for (int i = 0, count = 0; i < strs.size(); ++i) { + string newstr = strs[i]; + ranges::sort(newstr); + auto it = map.find(newstr); + if (it == map.end()) { + map[newstr] = count++; + res.push_back({strs[i]}); + } else { + res[it->second].push_back(strs[i]); + } + } + return res; + } +}; +// encode +class Solution2 { + string encode(const string& s) { + string res(26, 0); + for (char c : s) { + ++res[c - 'a']; + } + return res; + } + +public: + vector> groupAnagrams(vector& strs) { + unordered_map> mp; + for (auto& s : strs) { + mp[encode(s)].push_back(s); + } + vector> res; + for (auto& [k, v] : mp) { + res.push_back(move(v)); + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/491.IncreasingSubsequences/dfs.cpp b/cpp/491.IncreasingSubsequences/dfs.cpp deleted file mode 100644 index 5eff14e..0000000 --- a/cpp/491.IncreasingSubsequences/dfs.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { - set>myset; -public: - vector> findSubsequences(vector& nums) { - dfs(nums, vector(), 0); - vector>res(myset.begin(), myset.end()); - return res; - } - void dfs(vector&nums, vectorarr, int i) { - if (i == nums.size())return; - dfs(nums, arr, i + 1); - if (arr.size()==0||nums[i] >= arr.back()) { - arr.push_back(nums[i]); - if (arr.size() > 1 && myset.find(arr)==myset.end()) - myset.insert(arr); - dfs(nums, arr, i + 1); - } - } -}; diff --git a/cpp/491.cpp b/cpp/491.cpp new file mode 100644 index 0000000..7a8a525 --- /dev/null +++ b/cpp/491.cpp @@ -0,0 +1,22 @@ +// dfs.cpp +class Solution { + set> myset; + +public: + vector> findSubsequences(vector &nums) { + dfs(nums, vector(), 0); + vector> res(myset.begin(), myset.end()); + return res; + } + void dfs(vector &nums, vector arr, int i) { + if (i == nums.size()) + return; + dfs(nums, arr, i + 1); + if (arr.size() == 0 || nums[i] >= arr.back()) { + arr.push_back(nums[i]); + if (arr.size() > 1 && myset.find(arr) == myset.end()) + myset.insert(arr); + dfs(nums, arr, i + 1); + } + } +}; diff --git a/cpp/492.ConstructTheRectangle/sqrt-3ms.cpp b/cpp/492.ConstructTheRectangle/sqrt-3ms.cpp deleted file mode 100644 index a29cad9..0000000 --- a/cpp/492.ConstructTheRectangle/sqrt-3ms.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - vector constructRectangle(int area) { - vectorresult(2); - int max_wide=0; - for(int i=1;i*i<=area;++i) - if(area%i==0) - max_wide=i; - result[0]=area/max_wide; - result[1]=max_wide; - return result; - } -}; diff --git a/cpp/492.cpp b/cpp/492.cpp new file mode 100644 index 0000000..cd60a3e --- /dev/null +++ b/cpp/492.cpp @@ -0,0 +1,14 @@ +// sqrt-3ms.cpp +class Solution { +public: + vector constructRectangle(int area) { + vector result(2); + int max_wide = 0; + for (int i = 1; i * i <= area; ++i) + if (area % i == 0) + max_wide = i; + result[0] = area / max_wide; + result[1] = max_wide; + return result; + } +}; diff --git a/cpp/494.TargetSum/dp.cpp b/cpp/494.TargetSum/dp.cpp deleted file mode 100644 index 8425d1a..0000000 --- a/cpp/494.TargetSum/dp.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - int findTargetSumWays(vector& nums, int S) { - int sum=0,len=nums.size(); - for(int i=0;i>1; - vectordp(V+1,0); - dp[0]=1; - for(int i=0;i &nums, int S) { + int sum = 0, len = nums.size(); + for (int i = 0; i < len; ++i) + sum += nums[i]; + if (((S + sum) & 1) == 1 || (sum + S) < 0 || sum < S) + return 0; + int V = (sum + S) >> 1; + vector dp(V + 1, 0); + dp[0] = 1; + for (int i = 0; i < len; ++i) + for (int v = V; nums[i] <= v; --v) + dp[v] += dp[v - nums[i]]; + return dp[V]; + } +}; diff --git a/cpp/495.TeemoAttacking/onepass.cpp b/cpp/495.TeemoAttacking/onepass.cpp deleted file mode 100644 index ee4f357..0000000 --- a/cpp/495.TeemoAttacking/onepass.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int findPoisonedDuration(vector& timeSeries, int duration) { - int len=timeSeries.size(),sum=0,gap; - for(int i=0;i0) - return sum+duration; - else - return 0; - } -}; diff --git a/cpp/495.cpp b/cpp/495.cpp new file mode 100644 index 0000000..ca1ffd1 --- /dev/null +++ b/cpp/495.cpp @@ -0,0 +1,14 @@ +// onepass.cpp +class Solution { +public: + int findPoisonedDuration(vector &timeSeries, int duration) { + int len = timeSeries.size(), sum = 0, gap; + for (int i = 0; i < len - 1; i++) + (gap = timeSeries[i + 1] - timeSeries[i]) < duration ? sum += gap + : sum += duration; + if (len > 0) + return sum + duration; + else + return 0; + } +}; diff --git a/cpp/496.NextGreaterElementI/solution.cpp b/cpp/496.NextGreaterElementI/solution.cpp deleted file mode 100644 index c2d3e67..0000000 --- a/cpp/496.NextGreaterElementI/solution.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - vector nextGreaterElement(vector& findNums, vector& nums) { - int i=findNums.size(),j=nums.size(); - vectorresult(i); - for(int m=0;mfindNums[m]){ - result[m]=nums[k]; - break; - } - break; - } - return result; - } -}; diff --git a/cpp/496.cpp b/cpp/496.cpp new file mode 100644 index 0000000..7a8d7d7 --- /dev/null +++ b/cpp/496.cpp @@ -0,0 +1,21 @@ +// solution.cpp +class Solution { +public: + vector nextGreaterElement(vector &findNums, vector &nums) { + int i = findNums.size(), j = nums.size(); + vector result(i); + for (int m = 0; m < i; ++m) + result[m] = -1; + for (int m = 0; m < i; ++m) + for (int n = 0; n < j; ++n) + if (findNums[m] == nums[n]) { + for (int k = n + 1; k < j; ++k) + if (nums[k] > findNums[m]) { + result[m] = nums[k]; + break; + } + break; + } + return result; + } +}; diff --git a/cpp/498.DiagonalTraverse/simple.cpp b/cpp/498.DiagonalTraverse/simple.cpp deleted file mode 100644 index 637fad5..0000000 --- a/cpp/498.DiagonalTraverse/simple.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - vector findDiagonalOrder(vector>& matrix) { - int m=matrix.size(); - if(m==0)return vector(); - int n=matrix[0].size(),i=0,j=0,k=1,sum=m*n; - vectorres(sum); - res[0]=matrix[0][0]; - while(k=0&&j+1=0) - res[k++]=matrix[++i][--j]; - if(i+1 findDiagonalOrder(vector> &matrix) { + int m = matrix.size(); + if (m == 0) + return vector(); + int n = matrix[0].size(), i = 0, j = 0, k = 1, sum = m * n; + vector res(sum); + res[0] = matrix[0][0]; + while (k < sum) { + while (i - 1 >= 0 && j + 1 < n) + res[k++] = matrix[--i][++j]; + if (j + 1 < n) + res[k++] = matrix[i][++j]; + else if (i + 1 < m) + res[k++] = matrix[++i][j]; + while (i + 1 < m && j - 1 >= 0) + res[k++] = matrix[++i][--j]; + if (i + 1 < m) + res[k++] = matrix[++i][j]; + else if (j + 1 < n) + res[k++] = matrix[i][++j]; + } + return res; + } +}; diff --git a/cpp/5.LongestPalindromicSubstring/center-extend.cpp b/cpp/5.LongestPalindromicSubstring/center-extend.cpp deleted file mode 100644 index 57768da..0000000 --- a/cpp/5.LongestPalindromicSubstring/center-extend.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { - int getPalindromeLength(string &str,int index){ - int len=1; - while(index-len>=0&&index+lenlen){ - len=cur; - index=i; - } - } - return s.substr(index/2-len/2,len); - } -}; diff --git a/cpp/5.cpp b/cpp/5.cpp new file mode 100644 index 0000000..9a0dc5a --- /dev/null +++ b/cpp/5.cpp @@ -0,0 +1,55 @@ +// center-extend.cpp +class Solution { + int getPalindromeLength(string& str, int index) { + int len = 1; + while (index - len >= 0 && index + len < str.size() && + str[index - len] == str[index + len]) + ++len; + return len - 1; + } // #b#a#b#a#d#,#c#b#b#d# +public: + string longestPalindrome(string s) { + if (s.size() <= 1) + return s; + string str = "#"; + for (int i = 0; i < s.size(); ++i, str += "#") + str.append(1, s[i]); + int len = 0, cur, index; + for (int i = 1; i < str.size(); ++i) { + cur = getPalindromeLength(str, i); + if (cur > len) { + len = cur; + index = i; + } + } + return s.substr(index / 2 - len / 2, len); + } +}; +class SolutionDP { + bool recursive(const string& s, int i, int j, vector>& dp) { + if (i >= j) { + return dp[i][j] = 1; + } + if (dp[i][j] != -1) { + return dp[i][j]; + } + if (s[i] == s[j]) { + return dp[i][j] = recursive(s, i + 1, j - 1, dp); + } else { + return dp[i][j] = 0; + } + } + +public: + string longestPalindrome(string s) { + vector> dp(s.size(), vector(s.size(), -1)); + for (int len = s.size(); len > 0; --len) { + for (int i = 0; i + len <= s.size(); ++i) { + if (recursive(s, i, i + len - 1, dp)) { + return s.substr(i, len); + } + } + } + return ""; + } +}; \ No newline at end of file diff --git a/cpp/50.Powx,n/recursion.cpp b/cpp/50.Powx,n/recursion.cpp deleted file mode 100644 index b713006..0000000 --- a/cpp/50.Powx,n/recursion.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - double myPow(double x, long long int n) { - if(n==0)return 1; - if(n<0){ - x=1/x; - n=-n; - } - return n%2==0?myPow(x*x,n/2):x*myPow(x*x,n/2); - } -}; diff --git a/cpp/50.cpp b/cpp/50.cpp new file mode 100644 index 0000000..f029fee --- /dev/null +++ b/cpp/50.cpp @@ -0,0 +1,13 @@ +// recursion.cpp +class Solution { +public: + double myPow(double x, long long int n) { + if (n == 0) + return 1; + if (n < 0) { + x = 1 / x; + n = -n; + } + return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); + } +}; diff --git a/cpp/500.KeyBoardRow/hash.cpp b/cpp/500.KeyBoardRow/hash.cpp deleted file mode 100644 index a8f4ed9..0000000 --- a/cpp/500.KeyBoardRow/hash.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -public: - int hash[26] = {2,3,3,2,1,2,2,2,1,2,2,2,3,3,1,1,1,1,2,1,1,3,1,3,1,3}; - vector findWords(vector& words) { - vector res; - for(string val : words) - { - if(val == "") continue; - int line = val[0] >= 'a'?hash[val[0]-'a']:hash[val[0]-'A']; - bool flag = true; - for(char ch : val) - { - int h_code = ch >= 'a'?hash[ch-'a']:hash[ch-'A']; - if(h_code != line) - { flag = false; break;} - } - if(flag) - res.push_back(val); - } - return res; - } -}; diff --git a/cpp/500.cpp b/cpp/500.cpp new file mode 100644 index 0000000..33be7b0 --- /dev/null +++ b/cpp/500.cpp @@ -0,0 +1,25 @@ +// hash.cpp +class Solution { +public: + int hash[26] = {2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, + 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3}; + vector findWords(vector &words) { + vector res; + for (string val : words) { + if (val == "") + continue; + int line = val[0] >= 'a' ? hash[val[0] - 'a'] : hash[val[0] - 'A']; + bool flag = true; + for (char ch : val) { + int h_code = ch >= 'a' ? hash[ch - 'a'] : hash[ch - 'A']; + if (h_code != line) { + flag = false; + break; + } + } + if (flag) + res.push_back(val); + } + return res; + } +}; diff --git a/cpp/501.FindModeInBinarySearchTree/inOrderTraversal.cpp b/cpp/501.FindModeInBinarySearchTree/inOrderTraversal.cpp deleted file mode 100644 index ab79e57..0000000 --- a/cpp/501.FindModeInBinarySearchTree/inOrderTraversal.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - vectorresult; - int curCount=0; - int maxCount=0; - int lastValue; - bool firstTime=1; -public: - vector findMode(TreeNode* root) { - inOrder(root); - return result; - } - void inOrder(TreeNode* root){ - if(root==NULL) - return; - inOrder(root->left); - if(firstTime){ - lastValue=root->val; - firstTime=0; - } - if(lastValue!=root->val){ - curCount=0; - lastValue=root->val; - } - if(lastValue==root->val){ - ++curCount; - if(curCount==maxCount){ - result.push_back(lastValue); - } - else if(curCount>maxCount){ - maxCount=curCount; - result.clear(); - result.push_back(lastValue); - } - } - inOrder(root->right); - } -}; diff --git a/cpp/501.cpp b/cpp/501.cpp new file mode 100644 index 0000000..6eda9ce --- /dev/null +++ b/cpp/501.cpp @@ -0,0 +1,47 @@ +// inOrderTraversal.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + vector result; + int curCount = 0; + int maxCount = 0; + int lastValue; + bool firstTime = 1; + +public: + vector findMode(TreeNode *root) { + inOrder(root); + return result; + } + void inOrder(TreeNode *root) { + if (root == NULL) + return; + inOrder(root->left); + if (firstTime) { + lastValue = root->val; + firstTime = 0; + } + if (lastValue != root->val) { + curCount = 0; + lastValue = root->val; + } + if (lastValue == root->val) { + ++curCount; + if (curCount == maxCount) { + result.push_back(lastValue); + } else if (curCount > maxCount) { + maxCount = curCount; + result.clear(); + result.push_back(lastValue); + } + } + inOrder(root->right); + } +}; diff --git a/cpp/504.Base7/base7.cpp b/cpp/504.Base7/base7.cpp deleted file mode 100644 index 0bee5a0..0000000 --- a/cpp/504.Base7/base7.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -public: - string convertToBase7(int num) { - if(num==0) - return "0"; - bool neg=0; - if(num<0){ - neg=1; - num=-num; - } - char ch; - string s=""; - while(num>0){ - ch=num%7+'0'; - s=ch+s; - num=(num-num%7)/7; - } - if(neg==1) - s='-'+s; - return s; - } -}; diff --git a/cpp/504.cpp b/cpp/504.cpp new file mode 100644 index 0000000..41eceee --- /dev/null +++ b/cpp/504.cpp @@ -0,0 +1,23 @@ +// base7.cpp +class Solution { +public: + string convertToBase7(int num) { + if (num == 0) + return "0"; + bool neg = 0; + if (num < 0) { + neg = 1; + num = -num; + } + char ch; + string s = ""; + while (num > 0) { + ch = num % 7 + '0'; + s = ch + s; + num = (num - num % 7) / 7; + } + if (neg == 1) + s = '-' + s; + return s; + } +}; diff --git a/cpp/506.RelativeRanks/simpleidea.cpp b/cpp/506.RelativeRanks/simpleidea.cpp deleted file mode 100644 index 9748d73..0000000 --- a/cpp/506.RelativeRanks/simpleidea.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution { -public: - vector findRelativeRanks(vector& nums) { - struct tri { - int score; - int index; - string str; - tri() {}; - tri(int score, int index) :score(score), index(index), str("") {}; - }; - int n = nums.size(); - vectorarr(n); - for (int i = 0; i b.score; }); - if (n) - arr[0].str = "Gold Medal"; - if (n>1) - arr[1].str = "Silver Medal"; - if (n>2) - arr[2].str = "Bronze Medal"; - for (int i = 3; i result(n); - for (int i = 0; i findRelativeRanks(vector &nums) { + struct tri { + int score; + int index; + string str; + tri(){}; + tri(int score, int index) : score(score), index(index), str(""){}; + }; + int n = nums.size(); + vector arr(n); + for (int i = 0; i < n; ++i) + arr[i] = tri(nums[i], i); + sort(arr.begin(), arr.end(), + [](tri a, tri b) { return a.score > b.score; }); + if (n) + arr[0].str = "Gold Medal"; + if (n > 1) + arr[1].str = "Silver Medal"; + if (n > 2) + arr[2].str = "Bronze Medal"; + for (int i = 3; i < n; ++i) + arr[i].str = to_string(i + 1); + sort(arr.begin(), arr.end(), + [](tri a, tri b) { return a.index < b.index; }); + vector result(n); + for (int i = 0; i < n; ++i) + result[i] = arr[i].str; + return result; + } +}; diff --git a/cpp/507.PerfectNumber/Osqrt-3ms.cpp b/cpp/507.PerfectNumber/Osqrt-3ms.cpp deleted file mode 100644 index c928a26..0000000 --- a/cpp/507.PerfectNumber/Osqrt-3ms.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - bool checkPerfectNumber(int num) { - if(num==1)return 0; - int sum=1,i; - for(i=2;i*imap; - vectorresult; -public: - vector findFrequentTreeSum(TreeNode* root) { - if(root==NULL)return result; - postorder(root); - int max=0,f; - for(auto it=map.begin();it!=map.end();++it) - if(it->second>max){ - max=it->second; - result.assign(1,it->first); - } - else if(it->second==max) - result.push_back(it->first); - return result; - } - int postorder(TreeNode* root){ - int left=0,right=0; - if(root->left) - left=postorder(root->left); - if(root->right) - right=postorder(root->right); - map[root->val+left+right]++; - return root->val+left+right; - } -}; diff --git a/cpp/508.cpp b/cpp/508.cpp new file mode 100644 index 0000000..663126a --- /dev/null +++ b/cpp/508.cpp @@ -0,0 +1,38 @@ +// hash_postorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + unordered_map map; + vector result; + +public: + vector findFrequentTreeSum(TreeNode *root) { + if (root == NULL) + return result; + postorder(root); + int max = 0, f; + for (auto it = map.begin(); it != map.end(); ++it) + if (it->second > max) { + max = it->second; + result.assign(1, it->first); + } else if (it->second == max) + result.push_back(it->first); + return result; + } + int postorder(TreeNode *root) { + int left = 0, right = 0; + if (root->left) + left = postorder(root->left); + if (root->right) + right = postorder(root->right); + map[root->val + left + right]++; + return root->val + left + right; + } +}; diff --git a/cpp/509.FibonacciNumber.cpp b/cpp/509.FibonacciNumber.cpp deleted file mode 100644 index 19ceee3..0000000 --- a/cpp/509.FibonacciNumber.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { //0ms -public: - int fib(int N) { - int a=0,b=1; - while(N--){ - int c=a+b; - a=b; - b=c; - } - return a; - } -}; \ No newline at end of file diff --git a/cpp/509.cpp b/cpp/509.cpp new file mode 100644 index 0000000..f4e211e --- /dev/null +++ b/cpp/509.cpp @@ -0,0 +1,12 @@ +class Solution { // 0ms +public: + int fib(int N) { + int a = 0, b = 1; + while (N--) { + int c = a + b; + a = b; + b = c; + } + return a; + } +}; \ No newline at end of file diff --git a/cpp/51.N-Queens/simplehash+dfs+9ms.cpp b/cpp/51.N-Queens/simplehash+dfs+9ms.cpp deleted file mode 100644 index 27a7817..0000000 --- a/cpp/51.N-Queens/simplehash+dfs+9ms.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution { - unordered_setver,lTilt,rTilt; - vector>res; - vectorr; - int n; -public: - vector> solveNQueens(int n) { - string str(n,'.'); - this->n=n; - r.assign(n,str); - dfs(0); - return res; - } - void dfs(int i){ - if(i==n){ - res.push_back(r); - return; - } - for(int j=0;jflag; - vector>res; - vectorr; - int n; -public: - vector> solveNQueens(int n) { - string str(n,'.'); - this->n=n; - r.assign(n,str); - flag.assign(5*n,1); - dfs(0); - return res; - } - void dfs(int i){ - if(i==n){ - res.push_back(r); - return; - } - for(int j=0;j> solveNQueens(int n) { + vector r(n, string(n, '.')); + vector> res; + unordered_set ver, lTilt, rTilt; + function dfs = [&](int i) { + if (i == n) { + res.push_back(r); + return; + } + for (int j = 0; j < n; ++j) + if (!ver.contains(j) && !lTilt.contains(i - j) && + !rTilt.contains(i + j)) { + ver.insert(j), lTilt.insert(i - j), rTilt.insert(i + j); + r[i][j] = 'Q'; + dfs(i + 1); + r[i][j] = '.'; + ver.erase(j), lTilt.erase(i - j), rTilt.erase(i + j); + } + }; + dfs(0); + return res; + } +}; +// smarthash+dfs+3ms.cpp +class Solution2 { + vector flag; + vector> res; + vector r; + int n; + void dfs(int i) { + if (i == n) { + res.push_back(r); + return; + } + for (int j = 0; j < n; ++j) + if (flag[j] && flag[n + i + j] && flag[4 * n + i - j]) { + flag[j] = flag[n + i + j] = flag[4 * n + i - j] = 0; + r[i][j] = 'Q'; + dfs(i + 1); + r[i][j] = '.'; + flag[j] = flag[n + i + j] = flag[4 * n + i - j] = 1; + } + } + +public: + vector> solveNQueens(int n) { + string str(n, '.'); + this->n = n; + r.assign(n, str); + flag.assign(5 * n, 1); + dfs(0); + return res; + } +}; diff --git a/cpp/513.FindBottomLeftTreeValue/preorder.cpp b/cpp/513.FindBottomLeftTreeValue/preorder.cpp deleted file mode 100644 index e207899..0000000 --- a/cpp/513.FindBottomLeftTreeValue/preorder.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int maxDepth=-1; - int value; -public: - int findBottomLeftValue(TreeNode* root) { - value=root->val; - preorder(root,0); - return value; - } - void preorder(TreeNode*root,int depth){ - if(root==NULL)return; - if(depth>maxDepth){ - maxDepth=depth; - value=root->val; - } - preorder(root->left,depth+1); - preorder(root->right,depth+1); - } -}; diff --git a/cpp/513.cpp b/cpp/513.cpp new file mode 100644 index 0000000..8b3ce17 --- /dev/null +++ b/cpp/513.cpp @@ -0,0 +1,31 @@ +// preorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int maxDepth = -1; + int value; + +public: + int findBottomLeftValue(TreeNode *root) { + value = root->val; + preorder(root, 0); + return value; + } + void preorder(TreeNode *root, int depth) { + if (root == NULL) + return; + if (depth > maxDepth) { + maxDepth = depth; + value = root->val; + } + preorder(root->left, depth + 1); + preorder(root->right, depth + 1); + } +}; diff --git a/cpp/515.FindLargestValueInEachTreeRow/preOrderRecursion-12ms.cpp b/cpp/515.FindLargestValueInEachTreeRow/preOrderRecursion-12ms.cpp deleted file mode 100644 index b6bfbe5..0000000 --- a/cpp/515.FindLargestValueInEachTreeRow/preOrderRecursion-12ms.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector largestValues(TreeNode* root) { - vectorresult; - preOrder(0,root,result); - return result; - } - void preOrder(int i,TreeNode* root,vector&nums){ - if(root==NULL)return; - if(nums.size()==i) - nums.push_back(INT_MIN); - if(root->val>nums[i]) - nums[i]=root->val; - preOrder(i+1,root->left,nums); - preOrder(i+1,root->right,nums); - } - -}; diff --git a/cpp/515.cpp b/cpp/515.cpp new file mode 100644 index 0000000..a6ddebc --- /dev/null +++ b/cpp/515.cpp @@ -0,0 +1,28 @@ +// preOrderRecursion-12ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector largestValues(TreeNode *root) { + vector result; + preOrder(0, root, result); + return result; + } + void preOrder(int i, TreeNode *root, vector &nums) { + if (root == NULL) + return; + if (nums.size() == i) + nums.push_back(INT_MIN); + if (root->val > nums[i]) + nums[i] = root->val; + preOrder(i + 1, root->left, nums); + preOrder(i + 1, root->right, nums); + } +}; diff --git a/cpp/52.N-QueensII/smarthash+dfs.cpp b/cpp/52.N-QueensII/smarthash+dfs.cpp deleted file mode 100644 index a2e7f64..0000000 --- a/cpp/52.N-QueensII/smarthash+dfs.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { - vectorflag; - int n,res=0; -public: - int totalNQueens(int n) { - this->n=n; - flag.assign(5*n,1); - dfs(0); - return res; - } - void dfs(int i){ - if(i==n){ - res++; - return; - } - for(int j=0;j flag(5 * n, 1); + function dfs = [&](int i) { + if (i == n) { + res++; + return; + } + for (int j = 0; j < n; ++j) + if (flag[j] && flag[n + i + j] && flag[4 * n + i - j]) { + flag[j] = flag[n + i + j] = flag[4 * n + i - j] = 0; + dfs(i + 1); + flag[j] = flag[n + i + j] = flag[4 * n + i - j] = 1; + } + }; + dfs(0); + return res; + } +}; \ No newline at end of file diff --git a/cpp/520.DetectCapital/onepass-9ms.cpp b/cpp/520.DetectCapital/onepass-9ms.cpp deleted file mode 100644 index 027341f..0000000 --- a/cpp/520.DetectCapital/onepass-9ms.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - bool detectCapitalUse(string word) { - if(word.size()==1)return 1; - int ch=word[0]-'a'; - if(ch>=0){ - for(int i=1;i=0) - { for(int i=1;i='a') - return 0; - } - return 1; - } -}; diff --git a/cpp/520.cpp b/cpp/520.cpp new file mode 100644 index 0000000..0a350d1 --- /dev/null +++ b/cpp/520.cpp @@ -0,0 +1,26 @@ +// onepass-9ms.cpp +class Solution { +public: + bool detectCapitalUse(string word) { + if (word.size() == 1) + return 1; + int ch = word[0] - 'a'; + if (ch >= 0) { + for (int i = 1; i < word.size(); ++i) + if (word[i] < 'a') + return 0; + return 1; + } + ch = word[1] - 'a'; + if (ch >= 0) { + for (int i = 1; i < word.size(); ++i) + if (word[i] < 'a') + return 0; + } else { + for (int i = 1; i < word.size(); ++i) + if (word[i] >= 'a') + return 0; + } + return 1; + } +}; diff --git a/cpp/521.LongestUncommonSubsequenceI/WTF-3ms.cpp b/cpp/521.LongestUncommonSubsequenceI/WTF-3ms.cpp deleted file mode 100644 index 531adc6..0000000 --- a/cpp/521.LongestUncommonSubsequenceI/WTF-3ms.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - int findLUSlength(string a, string b) { - return a==b?-1:(a.size()>b.size()?a.size():b.size()); - } -}; diff --git a/cpp/521.cpp b/cpp/521.cpp new file mode 100644 index 0000000..07d248a --- /dev/null +++ b/cpp/521.cpp @@ -0,0 +1,7 @@ +// WTF-3ms.cpp +class Solution { +public: + int findLUSlength(string a, string b) { + return a == b ? -1 : (a.size() > b.size() ? a.size() : b.size()); + } +}; diff --git a/cpp/523.ContinuousSubarraySum/hashset.cpp b/cpp/523.ContinuousSubarraySum/hashset.cpp deleted file mode 100644 index 92ed6d8..0000000 --- a/cpp/523.ContinuousSubarraySum/hashset.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - bool checkSubarraySum(vector& nums, int k) { - unordered_setset; - int len=nums.size(),sum=0,pre=0,i; - for(i=0;i &nums, int k) { + unordered_set set; + int len = nums.size(), sum = 0, pre = 0, i; + for (i = 0; i < len; ++i) { + sum += nums[i]; + int mod = k == 0 ? sum : sum % k; + if (set.find(mod) != set.end()) + return 1; + set.insert(pre); + pre = mod; + } + return 0; + } +}; diff --git a/cpp/524.LongestWordInDictionaryThroughDeleting/sort.cpp b/cpp/524.LongestWordInDictionaryThroughDeleting/sort.cpp deleted file mode 100644 index a7d21bb..0000000 --- a/cpp/524.LongestWordInDictionaryThroughDeleting/sort.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - string findLongestWord(string s, vector& d) { - sort(d.begin(),d.end(),[](string a,string b){return a.size()>b.size()||(a.size()==b.size()&&a &d) { + sort(d.begin(), d.end(), [](string a, string b) { + return a.size() > b.size() || (a.size() == b.size() && a < b); + }); + for (int i = 0; i < d.size(); ++i) { + int start = 0, end = s.size(), j = 0; + for (; start < end && j < d[i].size(); ++start) + if (s[start] == d[i][j]) + ++j; + if (j == d[i].size()) + return d[i]; + } + return ""; + } +}; diff --git a/cpp/525.ContiguousArray/hashmap+deque.cpp b/cpp/525.ContiguousArray/hashmap+deque.cpp deleted file mode 100644 index 3a0f10e..0000000 --- a/cpp/525.ContiguousArray/hashmap+deque.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int findMaxLength(vector& nums) { - dequeres(nums.size(),0); - int count=0,len=0; - for(int i=0;ihashmap; - for(int i=0;isecond); - } - return len; - } -}; diff --git a/cpp/525.cpp b/cpp/525.cpp new file mode 100644 index 0000000..1f4c5f2 --- /dev/null +++ b/cpp/525.cpp @@ -0,0 +1,20 @@ +// hashmap+deque.cpp +class Solution { +public: + int findMaxLength(vector &nums) { + deque res(nums.size(), 0); + int count = 0, len = 0; + for (int i = 0; i < nums.size(); ++i) + res[i] = count += nums[i] == 0 ? 1 : -1; + res.push_front(0); + unordered_map hashmap; + for (int i = 0; i < res.size(); ++i) { + auto it = hashmap.find(res[i]); + if (it == hashmap.end()) + hashmap[res[i]] = i; + else + len = max(len, i - it->second); + } + return len; + } +}; diff --git a/cpp/526.BeautifulArrangement/simple.cpp b/cpp/526.BeautifulArrangement/simple.cpp deleted file mode 100644 index 579a84a..0000000 --- a/cpp/526.BeautifulArrangement/simple.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { - int count; -public: - int countArrangement(int N) { - vectorvisited(N+1,0); - recursion(visited,N,1); - return count; - } - void recursion(vector&visited,int N,int cur){ - if(cur>N){ - ++count; - return; - } - for(int i=1;i<=N;++i) - if(visited[i]==0&&(i%cur==0||cur%i==0 )){ - visited[i]=1; - recursion(visited,N,cur+1); - visited[i]=0; - } - } -}; diff --git a/cpp/526.cpp b/cpp/526.cpp new file mode 100644 index 0000000..c504bdd --- /dev/null +++ b/cpp/526.cpp @@ -0,0 +1,23 @@ +// simple.cpp +class Solution { + int count; + +public: + int countArrangement(int N) { + vector visited(N + 1, 0); + recursion(visited, N, 1); + return count; + } + void recursion(vector &visited, int N, int cur) { + if (cur > N) { + ++count; + return; + } + for (int i = 1; i <= N; ++i) + if (visited[i] == 0 && (i % cur == 0 || cur % i == 0)) { + visited[i] = 1; + recursion(visited, N, cur + 1); + visited[i] = 0; + } + } +}; diff --git a/cpp/529.Minesweeper/simple.cpp b/cpp/529.Minesweeper/simple.cpp deleted file mode 100644 index a8f0654..0000000 --- a/cpp/529.Minesweeper/simple.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution { - enum { GAME_OVER, CLICK_SUCCESS }; - int height, width, n; -public: - vector> updateBoard(vector>& board, vector& click) { - height = board.size(), width = board[0].size(), n = click.size(); - for (int i = 0; i>& board, int x, int y) { - switch (board[x][y]) { - case 'M': { - board[x][y] = 'X'; - return GAME_OVER; - } - case 'E': { - int count = 0; - for (int i = -1; i <= 1; ++i) - for (int j = -1; j <= 1; ++j) - if (x + i<0 || y + j<0 || x + i >= height || y + j >= width) - continue; - else if (board[x + i][y + j] == 'M') - ++count; - if (count == 0) { - board[x][y] = 'B'; - for (int i = -1; i <= 1; ++i) - for (int j = -1; j <= 1; ++j) - if (x + i<0 || y + j<0 || x + i >= height || y + j >= width) - continue; - else - onClick(board, x + i, y + j); - } - else - board[x][y] = '0' + count; - } - } - return CLICK_SUCCESS; - } -}; diff --git a/cpp/529.cpp b/cpp/529.cpp new file mode 100644 index 0000000..f94fa2e --- /dev/null +++ b/cpp/529.cpp @@ -0,0 +1,43 @@ +// simple.cpp +class Solution { + enum { GAME_OVER, CLICK_SUCCESS }; + int height, width, n; + +public: + vector> updateBoard(vector> &board, + vector &click) { + height = board.size(), width = board[0].size(), n = click.size(); + for (int i = 0; i < n; i += 2) + if (onClick(board, click[i], click[i + 1]) == GAME_OVER) + return board; + return board; + } + int onClick(vector> &board, int x, int y) { + switch (board[x][y]) { + case 'M': { + board[x][y] = 'X'; + return GAME_OVER; + } + case 'E': { + int count = 0; + for (int i = -1; i <= 1; ++i) + for (int j = -1; j <= 1; ++j) + if (x + i < 0 || y + j < 0 || x + i >= height || y + j >= width) + continue; + else if (board[x + i][y + j] == 'M') + ++count; + if (count == 0) { + board[x][y] = 'B'; + for (int i = -1; i <= 1; ++i) + for (int j = -1; j <= 1; ++j) + if (x + i < 0 || y + j < 0 || x + i >= height || y + j >= width) + continue; + else + onClick(board, x + i, y + j); + } else + board[x][y] = '0' + count; + } + } + return CLICK_SUCCESS; + } +}; diff --git a/cpp/53.MaximumSubarray/dp-16ms.cpp b/cpp/53.MaximumSubarray/dp-16ms.cpp deleted file mode 100644 index dbb7d08..0000000 --- a/cpp/53.MaximumSubarray/dp-16ms.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int maxSubArray(vector& nums) { - int len=nums.size(); - vectordp(len); - dp[0]=nums[0]; - for(int i=1;i& nums) { + int ret = nums[0]; + for (int sum = 0, l = 0; l < nums.size(); ++l) { + sum += nums[l]; + ret = max(sum, ret); + if (sum < 0){ + sum = 0; + } + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/530.MinimumAbsoluteDifferenceInBST/inOrderTraversal.cpp b/cpp/530.MinimumAbsoluteDifferenceInBST/inOrderTraversal.cpp deleted file mode 100644 index 1ec7a5a..0000000 --- a/cpp/530.MinimumAbsoluteDifferenceInBST/inOrderTraversal.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int min; - int lastValue; -public: - int getMinimumDifference(TreeNode* root) { - min=INT_MAX; - lastValue=-1; - getMinimum(root); - return min; - } - void getMinimum(TreeNode* root){ - if(root->left!=NULL) - getMinimum(root->left); - if( lastValue>=0 && abs(lastValue-root->val)val); - lastValue=root->val; - if(root->right!=NULL) - getMinimum(root->right); - } -}; diff --git a/cpp/530.cpp b/cpp/530.cpp new file mode 100644 index 0000000..835021c --- /dev/null +++ b/cpp/530.cpp @@ -0,0 +1,31 @@ +// inOrderTraversal.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int min; + int lastValue; + +public: + int getMinimumDifference(TreeNode *root) { + min = INT_MAX; + lastValue = -1; + getMinimum(root); + return min; + } + void getMinimum(TreeNode *root) { + if (root->left != NULL) + getMinimum(root->left); + if (lastValue >= 0 && abs(lastValue - root->val) < min) + min = abs(lastValue - root->val); + lastValue = root->val; + if (root->right != NULL) + getMinimum(root->right); + } +}; diff --git a/cpp/532.K-DiffPairsInAnArray/onepass-39ms.cpp b/cpp/532.K-DiffPairsInAnArray/onepass-39ms.cpp deleted file mode 100644 index 909c05c..0000000 --- a/cpp/532.K-DiffPairsInAnArray/onepass-39ms.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - int findPairs(vector& nums, int k) { - set>s; - sort(nums.begin(),nums.end()); - int i=0,j=1,diff,len=nums.size(); - for(;j &nums, int k) { + set> s; + sort(nums.begin(), nums.end()); + int i = 0, j = 1, diff, len = nums.size(); + for (; j < len && i < len;) { + diff = nums[j] - nums[i]; + if (diff == k) { + s.insert(make_pair(nums[i], nums[j])); + ++j; + ++i; + } else if (diff < k) + ++j; + else + ++i; + if (i == j) + ++j; + } + return s.size(); + } +}; diff --git a/cpp/537.ComplexNumberMultiplication/o1-3ms.cpp b/cpp/537.ComplexNumberMultiplication/o1-3ms.cpp deleted file mode 100644 index 1ddf180..0000000 --- a/cpp/537.ComplexNumberMultiplication/o1-3ms.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - string complexNumberMultiply(string a, string b) { - stringstream ss; - int a1, a2, b1, b2; - int off = a.find('+'); - a1=stoi( a.substr(0,off) ); - a2=stoi( a.substr(off+1,a.size()-off-1) ); - off = b.find('+'); - b1=stoi( b.substr(0,off) ); - b2=stoi( b.substr(off+1,b.size()-off-1) ); - int c1 = a1*b1 - a2*b2, c2 = a1*b2 + a2*b1; - return to_string(c1)+"+"+to_string(c2)+"i"; - } -}; diff --git a/cpp/537.cpp b/cpp/537.cpp new file mode 100644 index 0000000..88d9453 --- /dev/null +++ b/cpp/537.cpp @@ -0,0 +1,16 @@ +// o1-3ms.cpp +class Solution { +public: + string complexNumberMultiply(string a, string b) { + stringstream ss; + int a1, a2, b1, b2; + int off = a.find('+'); + a1 = stoi(a.substr(0, off)); + a2 = stoi(a.substr(off + 1, a.size() - off - 1)); + off = b.find('+'); + b1 = stoi(b.substr(0, off)); + b2 = stoi(b.substr(off + 1, b.size() - off - 1)); + int c1 = a1 * b1 - a2 * b2, c2 = a1 * b2 + a2 * b1; + return to_string(c1) + "+" + to_string(c2) + "i"; + } +}; diff --git a/cpp/538.CovertBSTtoGreaterTree/inOrderTraversal.cpp b/cpp/538.CovertBSTtoGreaterTree/inOrderTraversal.cpp deleted file mode 100644 index 7d00b77..0000000 --- a/cpp/538.CovertBSTtoGreaterTree/inOrderTraversal.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int sum=0; -public: - TreeNode* convertBST(TreeNode* root) { - inOrder(root); - return root; - } - void inOrder(TreeNode* root){ - if(root==NULL) - return; - inOrder(root->right); - int temp=root->val; - root->val+=sum; - sum+=temp; - inOrder(root->left); - } -}; diff --git a/cpp/538.cpp b/cpp/538.cpp new file mode 100644 index 0000000..c69184e --- /dev/null +++ b/cpp/538.cpp @@ -0,0 +1,28 @@ +// inOrderTraversal.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int sum = 0; + +public: + TreeNode *convertBST(TreeNode *root) { + inOrder(root); + return root; + } + void inOrder(TreeNode *root) { + if (root == NULL) + return; + inOrder(root->right); + int temp = root->val; + root->val += sum; + sum += temp; + inOrder(root->left); + } +}; diff --git a/cpp/539.MinimumTimeDifference/sort-19ms.cpp b/cpp/539.MinimumTimeDifference/sort-19ms.cpp deleted file mode 100644 index 2c69d30..0000000 --- a/cpp/539.MinimumTimeDifference/sort-19ms.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int findMinDifference(vector& timePoints) { - vectorarr(timePoints.size()); - for(int i=0;i &timePoints) { + vector arr(timePoints.size()); + for (int i = 0; i < timePoints.size(); ++i) + arr[i] = ((timePoints[i][0] - '0') * 10 + (timePoints[i][1] - '0')) * 60 + + (timePoints[i][3] - '0') * 10 + (timePoints[i][4] - '0'); + sort(arr.begin(), arr.end()); + int min = arr[0] + 24 * 60 - arr[arr.size() - 1]; + for (int i = 1; i < arr.size(); ++i) + min = min < arr[i] - arr[i - 1] ? min : arr[i] - arr[i - 1]; + return min; + } +}; diff --git a/cpp/54.SpiralMatrix/iteration-3ms.cpp b/cpp/54.SpiralMatrix/iteration-3ms.cpp deleted file mode 100644 index 23b5295..0000000 --- a/cpp/54.SpiralMatrix/iteration-3ms.cpp +++ /dev/null @@ -1,45 +0,0 @@ -class Solution { -public: - vector spiralOrder(vector>& matrix) { - vectorresult; - int m=matrix.size(); - if(m<1)return result; - int n=matrix[0].size(); - int i=0,j=0; - while(n>0&&m>0){ - result.push_back(matrix[i][j]); - int k=1; - --n; - while(k<=n){ - result.push_back(matrix[i][j+k]); - ++k; - } - j=j+n; - k=1; - --m; - if(m==0)break; - while(k<=m){ - result.push_back(matrix[i+k][j]); - ++k; - } - i=i+m; - k=1; - if(n==0)break; - while(k<=n){ - result.push_back(matrix[i][j-k]); - ++k; - } - j=j-n; - k=1; - --m; - while(k<=m){ - result.push_back(matrix[i-k][j]); - ++k; - } - i=i-m; - j+=1; - --n; - } - return result; - } -}; diff --git a/cpp/54.cpp b/cpp/54.cpp new file mode 100644 index 0000000..cce63d8 --- /dev/null +++ b/cpp/54.cpp @@ -0,0 +1,78 @@ +// iteration-3ms.cpp +class Solution { +public: + vector spiralOrder(vector>& matrix) { + vector result; + int m = matrix.size(); + if (m < 1) + return result; + int n = matrix[0].size(); + int i = 0, j = 0; + while (n > 0 && m > 0) { + result.push_back(matrix[i][j]); + int k = 1; + --n; + while (k <= n) { + result.push_back(matrix[i][j + k]); + ++k; + } + j = j + n; + k = 1; + --m; + if (m == 0) + break; + while (k <= m) { + result.push_back(matrix[i + k][j]); + ++k; + } + i = i + m; + k = 1; + if (n == 0) + break; + while (k <= n) { + result.push_back(matrix[i][j - k]); + ++k; + } + j = j - n; + k = 1; + --m; + while (k <= m) { + result.push_back(matrix[i - k][j]); + ++k; + } + i = i - m; + j += 1; + --n; + } + return result; + } +}; +class SolutionGenSteps { + vector genSteps(int m, int n) { + if (m == 1) + return {n - 1, 0, 0, 0}; + if (n == 1) + return {0, m - 1, 0, 0}; + return {n - 1, m - 1, n - 1, m - 2}; + } + +public: + vector spiralOrder(vector> matrix) { + auto directions = vector>{pair{0, 1}, pair{1, 0}, + pair{0, -1}, pair{-1, 0}}; + vector res; + int m = matrix.size(), n = matrix[0].size(); + for (int i = 0, j = 0, d = 0; res.size() < m * n; ++j) { + res.push_back(matrix[i][j]); + for (auto step : genSteps(m - 2 * i, n - 2 * i)) { + auto [x, y] = directions[d]; + for (int k = 0; k < step; ++k) { + i += x, j += y; + res.push_back(matrix[i][j]); + } + d = (d + 1) % 4; + } + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/540.SingleElementInASortedArray/binary-search.cpp b/cpp/540.SingleElementInASortedArray/binary-search.cpp deleted file mode 100644 index e99df6e..0000000 --- a/cpp/540.SingleElementInASortedArray/binary-search.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - int singleNonDuplicate(vector& nums) { - return helper(0,nums.size()-1,nums); - } - int helper(int left,int right,vector&nums){ - if(left==right) - return nums[left]; - int mid=(left+right)/2; - if(nums[mid]!=nums[mid+1]&&nums[mid]!=nums[mid-1]) - return nums[mid]; - if(((right-left)/2)&1){//odd - if(nums[mid]==nums[mid+1]) - return helper(left,mid-1,nums); - else if(nums[mid]==nums[mid-1]) - return helper(mid+1,right,nums); - } - else{//even - if(nums[mid]==nums[mid+1]) - return helper(mid+2,right,nums); - else if(nums[mid]==nums[mid-1]) - return helper(left,mid-2,nums); - } - } -}; diff --git a/cpp/540.SingleElementInASortedArray/single-scan.cpp b/cpp/540.SingleElementInASortedArray/single-scan.cpp deleted file mode 100644 index 946fce8..0000000 --- a/cpp/540.SingleElementInASortedArray/single-scan.cpp +++ /dev/null @@ -1,8 +0,0 @@ -class Solution { -public: - int singleNonDuplicate(vector& nums) { - for(int i=0;i &nums) { + return helper(0, nums.size() - 1, nums); + } + int helper(int left, int right, vector &nums) { + if (left == right) + return nums[left]; + int mid = (left + right) / 2; + if (nums[mid] != nums[mid + 1] && nums[mid] != nums[mid - 1]) + return nums[mid]; + if (((right - left) / 2) & 1) { // odd + if (nums[mid] == nums[mid + 1]) + return helper(left, mid - 1, nums); + else if (nums[mid] == nums[mid - 1]) + return helper(mid + 1, right, nums); + } else { // even + if (nums[mid] == nums[mid + 1]) + return helper(mid + 2, right, nums); + else if (nums[mid] == nums[mid - 1]) + return helper(left, mid - 2, nums); + } + } +}; +// single-scan.cpp +class Solution2 { +public: + int singleNonDuplicate(vector &nums) { + for (int i = 0; i < nums.size(); i += 2) + if (i == nums.size() - 1 || nums[i] != nums[i + 1]) + return nums[i]; + } +}; diff --git a/cpp/541.ReverseStringII/onepass.cpp b/cpp/541.ReverseStringII/onepass.cpp deleted file mode 100644 index 11ce47e..0000000 --- a/cpp/541.ReverseStringII/onepass.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - string reverseStr(string s, int k) { - int len=s.size(); - for(int i=0;i= row || y < 0 || y >= col) - return 0; - return 1; - } - int bruteForce(vector>&matrix,int i,int j) { - int len = 1; - while (1) { - int x = 0, y = len; - while (0 <= y) { - if ((valid(i + x, j + y) && matrix[i + x][j + y] == 0) || - (valid(i - x, j + y) && matrix[i - x][j + y] == 0) || - (valid(i + x, j - y) && matrix[i + x][j - y] == 0) || - (valid(i - x, j - y) && matrix[i - x][j - y] == 0)) - return len; - x++, y--; - } - ++len; - } - } -public: - vector> updateMatrix(vector>& matrix) { - row=matrix.size(); - col=matrix[0].size(); - vector>res(row,vector(col,0)); - for(int i=0;i= row || y < 0 || y >= col) + return 0; + return 1; + } + int bruteForce(vector> &matrix, int i, int j) { + int len = 1; + while (1) { + int x = 0, y = len; + while (0 <= y) { + if ((valid(i + x, j + y) && matrix[i + x][j + y] == 0) || + (valid(i - x, j + y) && matrix[i - x][j + y] == 0) || + (valid(i + x, j - y) && matrix[i + x][j - y] == 0) || + (valid(i - x, j - y) && matrix[i - x][j - y] == 0)) + return len; + x++, y--; + } + ++len; + } + } + +public: + vector> updateMatrix(vector> &matrix) { + row = matrix.size(); + col = matrix[0].size(); + vector> res(row, vector(col, 0)); + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + if (matrix[i][j]) + res[i][j] = bruteForce(matrix, i, j); + return res; + } +}; diff --git a/cpp/543.DiameterOfBinaryTree/recursion.cpp b/cpp/543.DiameterOfBinaryTree/recursion.cpp deleted file mode 100644 index 280ed58..0000000 --- a/cpp/543.DiameterOfBinaryTree/recursion.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int result=0; -public: - int diameterOfBinaryTree(TreeNode* root) { - getDepth(root); - return result; - } - int getDepth(TreeNode* root){ - if(root==NULL) - return 0; - int depth1=getDepth(root->left); - int depth2=getDepth(root->right); - if(depth1+depth2>result) - result=depth1+depth2; - return depth1>depth2?depth1+1:depth2+1; - } -}; diff --git a/cpp/543.cpp b/cpp/543.cpp new file mode 100644 index 0000000..0b7035b --- /dev/null +++ b/cpp/543.cpp @@ -0,0 +1,28 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int result = 0; + +public: + int diameterOfBinaryTree(TreeNode *root) { + getDepth(root); + return result; + } + int getDepth(TreeNode *root) { + if (root == NULL) + return 0; + int depth1 = getDepth(root->left); + int depth2 = getDepth(root->right); + if (depth1 + depth2 > result) + result = depth1 + depth2; + return depth1 > depth2 ? depth1 + 1 : depth2 + 1; + } +}; diff --git a/cpp/547.FriendCircles/BFS-23ms.cpp b/cpp/547.FriendCircles/BFS-23ms.cpp deleted file mode 100644 index af9c32c..0000000 --- a/cpp/547.FriendCircles/BFS-23ms.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* -There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends. - -Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students. - -Example 1: -Input: -[[1,1,0], - [1,1,0], - [0,0,1]] -Output: 2 -Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. -The 2nd student himself is in a friend circle. So return 2. - -Example 2: -Input: -[[1,1,0], - [1,1,1], - [0,1,1]] -Output: 1 -Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, -so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1. - -Note: -N is in range [1,200]. -M[i][i] = 1 for all students. -If M[i][j] = 1, then M[j][i] = 1. -*/ - -class Solution { -public: - int findCircleNum(vector>& M) { - int count=0,n=M.size(); - unordered_setover; - dequedq; - for(int i=0;i> &M) { + int count = 0, n = M.size(); + unordered_set over; + deque dq; + for (int i = 0; i < n; ++i) { + if (over.find(i) == over.end()) { + dq.push_back(i); + ++count; + while (!dq.empty()) { + int k = dq.front(); + over.insert(k); + dq.pop_front(); + for (int j = 0; j < n; ++j) { + if (k == j) + M[k][j] = 0; + else if (M[k][j] == 1) { + M[k][j] = 0; + M[j][k] = 0; + dq.push_back(j); + } + } + } + } + } + return count; + } +}; \ No newline at end of file diff --git a/cpp/55.JumpGame/onepass.cpp b/cpp/55.JumpGame/onepass.cpp deleted file mode 100644 index 2486d9a..0000000 --- a/cpp/55.JumpGame/onepass.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - bool canJump(vector& nums) { - int last=nums.size()-1; - for(int j=last-1;j>=0;j--) - if(nums[j]+j>=last) - last=j; - return last==0; - } -}; diff --git a/cpp/55.cpp b/cpp/55.cpp new file mode 100644 index 0000000..beb11a1 --- /dev/null +++ b/cpp/55.cpp @@ -0,0 +1,11 @@ +// onepass.cpp +class Solution { +public: + bool canJump(vector& nums) { + int last = nums.size() - 1; + for (int j = last - 1; j >= 0; j--) + if (nums[j] + j >= last) + last = j; + return last == 0; + } +}; diff --git a/cpp/551.StudentAttendanceRecordI/onepass.cpp b/cpp/551.StudentAttendanceRecordI/onepass.cpp deleted file mode 100644 index 54ffe33..0000000 --- a/cpp/551.StudentAttendanceRecordI/onepass.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - bool checkRecord(string s) { - int a=0,l=0,n=s.size(),maxl=0; - for(int i=0;imaxl?l:maxl; - } - else - l=0; - return a<=1&&maxl<=2; - } -}; diff --git a/cpp/551.cpp b/cpp/551.cpp new file mode 100644 index 0000000..74f841a --- /dev/null +++ b/cpp/551.cpp @@ -0,0 +1,17 @@ +// onepass.cpp +class Solution { +public: + bool checkRecord(string s) { + int a = 0, l = 0, n = s.size(), maxl = 0; + for (int i = 0; i < n; ++i) + if (s[i] == 'A' || s[i] == 'a') { + ++a; + l = 0; + } else if (s[i] == 'L' || s[i] == 'l') { + ++l; + maxl = l > maxl ? l : maxl; + } else + l = 0; + return a <= 1 && maxl <= 2; + } +}; diff --git a/cpp/553.OptimalDivision/usingMath.cpp b/cpp/553.OptimalDivision/usingMath.cpp deleted file mode 100644 index 6f45414..0000000 --- a/cpp/553.OptimalDivision/usingMath.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - string optimalDivision(vector& nums) { - string ans; - if(!nums.size()) return ans; - ans = to_string(nums[0]); - if(nums.size()==1) return ans; - if(nums.size()==2) return ans + "/" + to_string(nums[1]); - ans += "/(" + to_string(nums[1]); - for(int i = 2; i < nums.size();++i) - ans += "/" + to_string(nums[i]); - ans += ")"; - return ans; -} -}; diff --git a/cpp/553.cpp b/cpp/553.cpp new file mode 100644 index 0000000..29d1cd2 --- /dev/null +++ b/cpp/553.cpp @@ -0,0 +1,19 @@ +// usingMath.cpp +class Solution { +public: + string optimalDivision(vector &nums) { + string ans; + if (!nums.size()) + return ans; + ans = to_string(nums[0]); + if (nums.size() == 1) + return ans; + if (nums.size() == 2) + return ans + "/" + to_string(nums[1]); + ans += "/(" + to_string(nums[1]); + for (int i = 2; i < nums.size(); ++i) + ans += "/" + to_string(nums[i]); + ans += ")"; + return ans; + } +}; diff --git a/cpp/554.BrickWall/hash.cpp b/cpp/554.BrickWall/hash.cpp deleted file mode 100644 index 3685016..0000000 --- a/cpp/554.BrickWall/hash.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - int leastBricks(vector>& wall) { - unordered_mapmap; - int m=wall.size(),n,sum,max=0; - for(int i=0;imax) - max=it.second; - return m-max; - } -}; diff --git a/cpp/554.cpp b/cpp/554.cpp new file mode 100644 index 0000000..c033a66 --- /dev/null +++ b/cpp/554.cpp @@ -0,0 +1,18 @@ +// hash.cpp +class Solution { +public: + int leastBricks(vector> &wall) { + unordered_map map; + int m = wall.size(), n, sum, max = 0; + for (int i = 0; i < m; ++i) { + n = wall[i].size(); + sum = 0; + for (int j = 0; j < n - 1; ++j) + ++map[sum += wall[i][j]]; + } + for (auto it : map) + if (it.second > max) + max = it.second; + return m - max; + } +}; diff --git a/cpp/557.ReverseWordsInAStringIII/onepass.cpp b/cpp/557.ReverseWordsInAStringIII/onepass.cpp deleted file mode 100644 index 829147b..0000000 --- a/cpp/557.ReverseWordsInAStringIII/onepass.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - string reverseWords(string s) { - int i=0,j=0,n=s.size(); - while(j children; - - Node() {} - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ -class Solution { // Runtime: 136 ms, faster than 98.03% of C++ online submissions for Maximum Depth of N-ary Tree. -public: - int maxDepth(Node* root) { - if (not root) - return 0; - int depth = 0; - for (auto& child : root->children) - depth = max(depth, maxDepth(child)); - return 1 + depth; - } -}; \ No newline at end of file diff --git a/cpp/559.cpp b/cpp/559.cpp new file mode 100644 index 0000000..bd6caa3 --- /dev/null +++ b/cpp/559.cpp @@ -0,0 +1,24 @@ +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +class Solution { // Runtime: 136 ms, faster than 98.03% of C++ online + // submissions for Maximum Depth of N-ary Tree. +public: + int maxDepth(Node *root) { + if (not root) + return 0; + int depth = 0; + for (auto &child : root->children) + depth = max(depth, maxDepth(child)); + return 1 + depth; + } +}; \ No newline at end of file diff --git a/cpp/56.MergeIntervals/iteration-15ms.cpp b/cpp/56.MergeIntervals/iteration-15ms.cpp deleted file mode 100644 index 052b2be..0000000 --- a/cpp/56.MergeIntervals/iteration-15ms.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for an interval. - * struct Interval { - * int start; - * int end; - * Interval() : start(0), end(0) {} - * Interval(int s, int e) : start(s), end(e) {} - * }; - */ -class Solution { -public: - vector merge(vector& intervals) { - sort(intervals.begin(),intervals.end(),[](Interval a,Interval b){return a.startresult; - if(intervals.size()<1)return result; - result.push_back(intervals[0]); - int i=0; - auto j=intervals.begin(); - for(++j;j!=intervals.end();++j){ - if(result[i].end>=(*j).start){ - result[i].end=max((*j).end,result[i].end); - } - else{ - ++i; - result.push_back(*j); - } - } - return result; - } -}; diff --git a/cpp/56.cpp b/cpp/56.cpp new file mode 100644 index 0000000..f2da326 --- /dev/null +++ b/cpp/56.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector> merge(vector>& intervals) { + sort(intervals.begin(), intervals.end(), + [](vector& a, vector& b) { + return a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]); + }); + vector> result = {intervals[0]}; + int i = 0; + auto j = intervals.begin() + 1; + for (; j != intervals.end(); ++j) { + if (result[i][1] >= (*j)[0]) { + result[i][1] = max((*j)[1], result[i][1]); + } else { + ++i; + result.push_back(*j); + } + } + return result; + } +}; \ No newline at end of file diff --git a/cpp/560.SubarraySumEqualsK/hash.cpp b/cpp/560.SubarraySumEqualsK/hash.cpp deleted file mode 100644 index bcf69bd..0000000 --- a/cpp/560.SubarraySumEqualsK/hash.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int subarraySum(vector& nums, int k) { - int number=0,sum=0,n=nums.size(); - unordered_mapmap; - map[0]=1; - for(int i=0;i &nums, int k) { + int number = 0, sum = 0, n = nums.size(); + unordered_map map; + map[0] = 1; + for (int i = 0; i < n; ++i) { + sum += nums[i]; + number += map[sum - k]; + ++map[sum]; + } + return number; + } +}; diff --git a/cpp/561.ArrayPartitionI/sort.cpp b/cpp/561.ArrayPartitionI/sort.cpp deleted file mode 100644 index d3510d3..0000000 --- a/cpp/561.ArrayPartitionI/sort.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - int arrayPairSum(vector& nums) { - sort(nums.begin(),nums.end()); - int sum=0; - for(int i=0;i &nums) { + sort(nums.begin(), nums.end()); + int sum = 0; + for (int i = 0; i < nums.size(); i += 2) + sum += nums[i]; + return sum; + } +}; diff --git a/cpp/563.BinaryTreeTilt/postorder.cpp b/cpp/563.BinaryTreeTilt/postorder.cpp deleted file mode 100644 index af639f0..0000000 --- a/cpp/563.BinaryTreeTilt/postorder.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int sum=0; -public: - int findTilt(TreeNode* root) { - postorder(root); - return sum; - } - int postorder(TreeNode* root) { - if(root==NULL)return 0; - int left=postorder(root->left); - int right=postorder(root->right); - int tilt=abs(left-right); - sum+=tilt; - return left+right+root->val; - } -}; diff --git a/cpp/563.cpp b/cpp/563.cpp new file mode 100644 index 0000000..054bae5 --- /dev/null +++ b/cpp/563.cpp @@ -0,0 +1,28 @@ +// postorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int sum = 0; + +public: + int findTilt(TreeNode *root) { + postorder(root); + return sum; + } + int postorder(TreeNode *root) { + if (root == NULL) + return 0; + int left = postorder(root->left); + int right = postorder(root->right); + int tilt = abs(left - right); + sum += tilt; + return left + right + root->val; + } +}; diff --git a/cpp/565.ArrayNesting/beat96%+O1Space.cpp b/cpp/565.ArrayNesting/beat96%+O1Space.cpp deleted file mode 100644 index be1ef27..0000000 --- a/cpp/565.ArrayNesting/beat96%+O1Space.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int arrayNesting(vector& nums) { - int n=nums.size(),maxlen=0; - for(int i=0;in/2) - return maxlen; - } - return maxlen; - } -}; diff --git a/cpp/565.ArrayNesting/hashset.cpp b/cpp/565.ArrayNesting/hashset.cpp deleted file mode 100644 index 3a4efba..0000000 --- a/cpp/565.ArrayNesting/hashset.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int arrayNesting(vector& nums) { - unordered_sethashset; - int len=0,n=nums.size(),maxlen=0; - for(int i=0;i &nums) { + int n = nums.size(), maxlen = 0; + for (int i = 0; i < n; ++i) { + int value = nums[i], pos = i, len = 0; + while (value != -1) { + nums[pos] = -1; + pos = value; + value = nums[value]; + ++len; + } + maxlen = max(maxlen, len); + if (maxlen > n / 2) + return maxlen; + } + return maxlen; + } +}; +// hashset.cpp +class Solution2 { +public: + int arrayNesting(vector &nums) { + unordered_set hashset; + int len = 0, n = nums.size(), maxlen = 0; + for (int i = 0; i < n; ++i) { + int value = nums[i]; + while (hashset.find(value) == hashset.end()) { + hashset.insert(value); + value = nums[value]; + ++len; + } + maxlen = max(maxlen, len); + len = 0; + } + return maxlen; + } +}; diff --git a/cpp/566.ReshapeTheMatrix/simpleidea.cpp b/cpp/566.ReshapeTheMatrix/simpleidea.cpp deleted file mode 100644 index e2b935f..0000000 --- a/cpp/566.ReshapeTheMatrix/simpleidea.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - vector> matrixReshape(vector>& nums, int r, int c) { - int row=nums.size(); - if(row==0)return nums; - int col=nums[0].size(),k=0; - if(r*c!=row*col)return nums; - vector>reshape(r,vector(c)); - for(int i=0;i> matrixReshape(vector> &nums, int r, int c) { + int row = nums.size(); + if (row == 0) + return nums; + int col = nums[0].size(), k = 0; + if (r * c != row * col) + return nums; + vector> reshape(r, vector(c)); + for (int i = 0; i < r; ++i) + for (int j = 0; j < c; ++j, ++k) + reshape[i][j] = nums[k / col][k % col]; + return reshape; + } +}; diff --git a/cpp/567.PermutationInString/conciseidea.cpp b/cpp/567.PermutationInString/conciseidea.cpp deleted file mode 100644 index f60d292..0000000 --- a/cpp/567.PermutationInString/conciseidea.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { -public: - bool checkInclusion(string s1, string s2) { - int count[26] = {}; - int n1 = s1.size(), n2=s2.size(); - if(n1>n2)return 0; - for (int i = 0; i0) { - s1s[s2[i + off] - 'a']--; - --n; - ++off; - if (n == 0) - return 1; - } - else { - if(off>0){ - s1s[s2[i] - 'a']++; - --off; - ++n; - } - ++i; - } - } - return 0; - } -}; diff --git a/cpp/567.cpp b/cpp/567.cpp new file mode 100644 index 0000000..8f65c10 --- /dev/null +++ b/cpp/567.cpp @@ -0,0 +1,56 @@ +// conciseidea.cpp +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int count[26] = {}; + int n1 = s1.size(), n2 = s2.size(); + if (n1 > n2) + return 0; + for (int i = 0; i < n1; ++i) { + ++count[s1[i] - 'a']; + --count[s2[i] - 'a']; + } + if (allZero(count)) + return 1; + for (int i = n1; i < n2; ++i) { + --count[s2[i] - 'a']; + ++count[s2[i - n1] - 'a']; + if (allZero(count)) + return 1; + } + return 0; + } + bool allZero(int arr[]) { + for (int i = 0; i < 26; ++i) + if (arr[i] != 0) + return 0; + return 1; + } +}; +// uglycode.cpp +class Solution2 { +public: + bool checkInclusion(string s1, string s2) { + int s1s[26] = {}; + int n = s1.size(), off = 0; + for (int i = 0; i < n; ++i) + ++s1s[s1[i] - 'a']; + for (int i = 0; i + off < s2.size();) { + if (s1s[s2[i + off] - 'a'] > 0) { + s1s[s2[i + off] - 'a']--; + --n; + ++off; + if (n == 0) + return 1; + } else { + if (off > 0) { + s1s[s2[i] - 'a']++; + --off; + ++n; + } + ++i; + } + } + return 0; + } +}; diff --git a/cpp/57.InsertInterval/simple.cpp b/cpp/57.InsertInterval/simple.cpp deleted file mode 100644 index b885bbe..0000000 --- a/cpp/57.InsertInterval/simple.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Definition for an interval. - * struct Interval { - * int start; - * int end; - * Interval() : start(0), end(0) {} - * Interval(int s, int e) : start(s), end(e) {} - * }; - */ -class Solution { - void combine(Interval &dst,Interval &src){ - dst.start=min(dst.start,src.start); - dst.end=max(dst.end,src.end); - } -public: - vector insert(vector& intervals, Interval newInterval) { - vectorres; - int i; - for(i=0;i insert(vector &intervals, Interval newInterval) { + vector res; + int i; + for (i = 0; i < intervals.size(); ++i) { + auto &interval = intervals[i]; + if (newInterval.start <= interval.end) + break; + res.push_back(interval); + } + for (; i < intervals.size(); ++i) { + auto &interval = intervals[i]; + if (!(interval.end < newInterval.start) && + !(newInterval.end < interval.start)) + combine(newInterval, interval); + else + break; + } + res.push_back(newInterval); + for (; i < intervals.size(); ++i) { + res.push_back(intervals[i]); + } + return res; + } +}; diff --git a/cpp/572.SubtreeOfAnotherTree/preorder.cpp b/cpp/572.SubtreeOfAnotherTree/preorder.cpp deleted file mode 100644 index cbae484..0000000 --- a/cpp/572.SubtreeOfAnotherTree/preorder.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - bool isSubtree(TreeNode* s, TreeNode* t) { - if(s==NULL)return t==NULL; - if(t==NULL)return false; - bool res=0; - if(s->val==t->val) - res=isSame(s,t); - return res||isSubtree(s->left,t)||isSubtree(s->right,t); - } - bool isSame(TreeNode* s, TreeNode* t){ - if(s==NULL)return t==NULL; - if(t==NULL)return s==NULL; - return s->val==t->val&&isSame(s->left,t->left)&&isSame(s->right,t->right); - } -}; diff --git a/cpp/572.SubtreeOfAnotherTree/preorder2.cpp b/cpp/572.SubtreeOfAnotherTree/preorder2.cpp deleted file mode 100644 index 09e0387..0000000 --- a/cpp/572.SubtreeOfAnotherTree/preorder2.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - bool isSubtree(TreeNode* s, TreeNode* t) { - string ss,tt; - preorder(s,ss); - preorder(t,tt); - return ss.find(tt)!=std::string::npos; - } - void preorder(TreeNode *root,string &s){ - s+=","; - if(root==NULL){ - s+="#"; - return; - } - s+=to_string(root->val); - preorder(root->left,s); - preorder(root->right,s); - } -}; diff --git a/cpp/572.cpp b/cpp/572.cpp new file mode 100644 index 0000000..aba717c --- /dev/null +++ b/cpp/572.cpp @@ -0,0 +1,60 @@ +// preorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + bool isSubtree(TreeNode *s, TreeNode *t) { + if (s == NULL) + return t == NULL; + if (t == NULL) + return false; + bool res = 0; + if (s->val == t->val) + res = isSame(s, t); + return res || isSubtree(s->left, t) || isSubtree(s->right, t); + } + bool isSame(TreeNode *s, TreeNode *t) { + if (s == NULL) + return t == NULL; + if (t == NULL) + return s == NULL; + return s->val == t->val && isSame(s->left, t->left) && + isSame(s->right, t->right); + } +}; +// preorder2.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution2 { +public: + bool isSubtree(TreeNode *s, TreeNode *t) { + string ss, tt; + preorder(s, ss); + preorder(t, tt); + return ss.find(tt) != std::string::npos; + } + void preorder(TreeNode *root, string &s) { + s += ","; + if (root == NULL) { + s += "#"; + return; + } + s += to_string(root->val); + preorder(root->left, s); + preorder(root->right, s); + } +}; diff --git a/cpp/575.DistributeCandies/hashset.cpp b/cpp/575.DistributeCandies/hashset.cpp deleted file mode 100644 index 553de48..0000000 --- a/cpp/575.DistributeCandies/hashset.cpp +++ /dev/null @@ -1,7 +0,0 @@ -class Solution { -public: - int distributeCandies(vector& candies) { - int kinds=unordered_set(candies.begin(),candies.end()).size(),n=candies.size()/2; - return kinds>=n?n:kinds; - } -}; diff --git a/cpp/575.cpp b/cpp/575.cpp new file mode 100644 index 0000000..3b77fdf --- /dev/null +++ b/cpp/575.cpp @@ -0,0 +1,9 @@ +// hashset.cpp +class Solution { +public: + int distributeCandies(vector &candies) { + int kinds = unordered_set(candies.begin(), candies.end()).size(), + n = candies.size() / 2; + return kinds >= n ? n : kinds; + } +}; diff --git a/cpp/58.LengthOfLastWord/onepass-3ms.cpp b/cpp/58.LengthOfLastWord/onepass-3ms.cpp deleted file mode 100644 index 16e1cdf..0000000 --- a/cpp/58.LengthOfLastWord/onepass-3ms.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int lengthOfLastWord(string s) { - int len=0,i=s.size()-1; - while(i>=0&& !((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')))--i; - while(i>=0){ - if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')) - ++len; - else - return len; - --i; - } - return len; - } -}; diff --git a/cpp/58.cpp b/cpp/58.cpp new file mode 100644 index 0000000..d067b80 --- /dev/null +++ b/cpp/58.cpp @@ -0,0 +1,13 @@ +// onepass-3ms.cpp +class Solution { +public: + int lengthOfLastWord(string s) { + int l = 0, r = s.size() - 1; + while (r >= 0 && s[r] == ' ') --r; + while (r >= 0 && s[r] != ' ') { + ++l; + --r; + } + return l; + } +}; diff --git a/cpp/581.ShortestUnsortedContinuousSubarray/O1SpaceOnTimeBeat95.cpp b/cpp/581.ShortestUnsortedContinuousSubarray/O1SpaceOnTimeBeat95.cpp deleted file mode 100644 index becdbd8..0000000 --- a/cpp/581.ShortestUnsortedContinuousSubarray/O1SpaceOnTimeBeat95.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - int findUnsortedSubarray(vector& nums) { - int sum=0,n=nums.size(),i,j; - for(i=0;i=nums[j-1];--j); - if(i--==j++)return 0; - for(int k=i+1;k=0&&nums[k]nums[j]) - ++j; - } - return j-i-1; - } -}; diff --git a/cpp/581.ShortestUnsortedContinuousSubarray/sort.cpp b/cpp/581.ShortestUnsortedContinuousSubarray/sort.cpp deleted file mode 100644 index e929327..0000000 --- a/cpp/581.ShortestUnsortedContinuousSubarray/sort.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int findUnsortedSubarray(vector& nums) { - vectorres(nums.begin(),nums.end()); - sort(res.begin(),res.end()); - int sum=0,n=nums.size(),i,j; - for(i=0;i& nums) { - stackst1,st2; - int sum=0,n=nums.size(),i,j; - for(i=0;i=nums[j-1];--j)st2.push(nums[j]); - if(i==j)return 0; - for(int k=i;k<=j;++k){ - while(!st1.empty()&&nums[k]st2.top()) - st2.pop(); - } - return n-st1.size()-st2.size(); - } -}; diff --git a/cpp/581.cpp b/cpp/581.cpp new file mode 100644 index 0000000..9b2df67 --- /dev/null +++ b/cpp/581.cpp @@ -0,0 +1,55 @@ +// O1SpaceOnTimeBeat95.cpp +class Solution { +public: + int findUnsortedSubarray(vector &nums) { + int sum = 0, n = nums.size(), i, j; + for (i = 0; i < n - 1 && nums[i] <= nums[i + 1]; ++i) + ; + for (j = n - 1; i < j && nums[j] >= nums[j - 1]; --j) + ; + if (i-- == j++) + return 0; + for (int k = i + 1; k < j; ++k) { + while (i >= 0 && nums[k] < nums[i]) + --i; + while (j < n && nums[k] > nums[j]) + ++j; + } + return j - i - 1; + } +}; +// sort.cpp +class Solution2 { +public: + int findUnsortedSubarray(vector &nums) { + vector res(nums.begin(), nums.end()); + sort(res.begin(), res.end()); + int sum = 0, n = nums.size(), i, j; + for (i = 0; i < n && nums[i] == res[i]; ++i, ++sum) + ; + for (j = n - 1; i < j && nums[j] == res[j]; --j, ++sum) + ; + return n - sum; + } +}; +// stack.cpp +class Solution3 { +public: + int findUnsortedSubarray(vector &nums) { + stack st1, st2; + int sum = 0, n = nums.size(), i, j; + for (i = 0; i < n - 1 && nums[i] <= nums[i + 1]; ++i) + st1.push(nums[i]); + for (j = n - 1; i < j && nums[j] >= nums[j - 1]; --j) + st2.push(nums[j]); + if (i == j) + return 0; + for (int k = i; k <= j; ++k) { + while (!st1.empty() && nums[k] < st1.top()) + st1.pop(); + while (!st2.empty() && nums[k] > st2.top()) + st2.pop(); + } + return n - st1.size() - st2.size(); + } +}; diff --git a/cpp/583.DeleteOperationForTwoStrings/dp.cpp b/cpp/583.DeleteOperationForTwoStrings/dp.cpp deleted file mode 100644 index a59aca5..0000000 --- a/cpp/583.DeleteOperationForTwoStrings/dp.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int minDistance(string word1, string word2) { - int m=word1.size(),n=word2.size(); - vector>dp(m+1,vector(n+1,0)); - for(int i=0;i> dp(m + 1, vector(n + 1, 0)); + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + dp[i + 1][j + 1] = word1[i] == word2[j] + ? dp[i][j] + 1 + : max(dp[i][j + 1], dp[i + 1][j]); + return m + n - 2 * dp[m][n]; + } +}; diff --git a/cpp/589.N-aryTreePreorderTraversal/recursion.cpp b/cpp/589.N-aryTreePreorderTraversal/recursion.cpp deleted file mode 100644 index f4c42e4..0000000 --- a/cpp/589.N-aryTreePreorderTraversal/recursion.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ -class Solution { - void preOrderVisit(vector&res,Node *root){ - if(!root) - return; - res.push_back(root->val); - for(auto &node:root->children) - preOrderVisit(res,node); - } -public: - vector preorder(Node* root) { - vectorres; - preOrderVisit(res,root); - return res; - } -}; diff --git a/cpp/589.cpp b/cpp/589.cpp new file mode 100644 index 0000000..ecc48d8 --- /dev/null +++ b/cpp/589.cpp @@ -0,0 +1,29 @@ +// recursion.cpp +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +class Solution { + void preOrderVisit(vector &res, Node *root) { + if (!root) + return; + res.push_back(root->val); + for (auto &node : root->children) + preOrderVisit(res, node); + } + +public: + vector preorder(Node *root) { + vector res; + preOrderVisit(res, root); + return res; + } +}; diff --git a/cpp/59.SpiralMatrixII/iteration-6ms.cpp b/cpp/59.SpiralMatrixII/iteration-6ms.cpp deleted file mode 100644 index 282884b..0000000 --- a/cpp/59.SpiralMatrixII/iteration-6ms.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution { -public: - vector> generateMatrix(int n) { - vector>result(n,vector(n,0)); - if(n<1)return result; - result[0][0]=1; - int x=1,y=0,towards=0,count=0,i=0,j=0,current=2; - while(count!=4){ - if(j+x=0 &&i+y=0 && result[i+y][j+x]==0){ - j+=x; - i+=y; - result[i][j]=current++; - count=0; - } - else{ - ++count; - changeDirt(x,y,towards); - } - } - return result; - } - void changeDirt(int &x,int &y,int &towards){ - towards=(towards+1)%4; - switch(towards){ - case 0:x=1;y=0;break; - case 1:x=0;y=1;break; - case 2:x=-1;y=0;break; - case 3:x=0;y=-1;break; - } - } -}; diff --git a/cpp/59.cpp b/cpp/59.cpp new file mode 100644 index 0000000..0e5d366 --- /dev/null +++ b/cpp/59.cpp @@ -0,0 +1,41 @@ +class Solution { + void changeDirt(int& x, int& y, int& towards) { + towards = (towards + 1) % 4; + switch (towards) { + case 0: + x = 1; + y = 0; + break; + case 1: + x = 0; + y = 1; + break; + case 2: + x = -1; + y = 0; + break; + case 3: + x = 0; + y = -1; + break; + } + } + +public: + vector> generateMatrix(int n) { + vector> result(n, vector(n, 0)); + result[0][0] = 1; + int x = 1, y = 0, towards = 0, i = 0, j = 0, current = 2; + while (current <= n * n) { + if (j + x < n && j + x >= 0 && i + y < n && i + y >= 0 && + result[i + y][j + x] == 0) { + j += x; + i += y; + result[i][j] = current++; + } else { + changeDirt(x, y, towards); + } + } + return result; + } +}; diff --git a/cpp/590.N-aryTreePostorderTraversal/recursion.cpp b/cpp/590.N-aryTreePostorderTraversal/recursion.cpp deleted file mode 100644 index 5e87f35..0000000 --- a/cpp/590.N-aryTreePostorderTraversal/recursion.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ -class Solution { - void postOrderVisit(vector&res,Node *root){ - if(!root) - return; - for(auto &node:root->children){ - postOrderVisit(res,node); - } - res.push_back(root->val); - - } -public: - vector postorder(Node* root) { - vectorres; - postOrderVisit(res,root); - return res; - } -}; diff --git a/cpp/590.cpp b/cpp/590.cpp new file mode 100644 index 0000000..0b100d0 --- /dev/null +++ b/cpp/590.cpp @@ -0,0 +1,30 @@ +// recursion.cpp +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +class Solution { + void postOrderVisit(vector &res, Node *root) { + if (!root) + return; + for (auto &node : root->children) { + postOrderVisit(res, node); + } + res.push_back(root->val); + } + +public: + vector postorder(Node *root) { + vector res; + postOrderVisit(res, root); + return res; + } +}; diff --git a/cpp/592.FractionAdditionAndSubtraction.cpp/gcd+lcm.cpp b/cpp/592.FractionAdditionAndSubtraction.cpp/gcd+lcm.cpp deleted file mode 100644 index a3e7023..0000000 --- a/cpp/592.FractionAdditionAndSubtraction.cpp/gcd+lcm.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution { -public: - string fractionAddition(string expression) { - stringstream ss(expression); - int a,b,suma=0,sumb=1; - char ch; - while(ss>>a>>ch>>b){ - int _lcm=lcm(b,sumb); - suma*=_lcm/sumb; - sumb=_lcm; - a*=_lcm/b; - suma+=a; - int _gcd=gcd(suma,sumb); - suma/=_gcd; - sumb/=_gcd; - } - if(suma*sumb<0) - return "-"+to_string(abs(suma))+"/"+to_string(abs(sumb)); - return to_string(abs(suma))+"/"+to_string(abs(sumb)); - } - int gcd(int a, int b) { - if(a < b) - return gcd(b,a); - int temp; - while(b != 0){ - temp = a % b; - a = b; - b = temp; - } - return a; - } - int lcm(int a, int b) { - return a * b / gcd(a, b); - } -}; diff --git a/cpp/592.cpp b/cpp/592.cpp new file mode 100644 index 0000000..de85bc0 --- /dev/null +++ b/cpp/592.cpp @@ -0,0 +1,34 @@ +// gcd+lcm.cpp +class Solution { +public: + string fractionAddition(string expression) { + stringstream ss(expression); + int a, b, suma = 0, sumb = 1; + char ch; + while (ss >> a >> ch >> b) { + int _lcm = lcm(b, sumb); + suma *= _lcm / sumb; + sumb = _lcm; + a *= _lcm / b; + suma += a; + int _gcd = gcd(suma, sumb); + suma /= _gcd; + sumb /= _gcd; + } + if (suma * sumb < 0) + return "-" + to_string(abs(suma)) + "/" + to_string(abs(sumb)); + return to_string(abs(suma)) + "/" + to_string(abs(sumb)); + } + int gcd(int a, int b) { + if (a < b) + return gcd(b, a); + int temp; + while (b != 0) { + temp = a % b; + a = b; + b = temp; + } + return a; + } + int lcm(int a, int b) { return a * b / gcd(a, b); } +}; diff --git a/cpp/593.ValidSquare.cpp b/cpp/593.ValidSquare.cpp deleted file mode 100644 index 4478ad5..0000000 --- a/cpp/593.ValidSquare.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 88.89% of C++ online submissions for Valid Square. -//Memory Usage: 8.4 MB, less than 65.97% of C++ online submissions for Valid Square. -public: - bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { - auto d=[](vector& p1, vector& p2) { - return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); - }; - unordered_set s({ d(p1, p2), d(p1, p3), d(p1, p4), d(p2, p3), d(p2, p4), d(p3, p4) }); - return !s.count(0) && s.size() == 2; - } -}; \ No newline at end of file diff --git a/cpp/593.cpp b/cpp/593.cpp new file mode 100644 index 0000000..0c6d581 --- /dev/null +++ b/cpp/593.cpp @@ -0,0 +1,16 @@ +class Solution { + // Runtime: 4 ms, faster than 88.89% of C++ online submissions for Valid + // Square. Memory Usage: 8.4 MB, less than 65.97% of C++ online submissions + // for Valid Square. +public: + bool validSquare(vector &p1, vector &p2, vector &p3, + vector &p4) { + auto d = [](vector &p1, vector &p2) { + return (p1[0] - p2[0]) * (p1[0] - p2[0]) + + (p1[1] - p2[1]) * (p1[1] - p2[1]); + }; + unordered_set s( + {d(p1, p2), d(p1, p3), d(p1, p4), d(p2, p3), d(p2, p4), d(p3, p4)}); + return !s.count(0) && s.size() == 2; + } +}; \ No newline at end of file diff --git a/cpp/594.LongestHarmoniousSubsequence/hash.cpp b/cpp/594.LongestHarmoniousSubsequence/hash.cpp deleted file mode 100644 index ffb93a7..0000000 --- a/cpp/594.LongestHarmoniousSubsequence/hash.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int findLHS(vector& nums) { - unordered_mapmap; - for(int i=0;ifirst+1); - if(it2!=map.end()) - res=max(it->second+it2->second,res); - it2=map.find(it->first-1); - if(it2!=map.end()) - res=max(it->second+it2->second,res); - } - return res; - } -}; diff --git a/cpp/594.cpp b/cpp/594.cpp new file mode 100644 index 0000000..4cc694d --- /dev/null +++ b/cpp/594.cpp @@ -0,0 +1,19 @@ +// hash.cpp +class Solution { +public: + int findLHS(vector &nums) { + unordered_map map; + for (int i = 0; i < nums.size(); ++i) + map[nums[i]]++; + int res = 0; + for (auto it = map.begin(); it != map.end(); ++it) { + auto it2 = map.find(it->first + 1); + if (it2 != map.end()) + res = max(it->second + it2->second, res); + it2 = map.find(it->first - 1); + if (it2 != map.end()) + res = max(it->second + it2->second, res); + } + return res; + } +}; diff --git a/cpp/598.RangeAdditionII/simple.cpp b/cpp/598.RangeAdditionII/simple.cpp deleted file mode 100644 index bfb6f33..0000000 --- a/cpp/598.RangeAdditionII/simple.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int maxCount(int m, int n, vector>& ops) { - if(ops.size()==0)return m*n; - int a=0x7fffffff,b=0x7fffffff; - for(auto nums:ops){ - a=min(nums[0],a); - b=min(nums[1],b); - } - return a*b; - } -}; diff --git a/cpp/598.cpp b/cpp/598.cpp new file mode 100644 index 0000000..5cf16f2 --- /dev/null +++ b/cpp/598.cpp @@ -0,0 +1,14 @@ +// simple.cpp +class Solution { +public: + int maxCount(int m, int n, vector> &ops) { + if (ops.size() == 0) + return m * n; + int a = 0x7fffffff, b = 0x7fffffff; + for (auto nums : ops) { + a = min(nums[0], a); + b = min(nums[1], b); + } + return a * b; + } +}; diff --git a/cpp/599.MinimumIndexSumofTwoLists/hashmap.cpp b/cpp/599.MinimumIndexSumofTwoLists/hashmap.cpp deleted file mode 100644 index 9d0f386..0000000 --- a/cpp/599.MinimumIndexSumofTwoLists/hashmap.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - vector findRestaurant(vector& list1, vector& list2) { - unordered_mapmap; - vectorres; - for(int i=0;isecond+i; - if(sum==m) - res.push_back(list2[i]); - else if(sum findRestaurant(vector &list1, vector &list2) { + unordered_map map; + vector res; + for (int i = 0; i < list1.size(); ++i) + map[list1[i]] = i; + int n = list2.size(), m = 0x7fffffff; + for (int i = 0; i < n; ++i) { + auto it = map.find(list2[i]); + if (it != map.end()) { + int sum = it->second + i; + if (sum == m) + res.push_back(list2[i]); + else if (sum < m) { + res.assign(1, list2[i]); + m = sum; + } + } + } + return res; + } +}; diff --git a/cpp/6.ZigzagConversion/simple.cpp b/cpp/6.ZigzagConversion/simple.cpp deleted file mode 100644 index d59c530..0000000 --- a/cpp/6.ZigzagConversion/simple.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - string convert(string s, int numRows) { - if(numRows<=1) - return s; - string res; - string *arr=new string[numRows]; - for(int i=0,j=0,sign=1;i(numRows); + for (int i = 0, j = 0, direct = 1; j < s.size(); i += direct) { + strings[i] += s[j++]; + if (i == 0) + direct = 1; + else if (i == numRows - 1) + direct = -1; + } + return accumulate(strings.begin(), strings.end(), string()); + } +}; \ No newline at end of file diff --git a/cpp/60.PermutationSequence/timeOnk.cpp b/cpp/60.PermutationSequence/timeOnk.cpp deleted file mode 100644 index 75c4da8..0000000 --- a/cpp/60.PermutationSequence/timeOnk.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - string getPermutation(int n, int k) { - string str=""; - for(int i=1;i<=n;++i) - str+=char(i+'0'); - for(int i=1;i0&&nums[j]<=nums[j-1])--j; - if(j-1>=0){ - int minIndex=j; - for(int k=j+1;knums[j-1]) - minIndex=nums[j] 0 && nums[j] <= nums[j - 1]) + --j; + if (j - 1 >= 0) { + int minIndex = j; + for (int k = j + 1; k < n; ++k) + if (nums[k] > nums[j - 1]) + minIndex = nums[j] < nums[k] ? j : k; + swap(nums[j - 1], nums[minIndex]); + sort(nums.begin() + j, nums.end()); + } else + sort(nums.begin(), nums.end()); + } +}; diff --git a/cpp/604.DesignCompressedStringIterator/simple.cpp b/cpp/604.DesignCompressedStringIterator/simple.cpp deleted file mode 100644 index e17117d..0000000 --- a/cpp/604.DesignCompressedStringIterator/simple.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class StringIterator { - vector>res; - int off; -public: - StringIterator(string compressedString) { - stringstream ss(compressedString); - char ch; - int val; - while(!ss.eof()){ - ss>>ch; - ss>>val; - res.push_back(pair(ch,val)); - } - off=0; - } - - char next() { - if(off> res; + int off; + +public: + StringIterator(string compressedString) { + stringstream ss(compressedString); + char ch; + int val; + while (!ss.eof()) { + ss >> ch; + ss >> val; + res.push_back(pair(ch, val)); + } + off = 0; + } + + char next() { + if (off < res.size()) { + char ch = res[off].first; + off += (--res[off].second == 0); + return ch; + } + return ' '; + } + + bool hasNext() { return off < res.size(); } +}; + +/** + * Your StringIterator object will be instantiated and called as such: + * StringIterator obj = new StringIterator(compressedString); + * char param_1 = obj.next(); + * bool param_2 = obj.hasNext(); + */ diff --git a/cpp/605.CanPlaceFlowers/greedy.cpp b/cpp/605.CanPlaceFlowers/greedy.cpp deleted file mode 100644 index f0e6e81..0000000 --- a/cpp/605.CanPlaceFlowers/greedy.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - bool canPlaceFlowers(vector& flowerbed, int n) { - int size=flowerbed.size(); - for(int i=0;i0;++i) - if(flowerbed[i]==0&&(i==size-1||flowerbed[i+1]==0)&&(i==0||flowerbed[i-1]==0)){ - --n; - flowerbed[i]=1; - } - return n==0; - } -}; diff --git a/cpp/605.cpp b/cpp/605.cpp new file mode 100644 index 0000000..31bb80f --- /dev/null +++ b/cpp/605.cpp @@ -0,0 +1,14 @@ +// greedy.cpp +class Solution { +public: + bool canPlaceFlowers(vector &flowerbed, int n) { + int size = flowerbed.size(); + for (int i = 0; i < size && n > 0; ++i) + if (flowerbed[i] == 0 && (i == size - 1 || flowerbed[i + 1] == 0) && + (i == 0 || flowerbed[i - 1] == 0)) { + --n; + flowerbed[i] = 1; + } + return n == 0; + } +}; diff --git a/cpp/606.ConstructStringFromBinaryTree/preorder.cpp b/cpp/606.ConstructStringFromBinaryTree/preorder.cpp deleted file mode 100644 index 892b769..0000000 --- a/cpp/606.ConstructStringFromBinaryTree/preorder.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - string tree2str(TreeNode* t) { - if(t==NULL) - return ""; - string s=to_string(t->val); - if(t->left||t->right){ - s+="("+tree2str(t->left)+")"; - if(t->right) - s+="("+tree2str(t->right)+")"; - } - return s; - } -}; diff --git a/cpp/606.cpp b/cpp/606.cpp new file mode 100644 index 0000000..f685216 --- /dev/null +++ b/cpp/606.cpp @@ -0,0 +1,24 @@ +// preorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + string tree2str(TreeNode *t) { + if (t == NULL) + return ""; + string s = to_string(t->val); + if (t->left || t->right) { + s += "(" + tree2str(t->left) + ")"; + if (t->right) + s += "(" + tree2str(t->right) + ")"; + } + return s; + } +}; diff --git a/cpp/609.FindDuplicateFileInSystem/hash+bettersort+102ms.cpp b/cpp/609.FindDuplicateFileInSystem/hash+bettersort+102ms.cpp deleted file mode 100644 index e806290..0000000 --- a/cpp/609.FindDuplicateFileInSystem/hash+bettersort+102ms.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution { -public: - vector> findDuplicate(vector& paths) { - unordered_maphashmap; - stringstream ss; - string path,filename,content; - vector> res; - for(string str:paths){ - ss<>path; - while(!ss.eof()){ - ss>>filename; - int left=filename.find("("),right=filename.find(")"); - content=filename.substr(left,right-left); - //filename=filename.substr(0,left); - if(hashmap.find(content)==hashmap.end()){ - hashmap[content]=res.size(); - res.push_back(vector(1,path+"/"+filename.substr(0,left))); - } - else - res[hashmap[content]].emplace_back(path+"/"+filename.substr(0,left)); - } - ss.clear(); - } - int i=0,j=res.size()-1; - while(i<=j){ - while(i<=j&&res[i].size()!=1)++i; - while(i<=j&&res[j].size()==1)--j; - if(i<=j)res[i++]=res[j--]; - } - res.resize(j+1); - return res; - } -}; diff --git a/cpp/609.FindDuplicateFileInSystem/hash+sort+96ms.cpp b/cpp/609.FindDuplicateFileInSystem/hash+sort+96ms.cpp deleted file mode 100644 index 493d42a..0000000 --- a/cpp/609.FindDuplicateFileInSystem/hash+sort+96ms.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { -public: - vector> findDuplicate(vector& paths) { - unordered_maphashmap; - stringstream ss; - string path,filename,content; - vector> res; - for(string str:paths){ - ss<>path; - while(!ss.eof()){ - ss>>filename; - int left=filename.find("("),right=filename.find(")"); - content=filename.substr(left,right-left); - filename=filename.substr(0,left); - if(hashmap.find(content)==hashmap.end()){ - hashmap[content]=res.size(); - res.push_back(vector(1,path+"/"+filename)); - } - else - res[hashmap[content]].emplace_back(path+"/"+filename); - } - ss.clear(); - } - sort(res.begin(),res.end(),[](vector&a,vector&b){return a.size()>b.size();}); - int i; - for(i=res.size()-1;i>=0&&res[i].size()==1;--i); - if(i>=-1) - res.resize(i+1); - return res; - } -}; diff --git a/cpp/609.cpp b/cpp/609.cpp new file mode 100644 index 0000000..7b954eb --- /dev/null +++ b/cpp/609.cpp @@ -0,0 +1,74 @@ +// hash+bettersort+102ms.cpp +class Solution { +public: + vector> findDuplicate(vector &paths) { + unordered_map hashmap; + stringstream ss; + string path, filename, content; + vector> res; + for (string str : paths) { + ss << str; + ss >> path; + while (!ss.eof()) { + ss >> filename; + int left = filename.find("("), right = filename.find(")"); + content = filename.substr(left, right - left); + // filename=filename.substr(0,left); + if (hashmap.find(content) == hashmap.end()) { + hashmap[content] = res.size(); + res.push_back( + vector(1, path + "/" + filename.substr(0, left))); + } else + res[hashmap[content]].emplace_back(path + "/" + + filename.substr(0, left)); + } + ss.clear(); + } + int i = 0, j = res.size() - 1; + while (i <= j) { + while (i <= j && res[i].size() != 1) + ++i; + while (i <= j && res[j].size() == 1) + --j; + if (i <= j) + res[i++] = res[j--]; + } + res.resize(j + 1); + return res; + } +}; +// hash+sort+96ms.cpp +class Solution2 { +public: + vector> findDuplicate(vector &paths) { + unordered_map hashmap; + stringstream ss; + string path, filename, content; + vector> res; + for (string str : paths) { + ss << str; + ss >> path; + while (!ss.eof()) { + ss >> filename; + int left = filename.find("("), right = filename.find(")"); + content = filename.substr(left, right - left); + filename = filename.substr(0, left); + if (hashmap.find(content) == hashmap.end()) { + hashmap[content] = res.size(); + res.push_back(vector(1, path + "/" + filename)); + } else + res[hashmap[content]].emplace_back(path + "/" + filename); + } + ss.clear(); + } + sort(res.begin(), res.end(), [](vector &a, vector &b) { + return a.size() > b.size(); + }); + int i; + for (i = res.size() - 1; i >= 0 && res[i].size() == 1; --i) + ; + if (i >= -1) + res.resize(i + 1); + return res; + } +}; diff --git a/cpp/61.RotateList/solution.cpp b/cpp/61.RotateList/solution.cpp deleted file mode 100644 index 81f67a9..0000000 --- a/cpp/61.RotateList/solution.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* rotateRight(ListNode* head, int k) { - if(head==NULL||head->next==NULL)return head; - ListNode*p=head,*tail; - int len=0; - while(p!=NULL){ - len++; - p=p->next; - } - p=head; - for(int i=0;inext; - tail=p; - k%=len; - if(k==0)return head; - p=head; - for(int i=0;inext; - ListNode*newhead=p->next; - tail->next=head; - p->next=NULL; - return newhead; - } -}; diff --git a/cpp/61.cpp b/cpp/61.cpp new file mode 100644 index 0000000..ed46a07 --- /dev/null +++ b/cpp/61.cpp @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* rotateRight(ListNode* head, int k) { + if (head == nullptr || head->next == nullptr) + return head; + ListNode h(0, head), *tail = &h; + int len = 0; + for (; tail->next; tail = tail->next) { + len++; + } + k %= len; + if (k == 0) + return head; + auto p = &h; + for (int i = 0; i < len - k; i++) + p = p->next; + ListNode* newhead = p->next; + tail->next = head; + p->next = nullptr; + return newhead; + } +}; diff --git a/cpp/617.MergeTwoBinaryTree/recursion.cpp b/cpp/617.MergeTwoBinaryTree/recursion.cpp deleted file mode 100644 index cac68cd..0000000 --- a/cpp/617.MergeTwoBinaryTree/recursion.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { - if(t1==NULL&&t2==NULL) - return NULL; - int val=(t1?t1->val:0)+(t2?t2->val:0); - TreeNode *p=new TreeNode(val); - p->left=mergeTrees(t1?t1->left:NULL,t2?t2->left:NULL); - p->right=mergeTrees(t1?t1->right:NULL,t2?t2->right:NULL); - return p; - } -}; diff --git a/cpp/617.cpp b/cpp/617.cpp new file mode 100644 index 0000000..3566870 --- /dev/null +++ b/cpp/617.cpp @@ -0,0 +1,22 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) { + if (t1 == NULL && t2 == NULL) + return NULL; + int val = (t1 ? t1->val : 0) + (t2 ? t2->val : 0); + TreeNode *p = new TreeNode(val); + p->left = mergeTrees(t1 ? t1->left : NULL, t2 ? t2->left : NULL); + p->right = mergeTrees(t1 ? t1->right : NULL, t2 ? t2->right : NULL); + return p; + } +}; diff --git a/cpp/62.UniquePaths/dp-0ms.cpp b/cpp/62.UniquePaths/dp-0ms.cpp deleted file mode 100644 index 6258774..0000000 --- a/cpp/62.UniquePaths/dp-0ms.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int uniquePaths(int m, int n) { - if(m==1||n==1)return 1; - vector>dp(m,vector(n,1)); - for(int i=1;i> dp(m, vector(n, 1)); + for (int i = 1; i < m; ++i) + for (int j = 1; j < n; ++j) + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + return dp[m - 1][n - 1]; + } +}; +// math +class Solution2 { +public: + int uniquePaths(int m, int n) { + if (n > m) + return uniquePaths(n, m); + --m, --n; + double ret = 1.0; + for (int i = m + 1; i <= m + n; ++i) + ret *= i; + for (int i = 2; i <= n; ++i) + ret /= i; + return ret; + } +}; \ No newline at end of file diff --git a/cpp/621.TaskScheduler.cpp b/cpp/621.TaskScheduler.cpp deleted file mode 100644 index 71a04f6..0000000 --- a/cpp/621.TaskScheduler.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -//Runtime: 124 ms, faster than 27.62% of C++ online submissions for Task Scheduler. -//Memory Usage: 19 MB, less than 20.41% of C++ online submissions for Task Scheduler. -public: - int leastInterval(vector& tasks, int n) { - int counter[26] = {}; - for (char task : tasks) - counter[task - 'A']++; - priority_queue pq; - for (int i = 0; i < 26; i++) - if (counter[i]) - pq.push(counter[i]); - int time = 0; - while (pq.size()) { - vector remaining; - int all = n + 1; - while (all and pq.size()) { - int counts = pq.top(); - pq.pop(); - if (--counts) - remaining.push_back(counts); - time++; - all--; - } - for (int counts : remaining) - pq.push(counts); - if (pq.empty()) - break; - time += all; - } - return time; - } -}; \ No newline at end of file diff --git a/cpp/621.cpp b/cpp/621.cpp new file mode 100644 index 0000000..905ae2c --- /dev/null +++ b/cpp/621.cpp @@ -0,0 +1,34 @@ +class Solution { + // Runtime: 124 ms, faster than 27.62% of C++ online submissions for Task + // Scheduler. Memory Usage: 19 MB, less than 20.41% of C++ online submissions + // for Task Scheduler. +public: + int leastInterval(vector &tasks, int n) { + int counter[26] = {}; + for (char task : tasks) + counter[task - 'A']++; + priority_queue pq; + for (int i = 0; i < 26; i++) + if (counter[i]) + pq.push(counter[i]); + int time = 0; + while (pq.size()) { + vector remaining; + int all = n + 1; + while (all and pq.size()) { + int counts = pq.top(); + pq.pop(); + if (--counts) + remaining.push_back(counts); + time++; + all--; + } + for (int counts : remaining) + pq.push(counts); + if (pq.empty()) + break; + time += all; + } + return time; + } +}; \ No newline at end of file diff --git a/cpp/623.AddOneRowToTree/dfs.cpp b/cpp/623.AddOneRowToTree/dfs.cpp deleted file mode 100644 index 2105326..0000000 --- a/cpp/623.AddOneRowToTree/dfs.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int v,d; - void dfs(TreeNode*root,int level){ - if(root==nullptr) - return; - if(level==d){ - TreeNode *node=new TreeNode(v); - node->left=root->left; - root->left=node; - node=new TreeNode(v); - node->right=root->right; - root->right=node; - return; - } - dfs(root->left,level+1); - dfs(root->right,level+1); - } -public: - TreeNode* addOneRow(TreeNode* root, int v, int d) { - this->v=v; - this->d=d; - if(d==1){ - TreeNode* node=new TreeNode(v); - node->left=root; - return node; - } - dfs(root,2); - return root; - } -}; diff --git a/cpp/623.cpp b/cpp/623.cpp new file mode 100644 index 0000000..4eb419b --- /dev/null +++ b/cpp/623.cpp @@ -0,0 +1,41 @@ +// dfs.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int v, d; + void dfs(TreeNode *root, int level) { + if (root == nullptr) + return; + if (level == d) { + TreeNode *node = new TreeNode(v); + node->left = root->left; + root->left = node; + node = new TreeNode(v); + node->right = root->right; + root->right = node; + return; + } + dfs(root->left, level + 1); + dfs(root->right, level + 1); + } + +public: + TreeNode *addOneRow(TreeNode *root, int v, int d) { + this->v = v; + this->d = d; + if (d == 1) { + TreeNode *node = new TreeNode(v); + node->left = root; + return node; + } + dfs(root, 2); + return root; + } +}; diff --git a/cpp/628.MaximunProductOfThreeNumbers/SingleScan.cpp b/cpp/628.MaximunProductOfThreeNumbers/SingleScan.cpp deleted file mode 100644 index 099b1ac..0000000 --- a/cpp/628.MaximunProductOfThreeNumbers/SingleScan.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { -public: - int maximumProduct(vector& nums) { - int min1 = INT_MAX, min2 = INT_MAX; - int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; - for (int n: nums) { - if (n <= min1) { - min2 = min1; - min1 = n; - } else if (n <= min2) { // n lies between min1 and min2 - min2 = n; - } - if (n >= max1) { // n is greater than max1, max2 and max3 - max3 = max2; - max2 = max1; - max1 = n; - } else if (n >= max2) { // n lies betweeen max1 and max2 - max3 = max2; - max2 = n; - } else if (n >= max3) { // n lies betwen max2 and max3 - max3 = n; - } - } - return max(min1 * min2 * max1, max1 * max2 * max3); - } -}; diff --git a/cpp/628.MaximunProductOfThreeNumbers/sort.cpp b/cpp/628.MaximunProductOfThreeNumbers/sort.cpp deleted file mode 100644 index ca11895..0000000 --- a/cpp/628.MaximunProductOfThreeNumbers/sort.cpp +++ /dev/null @@ -1,8 +0,0 @@ -class Solution { -public: - int maximumProduct(vector& nums) { - sort(nums.begin(),nums.end()); - int n=nums.size()-1; - return max(nums[n]*nums[n-1]*nums[n-2],nums[0]*nums[1]*nums[n]); - } -}; diff --git a/cpp/628.cpp b/cpp/628.cpp new file mode 100644 index 0000000..53f3c04 --- /dev/null +++ b/cpp/628.cpp @@ -0,0 +1,37 @@ +// SingleScan.cpp +class Solution { +public: + int maximumProduct(vector &nums) { + int min1 = INT_MAX, min2 = INT_MAX; + int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; + for (int n : nums) { + if (n <= min1) { + min2 = min1; + min1 = n; + } else if (n <= min2) { // n lies between min1 and min2 + min2 = n; + } + if (n >= max1) { // n is greater than max1, max2 and max3 + max3 = max2; + max2 = max1; + max1 = n; + } else if (n >= max2) { // n lies betweeen max1 and max2 + max3 = max2; + max2 = n; + } else if (n >= max3) { // n lies betwen max2 and max3 + max3 = n; + } + } + return max(min1 * min2 * max1, max1 * max2 * max3); + } +}; +// sort.cpp +class Solution2 { +public: + int maximumProduct(vector &nums) { + sort(nums.begin(), nums.end()); + int n = nums.size() - 1; + return max(nums[n] * nums[n - 1] * nums[n - 2], + nums[0] * nums[1] * nums[n]); + } +}; diff --git a/cpp/63.UniquePathsII/dp.cpp b/cpp/63.UniquePathsII/dp.cpp deleted file mode 100644 index 14124db..0000000 --- a/cpp/63.UniquePathsII/dp.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int uniquePathsWithObstacles(vector>& obstacleGrid) { - int row=obstacleGrid.size(); - if(row==0)return 0; - int col=obstacleGrid[0].size(); - if(col==0)return 1; - vector>res(row,vector(col,0)); - res[0][0]=!obstacleGrid[0][0]; - for(int i=0;i0?res[i-1][j]:0; - res[i][j]+=j>0?res[i][j-1]:0; - } - return res[row-1][col-1]; - } -}; diff --git a/cpp/63.cpp b/cpp/63.cpp new file mode 100644 index 0000000..43a8deb --- /dev/null +++ b/cpp/63.cpp @@ -0,0 +1,21 @@ +// dp.cpp +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + int row = obstacleGrid.size(); + if (row == 0) + return 0; + int col = obstacleGrid[0].size(); + if (col == 0) + return 1; + vector> res(row, vector(col, 0)); + res[0][0] = !obstacleGrid[0][0]; + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + if (obstacleGrid[i][j] != 1) { + res[i][j] += i > 0 ? res[i - 1][j] : 0; + res[i][j] += j > 0 ? res[i][j - 1] : 0; + } + return res[row - 1][col - 1]; + } +}; diff --git a/cpp/633.SumOfSquareNumbers/binarySearch.cpp b/cpp/633.SumOfSquareNumbers/binarySearch.cpp deleted file mode 100644 index c542b52..0000000 --- a/cpp/633.SumOfSquareNumbers/binarySearch.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - bool judgeSquareSum(int c) { - for(long long int i=0;i*i<=c;++i){ - long long int res=c-i*i; - if(helper(0,res,res)) - return true; - } - return false; - } - bool helper(int left,int right,int num){ - while(left<=right){ - long long int mid=left+(right-left)/2; - if(mid*mid==num) - return true; - else if(mid*mid exclusiveTime(int n, vector& logs) { - vectorres(n,0); - int lastTime=0,lastId=0; - vectorst(1,0); - for(auto &str:logs){ - int first=str.find(':'),second=str.rfind(':'); - int id=stoi(str.substr(0,first)); - bool end=second-first==4;//sizeof(":end:")-1; - int timestamp=stoi(str.substr(second+1)); - if(end){ - res[id]+=timestamp-lastTime+1; - lastTime=timestamp+1; - st.pop_back(); - } - else{ - res[st.back()]+=timestamp-lastTime; - lastTime=timestamp; - st.push_back(id); - } - } - return res; - } -}; diff --git a/cpp/636.cpp b/cpp/636.cpp new file mode 100644 index 0000000..fa505dc --- /dev/null +++ b/cpp/636.cpp @@ -0,0 +1,25 @@ +// singleScan-iteration.cpp +class Solution { +public: + vector exclusiveTime(int n, vector &logs) { + vector res(n, 0); + int lastTime = 0, lastId = 0; + vector st(1, 0); + for (auto &str : logs) { + int first = str.find(':'), second = str.rfind(':'); + int id = stoi(str.substr(0, first)); + bool end = second - first == 4; // sizeof(":end:")-1; + int timestamp = stoi(str.substr(second + 1)); + if (end) { + res[id] += timestamp - lastTime + 1; + lastTime = timestamp + 1; + st.pop_back(); + } else { + res[st.back()] += timestamp - lastTime; + lastTime = timestamp; + st.push_back(id); + } + } + return res; + } +}; diff --git a/cpp/637.AverageOfLevelsInBinaryTree/dfs.cpp b/cpp/637.AverageOfLevelsInBinaryTree/dfs.cpp deleted file mode 100644 index 2b379b5..0000000 --- a/cpp/637.AverageOfLevelsInBinaryTree/dfs.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector averageOfLevels(TreeNode* root) { - vectorres; - vectornums; - helper(res,root,nums,0); - for(int i=0;i&res,TreeNode* root,vector&nums,int i){ - if(root==NULL) - return; - if(nums.size()==i){ - nums.emplace_back(1); - res.emplace_back(root->val); - } - else{ - ++nums[i]; - res[i]+=root->val; - } - helper(res,root->left,nums,i+1); - helper(res,root->right,nums,i+1); - } -}; diff --git a/cpp/637.cpp b/cpp/637.cpp new file mode 100644 index 0000000..2542cfc --- /dev/null +++ b/cpp/637.cpp @@ -0,0 +1,34 @@ +// dfs.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector averageOfLevels(TreeNode *root) { + vector res; + vector nums; + helper(res, root, nums, 0); + for (int i = 0; i < res.size(); ++i) + res[i] /= nums[i]; + return res; + } + void helper(vector &res, TreeNode *root, vector &nums, int i) { + if (root == NULL) + return; + if (nums.size() == i) { + nums.emplace_back(1); + res.emplace_back(root->val); + } else { + ++nums[i]; + res[i] += root->val; + } + helper(res, root->left, nums, i + 1); + helper(res, root->right, nums, i + 1); + } +}; diff --git a/cpp/64.MinimumPathSum/dp-9ms.cpp b/cpp/64.MinimumPathSum/dp-9ms.cpp deleted file mode 100644 index 955266a..0000000 --- a/cpp/64.MinimumPathSum/dp-9ms.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int minPathSum(vector>& grid) { - int row=grid.size(); - if(row==0)return 0; - int col=grid[0].size(); - vector>dp(row,vector(col)); - dp[0][0]=grid[0][0]; - for(int i=1;i>& grid) { + int row = grid.size(); + if (row == 0) + return 0; + int col = grid[0].size(); + vector> dp(row, vector(col)); + dp[0][0] = grid[0][0]; + for (int i = 1; i < col; ++i) + dp[0][i] = dp[0][i - 1] + grid[0][i]; + for (int i = 1; i < row; ++i) + dp[i][0] = dp[i - 1][0] + grid[i][0]; + for (int i = 1; i < row; ++i) + for (int j = 1; j < col; ++j) + dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; + return dp[row - 1][col - 1]; + } +}; diff --git a/cpp/643.MaximumAverageSubarrayI/SingleScan.cpp b/cpp/643.MaximumAverageSubarrayI/SingleScan.cpp deleted file mode 100644 index f0c047d..0000000 --- a/cpp/643.MaximumAverageSubarrayI/SingleScan.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - double findMaxAverage(vector& nums, int k) { - double curVal=0; - for(int i=0;i &nums, int k) { + double curVal = 0; + for (int i = 0; i < k; ++i) + curVal += nums[i]; + double maxVal = curVal; + for (int i = k; i < nums.size(); ++i) + maxVal = max(curVal += nums[i] - nums[i - k], maxVal); + return maxVal / k; + } +}; diff --git a/cpp/645.SetMismatch/hashset.cpp b/cpp/645.SetMismatch/hashset.cpp deleted file mode 100644 index b87a7c9..0000000 --- a/cpp/645.SetMismatch/hashset.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - vector findErrorNums(vector& nums) { - unordered_sethashset; - int n=nums.size(); - for(int i=1;i<=n;++i) - hashset.insert(i); - vectorres(2); - for(int num:nums) - if(hashset.find(num)!=hashset.end()) - hashset.erase(num); - else - res[0]=num; - res[1]=*hashset.begin(); - return res; - } -}; diff --git a/cpp/645.cpp b/cpp/645.cpp new file mode 100644 index 0000000..46bb487 --- /dev/null +++ b/cpp/645.cpp @@ -0,0 +1,18 @@ +// hashset.cpp +class Solution { +public: + vector findErrorNums(vector &nums) { + unordered_set hashset; + int n = nums.size(); + for (int i = 1; i <= n; ++i) + hashset.insert(i); + vector res(2); + for (int num : nums) + if (hashset.find(num) != hashset.end()) + hashset.erase(num); + else + res[0] = num; + res[1] = *hashset.begin(); + return res; + } +}; diff --git a/cpp/647.PalindromicSubstrings/center-extend-3ms.cpp b/cpp/647.PalindromicSubstrings/center-extend-3ms.cpp deleted file mode 100644 index 7bcf3b8..0000000 --- a/cpp/647.PalindromicSubstrings/center-extend-3ms.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - int count = 0; - int countSubstrings(string s) { - for (int i=0; i= 0 && right < s.size() && s[left] == s[right]) { - count++; left--, right++; - } - } -}; diff --git a/cpp/647.PalindromicSubstrings/dp-22ms.cpp b/cpp/647.PalindromicSubstrings/dp-22ms.cpp deleted file mode 100644 index 8de201c..0000000 --- a/cpp/647.PalindromicSubstrings/dp-22ms.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int countSubstrings(string s) { - int n=s.size(),res=n; - vector>dp(n,vector(n,0)); - for(int i=0;i= 0 && right < s.size() && s[left] == s[right]) { + count++; + left--, right++; + } + } +}; +// dp-22ms.cpp +class Solution2 { +public: + int countSubstrings(string s) { + int n = s.size(), res = n; + vector> dp(n, vector(n, 0)); + for (int i = 0; i < n; ++i) + dp[i][i] = 1; + for (int len = 1; len < n; ++len) + for (int i = 0; i + len < n; ++i) + if (s[i] == s[i + len] && (dp[i + 1][i + len - 1] || len < 2)) + res += (dp[i][i + len] = 1); + return res; + } +}; diff --git a/cpp/648.ReplaceWords/BruteForce.cpp b/cpp/648.ReplaceWords/BruteForce.cpp deleted file mode 100644 index 7758f2f..0000000 --- a/cpp/648.ReplaceWords/BruteForce.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - string replaceWords(vector& dict, string sentence) { - stringstream ss(sentence); - vectorres; - string word; - while(!ss.eof()){ - ss>>word; - res.emplace_back(word); - } - for(auto d:dict) - for(auto &w:res) - if(w.find(d)==0) - w=d; - word=""; - for(auto w:res) - word+=w+" "; - word.pop_back(); - return word; - } -}; diff --git a/cpp/648.ReplaceWords/usingTrie.cpp b/cpp/648.ReplaceWords/usingTrie.cpp deleted file mode 100644 index d407ce4..0000000 --- a/cpp/648.ReplaceWords/usingTrie.cpp +++ /dev/null @@ -1,50 +0,0 @@ -class Solution { - struct trie{ - trie():isWord(false){ - for(int i=0;i<26;++i) - arr[i]=nullptr; - } - bool isWord; - trie *arr[26]; - }root; - void buildTrie(vector& dict){ - for(auto &str:dict) - buildTrie(str); - } - void buildTrie(string &word){ - trie *p=&root; - for(auto ch:word){ - int offset=ch>='a'&&ch<='z'?ch-'a':ch-'A'; - if( p->arr[offset]==nullptr ) - p->arr[offset]=new trie(); - p=p->arr[offset]; - } - p->isWord=true; - } - int replace(string& word){ - trie* p=&root; - int length=0; - for(auto ch:word){ - int offset=ch>='a'&&ch<='z'?ch-'a':ch-'A'; - if( p->arr[offset]==nullptr ) - return INT_MAX; - ++length; - p=p->arr[offset]; - if( p->isWord ) - return length; - } - return INT_MAX; - } -public: - string replaceWords(vector& dict, string sentence) { - stringstream ss(sentence); - string word,res; - buildTrie(dict); - while(!ss.eof()){ - ss>>word; - res+=word.substr(0,replace(word))+" "; - } - res.pop_back(); - return res; - } -}; diff --git a/cpp/648.cpp b/cpp/648.cpp new file mode 100644 index 0000000..41e90e3 --- /dev/null +++ b/cpp/648.cpp @@ -0,0 +1,74 @@ +// BruteForce.cpp +class Solution { +public: + string replaceWords(vector &dict, string sentence) { + stringstream ss(sentence); + vector res; + string word; + while (!ss.eof()) { + ss >> word; + res.emplace_back(word); + } + for (auto d : dict) + for (auto &w : res) + if (w.find(d) == 0) + w = d; + word = ""; + for (auto w : res) + word += w + " "; + word.pop_back(); + return word; + } +}; +// usingTrie.cpp +class Solution2 { + struct trie { + trie() : isWord(false) { + for (int i = 0; i < 26; ++i) + arr[i] = nullptr; + } + bool isWord; + trie *arr[26]; + } root; + void buildTrie(vector &dict) { + for (auto &str : dict) + buildTrie(str); + } + void buildTrie(string &word) { + trie *p = &root; + for (auto ch : word) { + int offset = ch >= 'a' && ch <= 'z' ? ch - 'a' : ch - 'A'; + if (p->arr[offset] == nullptr) + p->arr[offset] = new trie(); + p = p->arr[offset]; + } + p->isWord = true; + } + int replace(string &word) { + trie *p = &root; + int length = 0; + for (auto ch : word) { + int offset = ch >= 'a' && ch <= 'z' ? ch - 'a' : ch - 'A'; + if (p->arr[offset] == nullptr) + return INT_MAX; + ++length; + p = p->arr[offset]; + if (p->isWord) + return length; + } + return INT_MAX; + } + +public: + string replaceWords(vector &dict, string sentence) { + stringstream ss(sentence); + string word, res; + buildTrie(dict); + while (!ss.eof()) { + ss >> word; + res += word.substr(0, replace(word)) + " "; + } + res.pop_back(); + return res; + } +}; diff --git a/cpp/65.ValidNumber/simple.cpp b/cpp/65.ValidNumber/simple.cpp deleted file mode 100644 index 84ee40c..0000000 --- a/cpp/65.ValidNumber/simple.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution { -public: - bool isNumber(string s) { - s.erase(0,s.find_first_not_of(" ")); - s.erase(s.find_last_not_of(" ") + 1); - bool eFlag=false,dotFlag=false,signFlag=false,digitFlag=false; - for(auto c:s){ - if(c>='0'&&c<='9'){ - digitFlag=true; - } - else - switch(c){ - case '+': - case '-': - if(signFlag||digitFlag||dotFlag) - return false; - signFlag=true; - break; - case 'e': - if(eFlag||!digitFlag) - return false; - eFlag=true; - signFlag=digitFlag=dotFlag=false; - break; - case '.': - if(dotFlag||eFlag) - return false; - dotFlag=true; - break; - default: - return false; - } - } - return digitFlag; - } -}; diff --git a/cpp/65.cpp b/cpp/65.cpp new file mode 100644 index 0000000..ffbc8ac --- /dev/null +++ b/cpp/65.cpp @@ -0,0 +1,36 @@ +// simple.cpp +class Solution { +public: + bool isNumber(string s) { + s.erase(0, s.find_first_not_of(" ")); + s.erase(s.find_last_not_of(" ") + 1); + bool eFlag = false, dotFlag = false, signFlag = false, digitFlag = false; + for (auto c : s) { + if (c >= '0' && c <= '9') { + digitFlag = true; + } else + switch (c) { + case '+': + case '-': + if (signFlag || digitFlag || dotFlag) + return false; + signFlag = true; + break; + case 'e': + if (eFlag || !digitFlag) + return false; + eFlag = true; + signFlag = digitFlag = dotFlag = false; + break; + case '.': + if (dotFlag || eFlag) + return false; + dotFlag = true; + break; + default: + return false; + } + } + return digitFlag; + } +}; diff --git a/cpp/650.2KeysKeyboard/simpleDP.cpp b/cpp/650.2KeysKeyboard/simpleDP.cpp deleted file mode 100644 index 4014cc2..0000000 --- a/cpp/650.2KeysKeyboard/simpleDP.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - int minSteps(int n) { - if(n<2) - return 0; - vectordp(n+1,0); - dp[2]=2; - for(int i=3;i<=n;++i){ - dp[i]=i; - for(int j=i-1;j>=2;--j) - if(i%j==0) - dp[i]=min(dp[j]+i/j,dp[i]); - } - return dp[n]; - } -}; diff --git a/cpp/650.2KeysKeyboard/smart.cpp b/cpp/650.2KeysKeyboard/smart.cpp deleted file mode 100644 index fd3b9b1..0000000 --- a/cpp/650.2KeysKeyboard/smart.cpp +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { -public: - int minSteps(int n) { - if (n == 1) return 0; - for (int i = 2; i < n; i++) - if (n % i == 0) return i + minSteps(n / i); - return n; - } -}; diff --git a/cpp/650.cpp b/cpp/650.cpp new file mode 100644 index 0000000..4756692 --- /dev/null +++ b/cpp/650.cpp @@ -0,0 +1,29 @@ +// simpleDP.cpp +class Solution { +public: + int minSteps(int n) { + if (n < 2) + return 0; + vector dp(n + 1, 0); + dp[2] = 2; + for (int i = 3; i <= n; ++i) { + dp[i] = i; + for (int j = i - 1; j >= 2; --j) + if (i % j == 0) + dp[i] = min(dp[j] + i / j, dp[i]); + } + return dp[n]; + } +}; +// smart.cpp +class Solution2 { +public: + int minSteps(int n) { + if (n == 1) + return 0; + for (int i = 2; i < n; i++) + if (n % i == 0) + return i + minSteps(n / i); + return n; + } +}; diff --git a/cpp/653.TwoSumIV-InputIsABST/hashset.cpp b/cpp/653.TwoSumIV-InputIsABST/hashset.cpp deleted file mode 100644 index f6b2f5f..0000000 --- a/cpp/653.TwoSumIV-InputIsABST/hashset.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - unordered_sethashset; -public: - bool findTarget(TreeNode* root, int k) { - if(!root) - return false; - if(hashset.find(k-root->val)!=hashset.end()) - return true; - hashset.insert(root->val); - return findTarget(root->left,k)||findTarget(root->right,k); - } -}; diff --git a/cpp/653.cpp b/cpp/653.cpp new file mode 100644 index 0000000..16ba9b1 --- /dev/null +++ b/cpp/653.cpp @@ -0,0 +1,23 @@ +// hashset.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + unordered_set hashset; + +public: + bool findTarget(TreeNode *root, int k) { + if (!root) + return false; + if (hashset.find(k - root->val) != hashset.end()) + return true; + hashset.insert(root->val); + return findTarget(root->left, k) || findTarget(root->right, k); + } +}; diff --git a/cpp/654.MaximumBinaryTree/nlogn.cpp b/cpp/654.MaximumBinaryTree/nlogn.cpp deleted file mode 100644 index d5c619c..0000000 --- a/cpp/654.MaximumBinaryTree/nlogn.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* constructMaximumBinaryTree(vector& nums) { - return recursion(nums.begin(),0,nums.size()); - } - TreeNode* recursion(vector::iterator it,int left,int right){ - if(left>=right) - return nullptr; - auto maxIt=max_element(it+left,it+right); - TreeNode *root=new TreeNode(*maxIt); - root->left=recursion(it,left,(int)(maxIt-it)); - root->right=recursion(it,(int)(maxIt-it)+1,right); - return root; - } -}; diff --git a/cpp/654.cpp b/cpp/654.cpp new file mode 100644 index 0000000..607766c --- /dev/null +++ b/cpp/654.cpp @@ -0,0 +1,25 @@ +// nlogn.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode *constructMaximumBinaryTree(vector &nums) { + return recursion(nums.begin(), 0, nums.size()); + } + TreeNode *recursion(vector::iterator it, int left, int right) { + if (left >= right) + return nullptr; + auto maxIt = max_element(it + left, it + right); + TreeNode *root = new TreeNode(*maxIt); + root->left = recursion(it, left, (int)(maxIt - it)); + root->right = recursion(it, (int)(maxIt - it) + 1, right); + return root; + } +}; diff --git a/cpp/655.PrintBinaryTree/preorder.cpp b/cpp/655.PrintBinaryTree/preorder.cpp deleted file mode 100644 index 7147fd6..0000000 --- a/cpp/655.PrintBinaryTree/preorder.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - vector> printTree(TreeNode* root) { - int m=getHeight(root); - if(m==0)return vector>(1,vector(1,"")); - int n=(1<>res(m,vector(n,"")); - fillVector(res,root,0,n-1,0); - return res; - } - void fillVector(vector>&res,TreeNode* root,int l,int r,int h){ - if(!root) - return; - int mid=(l+r)/2; - res[h][mid]=to_string(root->val); - fillVector(res,root->left,l,mid-1,h+1); - fillVector(res,root->right,mid+1,r,h+1); - } - int getHeight(TreeNode* root){ - if(root==nullptr) - return 0; - int l=getHeight(root->left); - int r=getHeight(root->right); - return l>r?l+1:r+1; - } -}; diff --git a/cpp/655.cpp b/cpp/655.cpp new file mode 100644 index 0000000..03aa595 --- /dev/null +++ b/cpp/655.cpp @@ -0,0 +1,38 @@ +// preorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector> printTree(TreeNode *root) { + int m = getHeight(root); + if (m == 0) + return vector>(1, vector(1, "")); + int n = (1 << m) - 1; + vector> res(m, vector(n, "")); + fillVector(res, root, 0, n - 1, 0); + return res; + } + void fillVector(vector> &res, TreeNode *root, int l, int r, + int h) { + if (!root) + return; + int mid = (l + r) / 2; + res[h][mid] = to_string(root->val); + fillVector(res, root->left, l, mid - 1, h + 1); + fillVector(res, root->right, mid + 1, r, h + 1); + } + int getHeight(TreeNode *root) { + if (root == nullptr) + return 0; + int l = getHeight(root->left); + int r = getHeight(root->right); + return l > r ? l + 1 : r + 1; + } +}; diff --git a/cpp/657.JudgeRouteCircle/usingSwitch.cpp b/cpp/657.JudgeRouteCircle/usingSwitch.cpp deleted file mode 100644 index cb5c8b8..0000000 --- a/cpp/657.JudgeRouteCircle/usingSwitch.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - bool judgeCircle(string moves) { - int x=0,y=0; - for(auto ch:moves) - switch(ch){ - case 'U':++y;break; - case 'D':--y;break; - case 'L':--x;break; - case 'R':++x;break; - } - return x==0&&y==0; - } -}; diff --git a/cpp/657.cpp b/cpp/657.cpp new file mode 100644 index 0000000..de0ce0b --- /dev/null +++ b/cpp/657.cpp @@ -0,0 +1,23 @@ +// usingSwitch.cpp +class Solution { +public: + bool judgeCircle(string moves) { + int x = 0, y = 0; + for (auto ch : moves) + switch (ch) { + case 'U': + ++y; + break; + case 'D': + --y; + break; + case 'L': + --x; + break; + case 'R': + ++x; + break; + } + return x == 0 && y == 0; + } +}; diff --git a/cpp/66.PlusOne/iteration-3ms.cpp b/cpp/66.PlusOne/iteration-3ms.cpp deleted file mode 100644 index 0506915..0000000 --- a/cpp/66.PlusOne/iteration-3ms.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - vector plusOne(vector& digits) { - int len=digits.size(),carry=0; - for(int i=len-1;i>=0;--i){ - digits[i]+=1; - if(digits[i]>=10){ - digits[i]-=10; - carry=1; - } - else - carry=0; - if(carry==0) - break; - } - if(carry==1) - digits.insert(digits.begin(),1); - return digits; - } -}; diff --git a/cpp/66.cpp b/cpp/66.cpp new file mode 100644 index 0000000..52181c6 --- /dev/null +++ b/cpp/66.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector plusOne(vector& digits) { + int carry = 1; + for (int i = digits.size() - 1; i >= 0 && carry; --i) { + digits[i] += 1; + if (digits[i] >= 10) { + digits[i] -= 10; + } else { + carry = 0; + } + } + if (carry == 1) + digits.insert(digits.begin(), 1); + return digits; + } +}; diff --git a/cpp/661.ImageSmoother/simple.cpp b/cpp/661.ImageSmoother/simple.cpp deleted file mode 100644 index ebaa475..0000000 --- a/cpp/661.ImageSmoother/simple.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -public: - vector> imageSmoother(vector>& M) { - int n=M.size(); - if(n==0) - return M; - int m=M[0].size(); - vector>res(n,vector(m,0)); - for(int i=0;i=n||i+x<0||j+y>=m||j+y<0) - continue; - else - ++count,sum+=M[i+x][y+j]; - res[i][j]=sum/count; - } - return res; - } -}; diff --git a/cpp/661.cpp b/cpp/661.cpp new file mode 100644 index 0000000..ef75736 --- /dev/null +++ b/cpp/661.cpp @@ -0,0 +1,23 @@ +// simple.cpp +class Solution { +public: + vector> imageSmoother(vector> &M) { + int n = M.size(); + if (n == 0) + return M; + int m = M[0].size(); + vector> res(n, vector(m, 0)); + for (int i = 0; i < n; ++i) + for (int j = 0; j < m; ++j) { + int sum = 0, count = 0; + for (int x = -1; x <= 1; ++x) + for (int y = -1; y <= 1; ++y) + if (i + x >= n || i + x < 0 || j + y >= m || j + y < 0) + continue; + else + ++count, sum += M[i + x][y + j]; + res[i][j] = sum / count; + } + return res; + } +}; diff --git a/cpp/665.Non-decreasingArray/singleScan.cpp b/cpp/665.Non-decreasingArray/singleScan.cpp deleted file mode 100644 index cc179fe..0000000 --- a/cpp/665.Non-decreasingArray/singleScan.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - bool checkPossibility(vector& nums) { - if(nums.size()<=2) - return true; - int count=0,left=0,right=nums.size()-1; - while(left=nums[right-1]) - --right; - if(left==right) - return true; - if(nums[left]>nums[right]&&right-left==1) - return (left==0||nums[left-1]<=nums[right])||(right==nums.size()-1||nums[left]<=nums[right+1]); - return false; - } -}; diff --git a/cpp/665.cpp b/cpp/665.cpp new file mode 100644 index 0000000..d652921 --- /dev/null +++ b/cpp/665.cpp @@ -0,0 +1,19 @@ +// singleScan.cpp +class Solution { +public: + bool checkPossibility(vector &nums) { + if (nums.size() <= 2) + return true; + int count = 0, left = 0, right = nums.size() - 1; + while (left < right && nums[left] <= nums[left + 1]) + ++left; + while (left < right && nums[right] >= nums[right - 1]) + --right; + if (left == right) + return true; + if (nums[left] > nums[right] && right - left == 1) + return (left == 0 || nums[left - 1] <= nums[right]) || + (right == nums.size() - 1 || nums[left] <= nums[right + 1]); + return false; + } +}; diff --git a/cpp/669.TrimABinarySearchTree/recursion.cpp b/cpp/669.TrimABinarySearchTree/recursion.cpp deleted file mode 100644 index 1ba397b..0000000 --- a/cpp/669.TrimABinarySearchTree/recursion.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* trimBST(TreeNode* root, int L, int R) { - if(!root) - return nullptr; - if(root->val>R) - return trimBST(root->left,L,R); - if(root->valright,L,R); - root->left=trimBST(root->left,L,R); - root->right=trimBST(root->right,L,R); - return root; - } -}; diff --git a/cpp/669.cpp b/cpp/669.cpp new file mode 100644 index 0000000..034667b --- /dev/null +++ b/cpp/669.cpp @@ -0,0 +1,24 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode *trimBST(TreeNode *root, int L, int R) { + if (!root) + return nullptr; + if (root->val > R) + return trimBST(root->left, L, R); + if (root->val < L) + return trimBST(root->right, L, R); + root->left = trimBST(root->left, L, R); + root->right = trimBST(root->right, L, R); + return root; + } +}; diff --git a/cpp/67.AddBinary/concise-6ms.cpp b/cpp/67.AddBinary/concise-6ms.cpp deleted file mode 100644 index 42551e0..0000000 --- a/cpp/67.AddBinary/concise-6ms.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - string addBinary(string a, string b) { - string s=""; - int i=a.size()-1,j=b.size()-1; - char c=0; - while(i>=0||j>=0||c==1){ - c+= i>=0?a[i--]-'0':0; - c+= j>=0?b[j--]-'0':0; - s=(char)(c%2+'0')+s; - c/=2; - } - return s; - } -}; diff --git a/cpp/67.cpp b/cpp/67.cpp new file mode 100644 index 0000000..e2e189f --- /dev/null +++ b/cpp/67.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + string addBinary(string a, string b) { + string s = ""; + int i = a.size() - 1, j = b.size() - 1; + char c = 0; + while (i >= 0 || j >= 0 || c == 1) { + c += i >= 0 ? a[i--] - '0' : 0; + c += j >= 0 ? b[j--] - '0' : 0; + s += (char)(c % 2 + '0'); + c /= 2; + } + return {s.rbegin(), s.rend()}; + } +}; diff --git a/cpp/670.MaximumSwap/greedy.cpp b/cpp/670.MaximumSwap/greedy.cpp deleted file mode 100644 index a169833..0000000 --- a/cpp/670.MaximumSwap/greedy.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - int maximumSwap(int num) { - string res=to_string(num); - int index1=-1,index2; - for(int i=0;ii;--j){ - if(res[j]>res[i]){ - if(index1==-1) - index1=i,index2=j; - else if(res[index2] i; --j) { + if (res[j] > res[i]) { + if (index1 == -1) + index1 = i, index2 = j; + else if (res[index2] < res[j]) + index2 = j; + } + } + if (index1 != -1) + break; + } + if (index1 == -1) + return num; + swap(res[index1], res[index2]); + return stoi(res); + } +}; diff --git a/cpp/671.SecondMinimumNodeInABinaryTree/recursion-0ms.cpp b/cpp/671.SecondMinimumNodeInABinaryTree/recursion-0ms.cpp deleted file mode 100644 index 3b55e76..0000000 --- a/cpp/671.SecondMinimumNodeInABinaryTree/recursion-0ms.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int minValue; - int *sec_min; -public: - int findSecondMinimumValue(TreeNode* root) { - if(!root) - return -1; - minValue=root->val; - sec_min=nullptr; - helper(root->left); - helper(root->right); - return sec_min==nullptr?-1:*sec_min; - } - void helper(TreeNode* root){ - if(!root) - return; - if(root->val > minValue) - sec_min= sec_min==nullptr? &root->val : *sec_min >root->val ? &root->val : sec_min ; - helper(root->left); - helper(root->right); - } -}; diff --git a/cpp/671.cpp b/cpp/671.cpp new file mode 100644 index 0000000..c8a4379 --- /dev/null +++ b/cpp/671.cpp @@ -0,0 +1,35 @@ +// recursion-0ms.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int minValue; + int *sec_min; + +public: + int findSecondMinimumValue(TreeNode *root) { + if (!root) + return -1; + minValue = root->val; + sec_min = nullptr; + helper(root->left); + helper(root->right); + return sec_min == nullptr ? -1 : *sec_min; + } + void helper(TreeNode *root) { + if (!root) + return; + if (root->val > minValue) + sec_min = sec_min == nullptr + ? &root->val + : *sec_min > root->val ? &root->val : sec_min; + helper(root->left); + helper(root->right); + } +}; diff --git a/cpp/674.LongestContinuousIncreasingSubsequence/singleScan.cpp b/cpp/674.LongestContinuousIncreasingSubsequence/singleScan.cpp deleted file mode 100644 index 69c9307..0000000 --- a/cpp/674.LongestContinuousIncreasingSubsequence/singleScan.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - int findLengthOfLCIS(vector& nums) { - if(nums.size()==0) - return 0; - int res=1,cur=1; - for(int i=1;inums[i-1]) - ++cur; - else{ - res=max(res,cur); - cur=1; - } - return max(res,cur); - } -}; diff --git a/cpp/674.cpp b/cpp/674.cpp new file mode 100644 index 0000000..a32a29f --- /dev/null +++ b/cpp/674.cpp @@ -0,0 +1,17 @@ +// singleScan.cpp +class Solution { +public: + int findLengthOfLCIS(vector &nums) { + if (nums.size() == 0) + return 0; + int res = 1, cur = 1; + for (int i = 1; i < nums.size(); ++i) + if (nums[i] > nums[i - 1]) + ++cur; + else { + res = max(res, cur); + cur = 1; + } + return max(res, cur); + } +}; diff --git a/cpp/676.ImplementMagicDictionary/trie.cpp b/cpp/676.ImplementMagicDictionary/trie.cpp deleted file mode 100644 index c5d0396..0000000 --- a/cpp/676.ImplementMagicDictionary/trie.cpp +++ /dev/null @@ -1,64 +0,0 @@ -class MagicDictionary { - struct trie{ - trie():isWord(false){ - memset(this,0,sizeof(trie)); - } - bool isWord; - trie *children[26]; - }root; - - void insert(string &word) { - trie *p=&root; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - p->children[offset]=new trie(); - p=p->children[offset]; - } - p->isWord=true; - } - - bool _search(string word) { - trie *p=&root; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr ) - return false; - p=p->children[offset]; - } - return p->isWord; - } - -public: - /** Initialize your data structure here. */ - MagicDictionary() { - - } - - /** Build a dictionary through a list of words */ - void buildDict(vector dict) { - for(string &str:dict) - insert(str); - } - - /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ - bool search(string word) { - for(int i=0;ichildren[offset] == nullptr) + p->children[offset] = new trie(); + p = p->children[offset]; + } + p->isWord = true; + } + + bool _search(string word) { + trie *p = &root; + for (auto ch : word) { + int offset = ch - 'a'; + if (p->children[offset] == nullptr) + return false; + p = p->children[offset]; + } + return p->isWord; + } + +public: + /** Initialize your data structure here. */ + MagicDictionary() {} + + /** Build a dictionary through a list of words */ + void buildDict(vector dict) { + for (string &str : dict) + insert(str); + } + + /** Returns if there is any word in the trie that equals to the given word + * after modifying exactly one character */ + bool search(string word) { + for (int i = 0; i < word.size(); ++i) { + char old = word[i]; + for (char j = 'a'; j <= 'z'; ++j) { + word[i] = j; + if (j != old && _search(word)) + return true; + } + word[i] = old; + } + return false; + } +}; + +/** + * Your MagicDictionary object will be instantiated and called as such: + * MagicDictionary obj = new MagicDictionary(); + * obj.buildDict(dict); + * bool param_2 = obj.search(word); + */ diff --git a/cpp/677.MapSumPairs/hashmap+trie.cpp b/cpp/677.MapSumPairs/hashmap+trie.cpp deleted file mode 100644 index 19eca5c..0000000 --- a/cpp/677.MapSumPairs/hashmap+trie.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class MapSum { - struct trie_node{ - trie_node *children[26]; - int val; - trie_node(){ - memset(this,0,sizeof(trie_node)); - } - }root; - unordered_mapwords; -public: - /** Initialize your data structure here. */ - MapSum() { - - } - - void insert(string key, int val) { - auto word=words.find(key); - if(word!=words.end()) - val=val-word->second; - words[key]=val; - trie_node *p=&root; - for(char ch:key){ - if(!p->children[ch-'a']) - p->children[ch-'a']=new trie_node(); - p=p->children[ch-'a']; - p->val+=val; - } - } - - int sum(string prefix) { - trie_node *p=&root,*child; - int i; - for(i=0;ichildren[prefix[i]-'a']; - if(!child) - return 0; - p=child; - } - return p->val; - } -}; - -/** - * Your MapSum object will be instantiated and called as such: - * MapSum obj = new MapSum(); - * obj.insert(key,val); - * int param_2 = obj.sum(prefix); - */ diff --git a/cpp/677.cpp b/cpp/677.cpp new file mode 100644 index 0000000..ff4faaa --- /dev/null +++ b/cpp/677.cpp @@ -0,0 +1,46 @@ +// hashmap+trie.cpp +class MapSum { + struct trie_node { + trie_node *children[26]; + int val; + trie_node() { memset(this, 0, sizeof(trie_node)); } + } root; + unordered_map words; + +public: + /** Initialize your data structure here. */ + MapSum() {} + + void insert(string key, int val) { + auto word = words.find(key); + if (word != words.end()) + val = val - word->second; + words[key] = val; + trie_node *p = &root; + for (char ch : key) { + if (!p->children[ch - 'a']) + p->children[ch - 'a'] = new trie_node(); + p = p->children[ch - 'a']; + p->val += val; + } + } + + int sum(string prefix) { + trie_node *p = &root, *child; + int i; + for (i = 0; i < prefix.size(); ++i) { + child = p->children[prefix[i] - 'a']; + if (!child) + return 0; + p = child; + } + return p->val; + } +}; + +/** + * Your MapSum object will be instantiated and called as such: + * MapSum obj = new MapSum(); + * obj.insert(key,val); + * int param_2 = obj.sum(prefix); + */ diff --git a/cpp/68.cpp b/cpp/68.cpp new file mode 100644 index 0000000..7576242 --- /dev/null +++ b/cpp/68.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + vector fullJustify(vector words, int maxWidth) { + vector res; + for(int i = 0, j = 0, curLen = 0; i < words.size(); i = j, curLen = 0) { + while (j < words.size() && words[j].size() + curLen + j - i <= maxWidth) { + curLen += words[j++].size(); + } + if (j < words.size() && j - i > 1) { + vector spaces(j - i - 1, 1); + for (int k = 0; k < (maxWidth - curLen) - spaces.size(); ++k) { + spaces[k % spaces.size()]++; + } + string line = words[i]; + for (int k = i + 1; k < j; ++k) { + line += string(spaces[k - i - 1], ' ') + words[k]; + } + res.push_back(line); + } else { + string line = words[i]; + for (int k = i + 1; k < j; ++k) { + line += ' ' + words[k]; + } + line += string(maxWidth - line.size(), ' '); + res.push_back(line); + } + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/680.ValidPalindromeII/singleScan.cpp b/cpp/680.ValidPalindromeII/singleScan.cpp deleted file mode 100644 index aaa96f6..0000000 --- a/cpp/680.ValidPalindromeII/singleScan.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - bool validPalindrome(string s) { - int l=0,r=s.size()-1; - while(l& ops) { - vectorst; - int res=0; - for(auto &str:ops){ - if(str=="C"){ - res-=st.back(); - st.pop_back(); - continue; - } - else if(str=="D") - st.push_back(st.back()*2); - else if(str=="+") - st.push_back(st.back()+st[st.size()-2]); - else - st.push_back(stoi(str)); - res+=st.back(); - } - return res; - } -}; diff --git a/cpp/682.cpp b/cpp/682.cpp new file mode 100644 index 0000000..6562315 --- /dev/null +++ b/cpp/682.cpp @@ -0,0 +1,22 @@ +// usingVector.cpp +class Solution { +public: + int calPoints(vector &ops) { + vector st; + int res = 0; + for (auto &str : ops) { + if (str == "C") { + res -= st.back(); + st.pop_back(); + continue; + } else if (str == "D") + st.push_back(st.back() * 2); + else if (str == "+") + st.push_back(st.back() + st[st.size() - 2]); + else + st.push_back(stoi(str)); + res += st.back(); + } + return res; + } +}; diff --git a/cpp/686.RepeatedStringMatch/simple.cpp b/cpp/686.RepeatedStringMatch/simple.cpp deleted file mode 100644 index 9948094..0000000 --- a/cpp/686.RepeatedStringMatch/simple.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int repeatedStringMatch(string A, string B) { - if(unordered_set(A.begin(),A.end()).size()(B.begin(),B.end()).size()) - return -1; - int i; - string temp=A; - for(i=1;i(A.begin(), A.end()).size() < + unordered_set(B.begin(), B.end()).size()) + return -1; + int i; + string temp = A; + for (i = 1; i < B.size() / A.size() + 3; ++i) + if (temp.find(B) != string::npos) + return i; + else + temp += A; + return -1; + } +}; diff --git a/cpp/687.LongestUnivaluePath.cpp b/cpp/687.LongestUnivaluePath.cpp deleted file mode 100644 index c110040..0000000 --- a/cpp/687.LongestUnivaluePath.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 120 ms, faster than 95.67% of C++ online submissions for Longest Univalue Path. -//Memory Usage: 49.7 MB, less than 64.70% of C++ online submissions for Longest Univalue Path. -public: - int longestUnivaluePath(TreeNode* root) { - int maxLen=0; - functiondfs=[&](TreeNode* root,TreeNode* parent){ - if(!root) - return 0; - int l=dfs(root->left,root); - int r=dfs(root->right,root); - maxLen=max(maxLen,l+r); - return not parent or parent->val==root->val?max(l,r)+1:0; - }; - dfs(root,nullptr); - return maxLen; - } -}; \ No newline at end of file diff --git a/cpp/687.cpp b/cpp/687.cpp new file mode 100644 index 0000000..63c576c --- /dev/null +++ b/cpp/687.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 120 ms, faster than 95.67% of C++ online submissions for Longest + // Univalue Path. Memory Usage: 49.7 MB, less than 64.70% of C++ online + // submissions for Longest Univalue Path. +public: + int longestUnivaluePath(TreeNode *root) { + int maxLen = 0; + function dfs = [&](TreeNode *root, + TreeNode *parent) { + if (!root) + return 0; + int l = dfs(root->left, root); + int r = dfs(root->right, root); + maxLen = max(maxLen, l + r); + return not parent or parent->val == root->val ? max(l, r) + 1 : 0; + }; + dfs(root, nullptr); + return maxLen; + } +}; \ No newline at end of file diff --git a/cpp/69.Sqrt(X).cpp b/cpp/69.Sqrt(X).cpp deleted file mode 100644 index 2c9d6eb..0000000 --- a/cpp/69.Sqrt(X).cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Sqrt(x). -//Memory Usage: 8.1 MB, less than 84.49% of C++ online submissions for Sqrt(x). -public: - int mySqrt(int x) { - if(x==0) return 0; - int low=1,high=x; - while(lowx?low-1:low; - } -}; \ No newline at end of file diff --git a/cpp/69.cpp b/cpp/69.cpp new file mode 100644 index 0000000..9ddd901 --- /dev/null +++ b/cpp/69.cpp @@ -0,0 +1,22 @@ +class Solution { + // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Sqrt(x). + // Memory Usage: 8.1 MB, less than 84.49% of C++ online submissions for + // Sqrt(x). +public: + int mySqrt(int x) { + if (x == 0) + return 0; + int low = 1, high = x; + while (low < high) { + int mid = low + (high - low) / 2; + int result = x / mid; + if (result == mid) + return mid; + else if (result < mid) + high = mid - 1; + else + low = mid + 1; + } + return (long long)low * low > x ? low - 1 : low; + } +}; \ No newline at end of file diff --git a/cpp/690.EmployeeImportance/dfs.cpp b/cpp/690.EmployeeImportance/dfs.cpp deleted file mode 100644 index 7c83563..0000000 --- a/cpp/690.EmployeeImportance/dfs.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -// Employee info -class Employee { -public: - // It's the unique ID of each node. - // unique id of this employee - int id; - // the importance value of this employee - int importance; - // the id of direct subordinates - vector subordinates; -}; -*/ -class Solution { -public: - int getImportance(vector employees, int id) { - Employee* e=employees[id-1]; - int res=e->importance; - for(int i=0;isubordinates.size();++i) - res+=getImportance(employees,e->subordinates[i]); - return res; - } -}; diff --git a/cpp/690.cpp b/cpp/690.cpp new file mode 100644 index 0000000..af3dced --- /dev/null +++ b/cpp/690.cpp @@ -0,0 +1,24 @@ +// dfs.cpp +/* +// Employee info +class Employee { +public: + // It's the unique ID of each node. + // unique id of this employee + int id; + // the importance value of this employee + int importance; + // the id of direct subordinates + vector subordinates; +}; +*/ +class Solution { +public: + int getImportance(vector employees, int id) { + Employee *e = employees[id - 1]; + int res = e->importance; + for (int i = 0; i < e->subordinates.size(); ++i) + res += getImportance(employees, e->subordinates[i]); + return res; + } +}; diff --git a/cpp/692.TopKFrequentWords/priority_queue.cpp b/cpp/692.TopKFrequentWords/priority_queue.cpp deleted file mode 100644 index 767c7b7..0000000 --- a/cpp/692.TopKFrequentWords/priority_queue.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { - struct cmp { - bool operator()(const pair&a,const pair&b) { - return a.second>b.second || (a.second == b.second&&a.first topKFrequent(vector& words, int k) { - unordered_maphashmap; - for (auto &str : words) - ++hashmap[str]; - priority_queue< pair, vector< pair >, cmp >pq; - auto it = hashmap.begin(); - for (int i = 0; ires(k); - cmp compare; - for (;it!=hashmap.end(); ++it) - if (compare(*it, pq.top())) { - pq.pop(); - pq.push(*it); - } - for(int i=k-1;i>=0;i--){ - res[i]=pq.top().first; - pq.pop(); - } - return res; - } -}; diff --git a/cpp/692.cpp b/cpp/692.cpp new file mode 100644 index 0000000..2974d77 --- /dev/null +++ b/cpp/692.cpp @@ -0,0 +1,31 @@ +// priority_queue.cpp +class Solution { + struct cmp { + bool operator()(const pair &a, const pair &b) { + return a.second > b.second || (a.second == b.second && a.first < b.first); + } + }; + +public: + vector topKFrequent(vector &words, int k) { + unordered_map hashmap; + for (auto &str : words) + ++hashmap[str]; + priority_queue, vector>, cmp> pq; + auto it = hashmap.begin(); + for (int i = 0; i < k; ++i) + pq.push(*it++); + vector res(k); + cmp compare; + for (; it != hashmap.end(); ++it) + if (compare(*it, pq.top())) { + pq.pop(); + pq.push(*it); + } + for (int i = k - 1; i >= 0; i--) { + res[i] = pq.top().first; + pq.pop(); + } + return res; + } +}; diff --git a/cpp/695.MaxAreaOfIsland/dfs.cpp b/cpp/695.MaxAreaOfIsland/dfs.cpp deleted file mode 100644 index 4256100..0000000 --- a/cpp/695.MaxAreaOfIsland/dfs.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { - int row,col; - int dfs(vector>&grid,vector>&visited,int i,int j){ - if(i<0||i>=row||j<0||j>=col||visited[i][j]||grid[i][j]==0) - return 0; - visited[i][j]=1; - return 1+dfs(grid,visited,i+1,j)+dfs(grid,visited,i,j+1)+dfs(grid,visited,i-1,j)+dfs(grid,visited,i,j-1); - } -public: - int maxAreaOfIsland(vector>& grid) { - row=grid.size(); - if(row==0)return 0; - col=grid[0].size(); - int maxArea=0; - vector>visited(row,vector(col,0)); - for(int i=0;i> &grid, vector> &visited, int i, + int j) { + if (i < 0 || i >= row || j < 0 || j >= col || visited[i][j] || + grid[i][j] == 0) + return 0; + visited[i][j] = 1; + return 1 + dfs(grid, visited, i + 1, j) + dfs(grid, visited, i, j + 1) + + dfs(grid, visited, i - 1, j) + dfs(grid, visited, i, j - 1); + } + +public: + int maxAreaOfIsland(vector> &grid) { + row = grid.size(); + if (row == 0) + return 0; + col = grid[0].size(); + int maxArea = 0; + vector> visited(row, vector(col, 0)); + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + if (visited[i][j] == 0 && grid[i][j] == 1) + maxArea = max(maxArea, dfs(grid, visited, i, j)); + return maxArea; + } +}; diff --git a/cpp/696.CountBinarySubstrings/simple.cpp b/cpp/696.CountBinarySubstrings/simple.cpp deleted file mode 100644 index 9118f8f..0000000 --- a/cpp/696.CountBinarySubstrings/simple.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { - int getCount(string &s,int l,int r,char lval){ - int len=1; - while(l-len>=0&&r+len= 0 && r + len < s.size() && s[l - len] == lval && + s[r + len] != lval) + len++; + return len; + } + +public: + int countBinarySubstrings(string s) { + int res = 0; + for (int i = 1; i < s.size(); ++i) + if (s[i - 1] != s[i]) + res += getCount(s, i - 1, i, s[i - 1]); + return res; + } +}; +// singleScan.cpp +class Solution2 { +public: + int countBinarySubstrings(string s) { + int pre = 0, cur = 1, res = 0; + for (int i = 1; i < s.size(); ++i) { + if (s[i] == s[i - 1]) + ++cur; + else { + pre = cur; + cur = 1; + } + if (cur <= pre) + ++res; + } + return res; + } +}; diff --git a/cpp/697.DegreeOfAnArray.cpp b/cpp/697.DegreeOfAnArray.cpp deleted file mode 100644 index c4b386e..0000000 --- a/cpp/697.DegreeOfAnArray.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -//Runtime: 28 ms, faster than 98.39% of C++ online submissions for Degree of an Array. -//Memory Usage: 12.4 MB, less than 92.00% of C++ online submissions for Degree of an Array. -public: - int findShortestSubArray(vector& nums) { - unordered_map>hashmap; - for(int i=0;isecond; - last=i; - ++count; - } - else{ - hashmap.insert({nums[i],{i,i,1}}); - } - } - auto ret = max_element(begin(hashmap),end(hashmap),[](const auto &a,const auto &b){ - if(get<2>(a.second)==get<2>(b.second)) return get<1>(a.second)-get<0>(a.second)>get<1>(b.second)-get<0>(b.second); - return get<2>(a.second)(b.second); - }); - return ret==end(hashmap)?0:get<1>(ret->second)-get<0>(ret->second)+1; - } -}; \ No newline at end of file diff --git a/cpp/697.cpp b/cpp/697.cpp new file mode 100644 index 0000000..38296be --- /dev/null +++ b/cpp/697.cpp @@ -0,0 +1,27 @@ +class Solution { + // Runtime: 28 ms, faster than 98.39% of C++ online submissions for Degree of + // an Array. Memory Usage: 12.4 MB, less than 92.00% of C++ online submissions + // for Degree of an Array. +public: + int findShortestSubArray(vector &nums) { + unordered_map> hashmap; + for (int i = 0; i < nums.size(); ++i) { + if (auto it = hashmap.find(nums[i]); it != end(hashmap)) { + auto &[first, last, count] = it->second; + last = i; + ++count; + } else { + hashmap.insert({nums[i], {i, i, 1}}); + } + } + auto ret = max_element(begin(hashmap), end(hashmap), + [](const auto &a, const auto &b) { + if (get<2>(a.second) == get<2>(b.second)) + return get<1>(a.second) - get<0>(a.second) > + get<1>(b.second) - get<0>(b.second); + return get<2>(a.second) < get<2>(b.second); + }); + return ret == end(hashmap) ? 0 + : get<1>(ret->second) - get<0>(ret->second) + 1; + } +}; \ No newline at end of file diff --git a/cpp/698.PartitionToKEqualSumSubsets.cpp b/cpp/698.PartitionToKEqualSumSubsets.cpp deleted file mode 100644 index c07a48c..0000000 --- a/cpp/698.PartitionToKEqualSumSubsets.cpp +++ /dev/null @@ -1,56 +0,0 @@ -class Solution { -//Runtime: 16 ms, faster than 44.02% of C++ online submissions for Partition to K Equal Sum Subsets. -//Memory Usage: 8.3 MB, less than 61.79% of C++ online submissions for Partition to K Equal Sum Subsets. -public: - bool canPartitionKSubsets(vector& nums, int k) { - int sum = accumulate(begin(nums),end(nums),0); - if(k <= 0 or sum%k != 0) return false; - vector visited(nums.size(), 0); - int target = sum/k; - functioncanPartition=[&](int start_index, int k, int cur_sum){ - if(k==1) - return true; - if(cur_sum == target) - return canPartition(0, k-1, 0); - for(int i = start_index; i& nums, int k) { - int sum = accumulate(begin(nums),end(nums),0); - sort(nums.begin(), nums.end(), greater()); - if (sum%k != 0) return false; - int target = sum/k; - vector buckets(k, 0); - function dfs=[&](int idx) { - if (idx == nums.size()) { - for (auto num:buckets) - if (num != target) return false; - return true; - } - for(auto &val:buckets) { - int curr = nums[idx]; - if (curr + val > target) continue; - val += curr; - if(dfs(idx+1)) - return true; - val -= curr; - if (val == 0) break; - } - return false; - }; - return dfs(0); - } -}; \ No newline at end of file diff --git a/cpp/698.cpp b/cpp/698.cpp new file mode 100644 index 0000000..f8730e6 --- /dev/null +++ b/cpp/698.cpp @@ -0,0 +1,63 @@ +class Solution { + // Runtime: 16 ms, faster than 44.02% of C++ online submissions for Partition + // to K Equal Sum Subsets. Memory Usage: 8.3 MB, less than 61.79% of C++ + // online submissions for Partition to K Equal Sum Subsets. +public: + bool canPartitionKSubsets(vector &nums, int k) { + int sum = accumulate(begin(nums), end(nums), 0); + if (k <= 0 or sum % k != 0) + return false; + vector visited(nums.size(), 0); + int target = sum / k; + function canPartition = [&](int start_index, int k, + int cur_sum) { + if (k == 1) + return true; + if (cur_sum == target) + return canPartition(0, k - 1, 0); + for (int i = start_index; i < nums.size(); i++) + if (!visited[i]) { + visited[i] = 1; + if (canPartition(i + 1, k, cur_sum + nums[i])) + return true; + visited[i] = 0; + } + return false; + }; + return canPartition(0, k, 0); + } +}; +class Solution2 { + // Runtime: 0 ms + // Memory Usage: 8.2 MB +public: + bool canPartitionKSubsets(vector &nums, int k) { + int sum = accumulate(begin(nums), end(nums), 0); + sort(nums.begin(), nums.end(), greater()); + if (sum % k != 0) + return false; + int target = sum / k; + vector buckets(k, 0); + function dfs = [&](int idx) { + if (idx == nums.size()) { + for (auto num : buckets) + if (num != target) + return false; + return true; + } + for (auto &val : buckets) { + int curr = nums[idx]; + if (curr + val > target) + continue; + val += curr; + if (dfs(idx + 1)) + return true; + val -= curr; + if (val == 0) + break; + } + return false; + }; + return dfs(0); + } +}; \ No newline at end of file diff --git a/cpp/7.ReverseInteger.cpp b/cpp/7.ReverseInteger.cpp deleted file mode 100644 index 2dc060f..0000000 --- a/cpp/7.ReverseInteger.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class SolutionA {// 15ms -public: - int reverse(int x) { - long long value=0; - bool neg=x>=0?0:1; - x=abs(x); - while(x>0){ - value=value*10+x%10; - x/=10; - } - value= neg==0?value:-value; - if(value<(int)0x80000000 || value> (int)0x7fffffff ) - return 0; - return value; - } -}; -class SolutionB { // 0ms 100% -public: - int reverse(int x) { - auto s=to_string(x<0?-(long long)x:x); - auto val=stoll(string{s.rbegin(),s.rend()}); - val = x<0?-val:val; - return (val>2147483647ll||val<-2147483648ll)?0:val; - } -}; \ No newline at end of file diff --git a/cpp/7.cpp b/cpp/7.cpp new file mode 100644 index 0000000..ff3efff --- /dev/null +++ b/cpp/7.cpp @@ -0,0 +1,25 @@ +class SolutionA { // 15ms +public: + int reverse(int x) { + long long value = 0; + bool neg = x >= 0 ? 0 : 1; + x = abs(x); + while (x > 0) { + value = value * 10 + x % 10; + x /= 10; + } + value = neg == 0 ? value : -value; + if (value < (int)0x80000000 || value > (int)0x7fffffff) + return 0; + return value; + } +}; +class SolutionB { // 0ms 100% +public: + int reverse(int x) { + auto s = to_string(x < 0 ? -(long long)x : x); + auto val = stoll(string{s.rbegin(), s.rend()}); + val = x < 0 ? -val : val; + return (val > 2147483647ll || val < -2147483648ll) ? 0 : val; + } +}; \ No newline at end of file diff --git a/cpp/70.ClimbingStairs/dp-0ms.cpp b/cpp/70.ClimbingStairs/dp-0ms.cpp deleted file mode 100644 index 243f201..0000000 --- a/cpp/70.ClimbingStairs/dp-0ms.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int climbStairs(int n) { - if(n<0)return 1; - vector dp(n+1); - dp[0]=1,dp[1]=1,dp[2]=2; - for(int i=2;i<=n;++i) - dp[i]=dp[i-1]+dp[i-2]; - return dp[n]; - } -}; diff --git a/cpp/70.cpp b/cpp/70.cpp new file mode 100644 index 0000000..240bde1 --- /dev/null +++ b/cpp/70.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int climbStairs(int n) { + if (n == 1) + return 1; + auto previous = make_pair(1, 2); + for (int i = 3; i <= n; ++i) { + previous = {previous.second, previous.first + previous.second}; + } + return previous.second; + } +}; \ No newline at end of file diff --git a/cpp/700.SearchInABinarySearchTree/recursion.cpp b/cpp/700.SearchInABinarySearchTree/recursion.cpp deleted file mode 100644 index f37c6cf..0000000 --- a/cpp/700.SearchInABinarySearchTree/recursion.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - TreeNode* searchBST(TreeNode* root, int val) { - if(!root) - return nullptr; - if(root->val == val) - return root; - else if(root->val > val) - return searchBST(root->left,val); - else if(root->val < val) - return searchBST(root->right,val); - } -}; diff --git a/cpp/700.cpp b/cpp/700.cpp new file mode 100644 index 0000000..5b955a7 --- /dev/null +++ b/cpp/700.cpp @@ -0,0 +1,23 @@ +// recursion.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode *searchBST(TreeNode *root, int val) { + if (!root) + return nullptr; + if (root->val == val) + return root; + else if (root->val > val) + return searchBST(root->left, val); + else if (root->val < val) + return searchBST(root->right, val); + } +}; diff --git a/cpp/701.InsertintoaBinarySearchTree.cpp b/cpp/701.InsertintoaBinarySearchTree.cpp deleted file mode 100644 index 836da2f..0000000 --- a/cpp/701.InsertintoaBinarySearchTree.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { //Runtime: 92 ms, faster than 84.56% of C++ online submissions for Insert into a Binary Search Tree. -public: - TreeNode* insertIntoBST(TreeNode* root, int val) { - if(!root) - return new TreeNode(val); - auto &target=root->val>val?root->left:root->right; - if(!target) - target=new TreeNode(val); - else - insertIntoBST(target,val); - return root; - } -}; \ No newline at end of file diff --git a/cpp/701.cpp b/cpp/701.cpp new file mode 100644 index 0000000..55fe7d9 --- /dev/null +++ b/cpp/701.cpp @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 92 ms, faster than 84.56% of C++ online submissions + // for Insert into a Binary Search Tree. +public: + TreeNode *insertIntoBST(TreeNode *root, int val) { + if (!root) + return new TreeNode(val); + auto &target = root->val > val ? root->left : root->right; + if (!target) + target = new TreeNode(val); + else + insertIntoBST(target, val); + return root; + } +}; \ No newline at end of file diff --git a/cpp/704.BinarySearch.cpp b/cpp/704.BinarySearch.cpp deleted file mode 100644 index 47a1520..0000000 --- a/cpp/704.BinarySearch.cpp +++ /dev/null @@ -1,8 +0,0 @@ -class Solution { // Runtime: 52 ms, faster than 87.93% of C++ online submissions for Binary Search. -public: - int search(vector& nums, int target) { - if(auto it=lower_bound(begin(nums),end(nums),target);it!=nums.end() and *it==target) - return it-nums.begin(); - return -1; - } -}; \ No newline at end of file diff --git a/cpp/704.cpp b/cpp/704.cpp new file mode 100644 index 0000000..0f8fd75 --- /dev/null +++ b/cpp/704.cpp @@ -0,0 +1,10 @@ +class Solution { // Runtime: 52 ms, faster than 87.93% of C++ online submissions + // for Binary Search. +public: + int search(vector &nums, int target) { + if (auto it = lower_bound(begin(nums), end(nums), target); + it != nums.end() and *it == target) + return it - nums.begin(); + return -1; + } +}; \ No newline at end of file diff --git a/cpp/705.DesignHashSet.cpp b/cpp/705.DesignHashSet.cpp deleted file mode 100644 index 9b9877f..0000000 --- a/cpp/705.DesignHashSet.cpp +++ /dev/null @@ -1,58 +0,0 @@ -class MyHashSet { - vector>m_buf=vector>(2); - int m_totalSize=0; - const int expandRatio=2; - int hashCode(int val,bool rebuild=false){ - return val%(rebuild?m_buf.size()*expandRatio:m_buf.size()); - } - void tryRebuild(){ - if(m_totalSize>new_buf(m_buf.size()*expandRatio); - for(auto &m:m_buf){ - for(auto &k:m){ - auto &m=new_buf[hashCode(k,true)]; - m.insert(k); - ++m_totalSize; - } - } - m_buf=move(new_buf); - } -public: - /** Initialize your data structure here. */ - MyHashSet() { - - } - - void add(int key) { - // tryRebuild(); - auto &m=m_buf[hashCode(key)]; - if(auto it=m.find(key);it==m.end()){ - m.insert(key); - ++m_totalSize; - } - } - - void remove(int key) { - auto &m=m_buf[hashCode(key)]; - if(auto it=m.find(key);it!=m.end()){ - m.erase(it); - --m_totalSize; - } - } - - /** Returns true if this set contains the specified element */ - bool contains(int key) { - auto &m=m_buf[hashCode(key)]; - return m.find(key)!=m.end(); - } -}; - -/** - * Your MyHashSet object will be instantiated and called as such: - * MyHashSet* obj = new MyHashSet(); - * obj->add(key); - * obj->remove(key); - * bool param_3 = obj->contains(key); - */ \ No newline at end of file diff --git a/cpp/705.cpp b/cpp/705.cpp new file mode 100644 index 0000000..88cd848 --- /dev/null +++ b/cpp/705.cpp @@ -0,0 +1,57 @@ +class MyHashSet { + vector> m_buf = vector>(2); + int m_totalSize = 0; + const int expandRatio = 2; + int hashCode(int val, bool rebuild = false) { + return val % (rebuild ? m_buf.size() * expandRatio : m_buf.size()); + } + void tryRebuild() { + if (m_totalSize < m_buf.size() * expandRatio * expandRatio) + return; + m_totalSize = 0; + vector> new_buf(m_buf.size() * expandRatio); + for (auto &m : m_buf) { + for (auto &k : m) { + auto &m = new_buf[hashCode(k, true)]; + m.insert(k); + ++m_totalSize; + } + } + m_buf = move(new_buf); + } + +public: + /** Initialize your data structure here. */ + MyHashSet() {} + + void add(int key) { + // tryRebuild(); + auto &m = m_buf[hashCode(key)]; + if (auto it = m.find(key); it == m.end()) { + m.insert(key); + ++m_totalSize; + } + } + + void remove(int key) { + auto &m = m_buf[hashCode(key)]; + if (auto it = m.find(key); it != m.end()) { + m.erase(it); + --m_totalSize; + } + } + + /** Returns true if this set contains the specified element */ + bool contains(int key) { + auto &m = m_buf[hashCode(key)]; + return m.find(key) != m.end(); + } +}; + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet* obj = new MyHashSet(); + * obj->add(key); + * obj->remove(key); + * bool param_3 = obj->contains(key); + */ \ No newline at end of file diff --git a/cpp/706.DesignHashMap.cpp b/cpp/706.DesignHashMap.cpp deleted file mode 100644 index d60e09f..0000000 --- a/cpp/706.DesignHashMap.cpp +++ /dev/null @@ -1,65 +0,0 @@ -class MyHashMap { //132ms 83.59% - vector>m_buf=vector>(2); - int m_totalSize=0; - const int expandRatio=2; - int hashCode(int val,bool rebuild=false){ - return val%(rebuild?m_buf.size()*expandRatio:m_buf.size()); - } - void tryRebuild(){ - if(m_totalSize>new_buf(m_buf.size()*expandRatio); - for(auto &m:m_buf){ - for(auto &[k,v]:m){ - auto &m=new_buf[hashCode(k,true)]; - m[k]=v; - ++m_totalSize; - } - } - m_buf=move(new_buf); - } -public: - /** Initialize your data structure here. */ - MyHashMap() { - - } - - /** value will always be non-negative. */ - void put(int key, int value) { - //tryRebuild(); - auto &m=m_buf[hashCode(key)]; - if(auto it=m.find(key);it==m.end()){ - m[key]=value; - ++m_totalSize; - } - else{ - it->second=value; - } - - } - - /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ - int get(int key) { - auto &m=m_buf[hashCode(key)]; - auto it=m.find(key); - return it==m.end()?-1:it->second; - } - - /** Removes the mapping of the specified value key if this map contains a mapping for the key */ - void remove(int key) { - auto &m=m_buf[hashCode(key)]; - if(auto it=m.find(key);it!=m.end()){ - m.erase(it); - --m_totalSize; - } - } -}; - -/** - * Your MyHashMap object will be instantiated and called as such: - * MyHashMap* obj = new MyHashMap(); - * obj->put(key,value); - * int param_2 = obj->get(key); - * obj->remove(key); - */ \ No newline at end of file diff --git a/cpp/706.cpp b/cpp/706.cpp new file mode 100644 index 0000000..43d6119 --- /dev/null +++ b/cpp/706.cpp @@ -0,0 +1,64 @@ +class MyHashMap { // 132ms 83.59% + vector> m_buf = vector>(2); + int m_totalSize = 0; + const int expandRatio = 2; + int hashCode(int val, bool rebuild = false) { + return val % (rebuild ? m_buf.size() * expandRatio : m_buf.size()); + } + void tryRebuild() { + if (m_totalSize < m_buf.size() * expandRatio * expandRatio) + return; + m_totalSize = 0; + vector> new_buf(m_buf.size() * expandRatio); + for (auto &m : m_buf) { + for (auto &[k, v] : m) { + auto &m = new_buf[hashCode(k, true)]; + m[k] = v; + ++m_totalSize; + } + } + m_buf = move(new_buf); + } + +public: + /** Initialize your data structure here. */ + MyHashMap() {} + + /** value will always be non-negative. */ + void put(int key, int value) { + // tryRebuild(); + auto &m = m_buf[hashCode(key)]; + if (auto it = m.find(key); it == m.end()) { + m[key] = value; + ++m_totalSize; + } else { + it->second = value; + } + } + + /** Returns the value to which the specified key is mapped, or -1 if this map + * contains no mapping for the key */ + int get(int key) { + auto &m = m_buf[hashCode(key)]; + auto it = m.find(key); + return it == m.end() ? -1 : it->second; + } + + /** Removes the mapping of the specified value key if this map contains a + * mapping for the key */ + void remove(int key) { + auto &m = m_buf[hashCode(key)]; + if (auto it = m.find(key); it != m.end()) { + m.erase(it); + --m_totalSize; + } + } +}; + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap* obj = new MyHashMap(); + * obj->put(key,value); + * int param_2 = obj->get(key); + * obj->remove(key); + */ \ No newline at end of file diff --git a/cpp/709.ToLowerCase/usingSTL.cpp b/cpp/709.ToLowerCase/usingSTL.cpp deleted file mode 100644 index 2684262..0000000 --- a/cpp/709.ToLowerCase/usingSTL.cpp +++ /dev/null @@ -1,7 +0,0 @@ -class Solution { -public: - string toLowerCase(string str) { - transform( str.begin(), str.end(), str.begin(), ptr_fun ( tolower ) ); - return str; - } -}; diff --git a/cpp/709.cpp b/cpp/709.cpp new file mode 100644 index 0000000..6d00872 --- /dev/null +++ b/cpp/709.cpp @@ -0,0 +1,8 @@ +// usingSTL.cpp +class Solution { +public: + string toLowerCase(string str) { + transform(str.begin(), str.end(), str.begin(), ptr_fun(tolower)); + return str; + } +}; diff --git a/cpp/71.SimplifyPath/vector.cpp b/cpp/71.SimplifyPath/vector.cpp deleted file mode 100644 index 5d5d205..0000000 --- a/cpp/71.SimplifyPath/vector.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - string simplifyPath(string path) { - stringstream ss(path); - string str,res; - vectorst; - while(getline(ss,str,'/')) - if(str==".."&&!st.empty()) - st.pop_back(); - else if(str=="."||str==""); - else if(str!="..") - st.push_back(str); - for(int i=0;i st; + while (getline(ss, str, '/')) + if (str == ".." && !st.empty()) + st.pop_back(); + else if (str == "." || str == "") + ; + else if (str != "..") + st.push_back(str); + for (int i = 0; i < st.size(); ++i) + res += "/" + st[i]; + return res == "" ? "/" : res; + } +}; diff --git a/cpp/712.MinimumAsciiDeleteSumForTwoStrings.cpp b/cpp/712.MinimumAsciiDeleteSumForTwoStrings.cpp deleted file mode 100644 index bca62a0..0000000 --- a/cpp/712.MinimumAsciiDeleteSumForTwoStrings.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -//Runtime: 32 ms, faster than 56.31% of C++ online submissions for Minimum ASCII Delete Sum for Two Strings. -//Memory Usage: 17.7 MB, less than 29.97% of C++ online submissions for Minimum ASCII Delete Sum for Two Strings. -public: - int minimumDeleteSum(string s1, string s2) { - vector>dp(s1.size()+1,vector(s2.size()+1)); - for(int i=1;i<=s1.size();++i) - dp[i][0]=dp[i-1][0]+s1[i-1]; - for(int i=1;i<=s2.size();++i) - dp[0][i]=dp[0][i-1]+s2[i-1]; - for(int i=1;i<=s1.size();++i) - for(int j=1;j<=s2.size();++j){ - if(s1[i-1]==s2[j-1]) - dp[i][j]=dp[i-1][j-1]; - else - dp[i][j]=min({dp[i][j-1]+s2[j-1], - dp[i-1][j-1]+s1[i-1]+s2[j-1], - dp[i-1][j]+s1[i-1]}); - } - return dp[s1.size()][s2.size()]; - } -}; \ No newline at end of file diff --git a/cpp/712.cpp b/cpp/712.cpp new file mode 100644 index 0000000..eda5e70 --- /dev/null +++ b/cpp/712.cpp @@ -0,0 +1,23 @@ +class Solution { + // Runtime: 32 ms, faster than 56.31% of C++ online submissions for Minimum + // ASCII Delete Sum for Two Strings. Memory Usage: 17.7 MB, less than 29.97% + // of C++ online submissions for Minimum ASCII Delete Sum for Two Strings. +public: + int minimumDeleteSum(string s1, string s2) { + vector> dp(s1.size() + 1, vector(s2.size() + 1)); + for (int i = 1; i <= s1.size(); ++i) + dp[i][0] = dp[i - 1][0] + s1[i - 1]; + for (int i = 1; i <= s2.size(); ++i) + dp[0][i] = dp[0][i - 1] + s2[i - 1]; + for (int i = 1; i <= s1.size(); ++i) + for (int j = 1; j <= s2.size(); ++j) { + if (s1[i - 1] == s2[j - 1]) + dp[i][j] = dp[i - 1][j - 1]; + else + dp[i][j] = min({dp[i][j - 1] + s2[j - 1], + dp[i - 1][j - 1] + s1[i - 1] + s2[j - 1], + dp[i - 1][j] + s1[i - 1]}); + } + return dp[s1.size()][s2.size()]; + } +}; \ No newline at end of file diff --git a/cpp/717.1-bitAnd2-bitCharacters/singleScan.cpp b/cpp/717.1-bitAnd2-bitCharacters/singleScan.cpp deleted file mode 100644 index 0171d83..0000000 --- a/cpp/717.1-bitAnd2-bitCharacters/singleScan.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - bool isOneBitCharacter(vector& bits) { - for(int i=0;i &bits) { + for (int i = 0; i < bits.size();) + if (bits[i] == 0) + if (i == bits.size() - 1) + return true; + else + ++i; + else + i += 2; + return false; + } +}; diff --git a/cpp/718.MaximumLengthOfRepeatedSubarray.cpp b/cpp/718.MaximumLengthOfRepeatedSubarray.cpp deleted file mode 100644 index 36c872c..0000000 --- a/cpp/718.MaximumLengthOfRepeatedSubarray.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -//Runtime: 188 ms -//Memory Usage: 106.4 MB -public: - int findLength(vector& A, vector& B) { - int m = A.size(), n = B.size(); - vector>dp(m+1, vector(n+1)); - int maxlen = 0; - for(int i = 1; i <= m; i++) - for(int j = 1; j <= n; j++){ - if(A[i-1] == B[j-1]){ - dp[i][j] = dp[i - 1][j - 1] + 1; - maxlen = max(maxlen, dp[i][j]); - } - } - return maxlen; - } -}; -// found an interesting solution https://leetcode.com/problems/maximum-length-of-repeated-subarray/solution/ -// named 'Binary Search with Rolling Hash' \ No newline at end of file diff --git a/cpp/718.cpp b/cpp/718.cpp new file mode 100644 index 0000000..7772905 --- /dev/null +++ b/cpp/718.cpp @@ -0,0 +1,21 @@ +class Solution { + // Runtime: 188 ms + // Memory Usage: 106.4 MB +public: + int findLength(vector &A, vector &B) { + int m = A.size(), n = B.size(); + vector> dp(m + 1, vector(n + 1)); + int maxlen = 0; + for (int i = 1; i <= m; i++) + for (int j = 1; j <= n; j++) { + if (A[i - 1] == B[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + maxlen = max(maxlen, dp[i][j]); + } + } + return maxlen; + } +}; +// found an interesting solution +// https://leetcode.com/problems/maximum-length-of-repeated-subarray/solution/ +// named 'Binary Search with Rolling Hash' \ No newline at end of file diff --git a/cpp/72.EditDistance.cpp b/cpp/72.EditDistance.cpp deleted file mode 100644 index c4e1dd5..0000000 --- a/cpp/72.EditDistance.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -//Runtime: 8 ms, faster than 96.76% of C++ online submissions for Edit Distance. -//Memory Usage: 11.4 MB, less than 15.14% of C++ online submissions for Edit Distance. -public: - int minDistance(string word1, string word2) { - int m = word1.size(), n = word2.size(); - vector> dp(m + 1, vector(n + 1, 0)); - for (int i = 1; i <= m; i++) - dp[i][0] = i; - for (int j = 1; j <= n; j++) - dp[0][j] = j; - for (int i = 1; i <= m; i++) - for (int j = 1; j <= n; j++) - dp[i][j] = word1[i - 1] == word2[j - 1] ? dp[i - 1][j - 1] : dp[i][j] = min({dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j]}) + 1; - return dp[m][n]; - } -}; \ No newline at end of file diff --git a/cpp/72.cpp b/cpp/72.cpp new file mode 100644 index 0000000..f13560e --- /dev/null +++ b/cpp/72.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minDistance(string word1, string word2) { + int m = word1.size(), n = word2.size(); + vector> dp(m + 1, vector(n + 1, 0)); + for (int i = 1; i <= m; i++) + dp[i][0] = i; + for (int j = 1; j <= n; j++) + dp[0][j] = j; + for (int i = 1; i <= m; i++) + for (int j = 1; j <= n; j++) + dp[i][j] = + word1[i - 1] == word2[j - 1] + ? dp[i - 1][j - 1] + : min({dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j]}) + + 1; + return dp[m][n]; + } +}; \ No newline at end of file diff --git a/cpp/720.LongestWordInDictionary/trie+45ms.cpp b/cpp/720.LongestWordInDictionary/trie+45ms.cpp deleted file mode 100644 index dff0480..0000000 --- a/cpp/720.LongestWordInDictionary/trie+45ms.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution { - struct trie{ - bool isWord=false; - trie *children[26]={}; - }root; -public: - - /** Inserts a word into the trie. */ - bool insert(string &word) { - trie *p=&root; - bool once=true; - trie*parent; - int child; - for(auto ch:word){ - int offset=ch-'a'; - if( p->children[offset]==nullptr){ - if(once){ - once=false; - p->children[offset]=new trie(); - parent=p; - child=offset; - } - else{ - delete parent->children[child]; - parent->children[child]=nullptr; - return false; - } - } - p=p->children[offset]; - } - p->isWord=true; - return true; - } -public: - string longestWord(vector& words) { - sort(words.begin(),words.end()); - string res=""; - for(auto &word:words) - if(insert(word)&&(word.size()>res.size()||(word.size()==res.size()&&wordchildren[offset]==nullptr) - if(i==word.size()-1) - p->children[offset]=new trie(); - else - return false; - p=p->children[offset]; - } - return true; - } -public: - string longestWord(vector& words) { - sort(words.begin(),words.end()); - string res=""; - for(auto &word:words) - if(insert(word)&&(word.size()>res.size()||(word.size()==res.size()&&wordchildren[offset] == nullptr) { + if (once) { + once = false; + p->children[offset] = new trie(); + parent = p; + child = offset; + } else { + delete parent->children[child]; + parent->children[child] = nullptr; + return false; + } + } + p = p->children[offset]; + } + p->isWord = true; + return true; + } + +public: + string longestWord(vector &words) { + sort(words.begin(), words.end()); + string res = ""; + for (auto &word : words) + if (insert(word) && (word.size() > res.size() || + (word.size() == res.size() && word < res))) + res = word; + return res; + } +}; +// trie+49ms.cpp +class Solution2 { + struct trie { + trie *children[26] = {}; + } root; + +public: + /** Inserts a word into the trie. */ + bool insert(string &word) { + trie *p = &root; + for (int i = 0; i < word.size(); ++i) { + int offset = word[i] - 'a'; + if (p->children[offset] == nullptr) + if (i == word.size() - 1) + p->children[offset] = new trie(); + else + return false; + p = p->children[offset]; + } + return true; + } + +public: + string longestWord(vector &words) { + sort(words.begin(), words.end()); + string res = ""; + for (auto &word : words) + if (insert(word) && (word.size() > res.size() || + (word.size() == res.size() && word < res))) + res = word; + return res; + } +}; diff --git a/cpp/722.RemoveComments/simple.cpp b/cpp/722.RemoveComments/simple.cpp deleted file mode 100644 index 0f7288c..0000000 --- a/cpp/722.RemoveComments/simple.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution { -public: - vector removeComments(vector& source) { - string temp; - vectorres; - int start = 0,i,j; - bool star = false; - for (i = 0; i removeComments(vector &source) { + string temp; + vector res; + int start = 0, i, j; + bool star = false; + for (i = 0; i < source.size(); ++i) { + for (j = 0; j < source[i].size(); ++j) { + if (!star && source[i][j] == '/' && j + 1 < source[i].size()) { + if (source[i][j + 1] == '/') + break; + else if (source[i][j + 1] == '*') { + star = true; + temp += source[i].substr(start, j - start); + ++j; + } + } else if (star && source[i][j] == '*' && j + 1 < source[i].size() && + source[i][j + 1] == '/') { + star = false; + ++j; + start = j + 1; + } + } + if (!star) { + temp += source[i].substr(start, j - start); + if (temp.size()) + res.emplace_back(move(temp)); + start = 0; + } + } + return res; + } +}; diff --git a/cpp/724.FindPivotIndex/doubleScan.cpp b/cpp/724.FindPivotIndex/doubleScan.cpp deleted file mode 100644 index 16d5db3..0000000 --- a/cpp/724.FindPivotIndex/doubleScan.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int pivotIndex(vector& nums) { - nums.push_back(0); - int n=nums.size()-1,i=0,right=accumulate(nums.begin()+1,nums.end(),0),left=0; - while(i &nums) { + nums.push_back(0); + int n = nums.size() - 1, i = 0, + right = accumulate(nums.begin() + 1, nums.end(), 0), left = 0; + while (i < n && left != right) { + left += nums[i++]; + right -= nums[i]; + } + return left == right && i < n ? i : -1; + } +}; diff --git a/cpp/728.SelfDividingNumbers/bruteForce.cpp b/cpp/728.SelfDividingNumbers/bruteForce.cpp deleted file mode 100644 index e3814af..0000000 --- a/cpp/728.SelfDividingNumbers/bruteForce.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { - bool selfDividing(int num){ - int remain=num; - while(remain){ - int mod=remain%10; - if(mod==0||num%mod!=0) - return false; - remain/=10; - } - return true; - } -public: - vector selfDividingNumbers(int left, int right) { - vectorres; - for(int i=left;i<=right;++i) - if(selfDividing(i)) - res.push_back(i); - return res; - } -}; diff --git a/cpp/728.cpp b/cpp/728.cpp new file mode 100644 index 0000000..286e975 --- /dev/null +++ b/cpp/728.cpp @@ -0,0 +1,22 @@ +// bruteForce.cpp +class Solution { + bool selfDividing(int num) { + int remain = num; + while (remain) { + int mod = remain % 10; + if (mod == 0 || num % mod != 0) + return false; + remain /= 10; + } + return true; + } + +public: + vector selfDividingNumbers(int left, int right) { + vector res; + for (int i = left; i <= right; ++i) + if (selfDividing(i)) + res.push_back(i); + return res; + } +}; diff --git a/cpp/73.SetMatrixZeroes/inplace.cpp b/cpp/73.SetMatrixZeroes/inplace.cpp deleted file mode 100644 index 6d8f853..0000000 --- a/cpp/73.SetMatrixZeroes/inplace.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution { -public: - void setZeroes(vector>& matrix) { - int row=matrix.size(); - if(row==0) - return; - int col=matrix[0].size(); - bool allZero=matrix[0][0]==0,rowZero=0,colZero=0; - for(int i=0;i(col,0); - if(colZero) - for(int i=0;i> &matrix) { + int row = matrix.size(); + if (row == 0) + return; + int col = matrix[0].size(); + bool allZero = matrix[0][0] == 0, rowZero = 0, colZero = 0; + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + if (matrix[i][j] == 0) { + rowZero = i == 0 ? true : rowZero; + colZero = j == 0 ? true : colZero; + matrix[i][0] = matrix[0][j] = 0; + } + for (int i = 1; i < row; ++i) + for (int j = 1; j < col; ++j) + if (matrix[0][j] == 0 || matrix[i][0] == 0) + matrix[i][j] = 0; + if (allZero) + colZero = rowZero = 1; + if (rowZero) + matrix[0] = vector(col, 0); + if (colZero) + for (int i = 0; i < row; ++i) + matrix[i][0] = 0; + } +}; diff --git a/cpp/733.FloodFill/bfs.cpp b/cpp/733.FloodFill/bfs.cpp deleted file mode 100644 index 86e89bc..0000000 --- a/cpp/733.FloodFill/bfs.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { - const int dirx[4]={0,1,0,-1}; - const int diry[4]={1,0,-1,0}; -public: - vector> floodFill(vector>& image, int sr, int sc, int newColor) { - deque>dq; - dq.push_back( make_pair(sr,sc) ); - int color=image[sr][sc]; - if(color==newColor) - return image; - image[sr][sc]=newColor; - int row=image.size(),col=image[0].size(); - while(!dq.empty()){ - auto point=dq.front(); - dq.pop_front(); - for(int i=0;i<4;++i){ - int x=point.first+dirx[i],y=point.second+diry[i]; - if(x>=0&&x=0&&y> floodFill(vector> &image, int sr, int sc, + int newColor) { + deque> dq; + dq.push_back(make_pair(sr, sc)); + int color = image[sr][sc]; + if (color == newColor) + return image; + image[sr][sc] = newColor; + int row = image.size(), col = image[0].size(); + while (!dq.empty()) { + auto point = dq.front(); + dq.pop_front(); + for (int i = 0; i < 4; ++i) { + int x = point.first + dirx[i], y = point.second + diry[i]; + if (x >= 0 && x < row && y >= 0 && y < col && image[x][y] == color) { + image[x][y] = newColor; + dq.push_back(make_pair(x, y)); + } + } + } + return image; + } +}; diff --git a/cpp/734.SentenceSimilarity/hashmap.cpp b/cpp/734.SentenceSimilarity/hashmap.cpp deleted file mode 100644 index a77378e..0000000 --- a/cpp/734.SentenceSimilarity/hashmap.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { - if(words1.size()!=words2.size()) - return false; - unordered_map>hashmap; - for(auto &p:pairs){ - hashmap[p.first].insert(p.second); - hashmap[p.second].insert(p.first); - } - for(int i=0;i &words1, vector &words2, + vector> pairs) { + if (words1.size() != words2.size()) + return false; + unordered_map> hashmap; + for (auto &p : pairs) { + hashmap[p.first].insert(p.second); + hashmap[p.second].insert(p.first); + } + for (int i = 0; i < words1.size(); ++i) + if (hashmap[words1[i]].find(words2[i]) == hashmap[words1[i]].end() && + words1[i] != words2[i]) + return false; + return true; + } +}; diff --git a/cpp/739.DailyTemperatures/stack.cpp b/cpp/739.DailyTemperatures/stack.cpp deleted file mode 100644 index d550fd5..0000000 --- a/cpp/739.DailyTemperatures/stack.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - vector dailyTemperatures(vector& temperatures) { - stack>st; - vectorres(temperatures.size(),0); - for(int i=0;i dailyTemperatures(vector &temperatures) { + stack> st; + vector res(temperatures.size(), 0); + for (int i = 0; i < temperatures.size(); ++i) { + while (st.size() && st.top().second < temperatures[i]) { + int index = st.top().first; + res[index] = i - index; + st.pop(); + } + st.push(make_pair(i, temperatures[i])); + } + return res; + } +}; diff --git a/cpp/74.SearchA2DMatrix/1-9ms.cpp b/cpp/74.SearchA2DMatrix/1-9ms.cpp deleted file mode 100644 index 7d05eb5..0000000 --- a/cpp/74.SearchA2DMatrix/1-9ms.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - int row=matrix.size(); - if(row==0)return 0; - int col=matrix[0].size(); - int j=col-1,i=0; - while(i=0){ - if(matrix[i][j]>target) - --j; - else if(matrix[i][j]>& matrix, int target) { + int row = matrix.size(); + if (row == 0) + return 0; + int col = matrix[0].size(); + int j = col - 1, i = 0; + while (i < row && j >= 0) { + if (matrix[i][j] > target) + --j; + else if (matrix[i][j] < target) + ++i; + else + return 1; + } + return 0; + } +}; +class SolutionStdlib { +public: + bool searchMatrix(vector>& matrix, int target) { + auto rowIt = lower_bound(matrix.begin(), matrix.end(), target, + [](const vector& v, int target) { + return v.front() < target; + }); + if (rowIt != matrix.end() && rowIt->front() == target) + return true; + if (rowIt == matrix.begin()) + return false; + rowIt -= 1; + auto colIt = lower_bound(rowIt->begin(), rowIt->end(), target); + return colIt != rowIt->end() && *colIt == target; + } +}; \ No newline at end of file diff --git a/cpp/740.DeleteAndEarn.cpp b/cpp/740.DeleteAndEarn.cpp deleted file mode 100644 index 8acdcc8..0000000 --- a/cpp/740.DeleteAndEarn.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution { -//dfs Time Limit Exceeded -//[12,32,93,17,100,72,40,71,37,92,58,34,29,78,11,84,77,90,92,35,12,5,27,92,91,23,65,91,85,14,42,28,80,85,38,71,62,82,66,3,33,33,55,60,48,78,63,11,20,51,78,42,37,21,100,13,60,57,91,53,49,15,45,19,51,2,96,22,32,2,46,62,58,11,29,6,74,38,70,97,4,22,76,19,1,90,63,55,64,44,90,51,36,16,65,95,64,59,53,93] -public: - int deleteAndEarn(vector& nums) { - unordered_map counter; - for(auto num:nums) - counter[num]++; - unordered_setused; - using itr=decltype(counter)::iterator; - int ret=0; - function dfs=[&dfs,&used,&ret](itr first,itr last,int sum){ - if(first==last){ - ret=max(ret,sum); - return; - } - if(not used.count(first->first+1) and not used.count(first->first-1)){ - auto it=used.insert(first->first); - auto itr=first; - dfs(++itr,last,first->first*first->second+sum); - used.erase(it.first); - } - dfs(++first,last,sum); - }; - dfs(begin(counter),end(counter),0); - return ret; - } -}; -class Solution { -//Runtime: 8 ms, faster than 94.04% of C++ online submissions for Delete and Earn. -//Memory Usage: 11.2 MB, less than 31.37% of C++ online submissions for Delete and Earn. -public: - int deleteAndEarn(vector& nums) { - int n = 10001; - vector values(n, 0); - for (int num : nums) - values[num] += num; - int take = 0, skip = 0; - for (int i = 0; i < n; i++) { - int takei = skip + values[i]; - int skipi = max(skip, take); - take = takei; - skip = skipi; - } - return max(take, skip); - } -}; \ No newline at end of file diff --git a/cpp/740.cpp b/cpp/740.cpp new file mode 100644 index 0000000..cc4a02a --- /dev/null +++ b/cpp/740.cpp @@ -0,0 +1,50 @@ +class Solution { + // dfs Time Limit Exceeded + //[12,32,93,17,100,72,40,71,37,92,58,34,29,78,11,84,77,90,92,35,12,5,27,92,91,23,65,91,85,14,42,28,80,85,38,71,62,82,66,3,33,33,55,60,48,78,63,11,20,51,78,42,37,21,100,13,60,57,91,53,49,15,45,19,51,2,96,22,32,2,46,62,58,11,29,6,74,38,70,97,4,22,76,19,1,90,63,55,64,44,90,51,36,16,65,95,64,59,53,93] +public: + int deleteAndEarn(vector &nums) { + unordered_map counter; + for (auto num : nums) + counter[num]++; + unordered_set used; + using itr = decltype(counter)::iterator; + int ret = 0; + function dfs = [&dfs, &used, &ret](itr first, itr last, + int sum) { + if (first == last) { + ret = max(ret, sum); + return; + } + if (not used.count(first->first + 1) and + not used.count(first->first - 1)) { + auto it = used.insert(first->first); + auto itr = first; + dfs(++itr, last, first->first * first->second + sum); + used.erase(it.first); + } + dfs(++first, last, sum); + }; + dfs(begin(counter), end(counter), 0); + return ret; + } +}; +class Solution2 { + // Runtime: 8 ms, faster than 94.04% of C++ online submissions for Delete and + // Earn. Memory Usage: 11.2 MB, less than 31.37% of C++ online submissions for + // Delete and Earn. +public: + int deleteAndEarn(vector &nums) { + int n = 10001; + vector values(n, 0); + for (int num : nums) + values[num] += num; + int take = 0, skip = 0; + for (int i = 0; i < n; i++) { + int takei = skip + values[i]; + int skipi = max(skip, take); + take = takei; + skip = skipi; + } + return max(take, skip); + } +}; \ No newline at end of file diff --git a/cpp/744.FindSmallestLetterGreaterThanTarget/upper_bound.cpp b/cpp/744.FindSmallestLetterGreaterThanTarget/upper_bound.cpp deleted file mode 100644 index 98ad283..0000000 --- a/cpp/744.FindSmallestLetterGreaterThanTarget/upper_bound.cpp +++ /dev/null @@ -1,7 +0,0 @@ -class Solution { -public: - char nextGreatestLetter(vector& letters, char target) { - auto it=upper_bound(letters.begin(),letters.end(),target); - return it==letters.end()?letters.front():*it; - } -}; diff --git a/cpp/744.cpp b/cpp/744.cpp new file mode 100644 index 0000000..f830724 --- /dev/null +++ b/cpp/744.cpp @@ -0,0 +1,8 @@ +// upper_bound.cpp +class Solution { +public: + char nextGreatestLetter(vector &letters, char target) { + auto it = upper_bound(letters.begin(), letters.end(), target); + return it == letters.end() ? letters.front() : *it; + } +}; diff --git a/cpp/746.MinCostClimbingStairs/dp.cpp b/cpp/746.MinCostClimbingStairs/dp.cpp deleted file mode 100644 index 741ba34..0000000 --- a/cpp/746.MinCostClimbingStairs/dp.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - int minCostClimbingStairs(vector& cost) { - vectordp(cost.size()+1,0); - dp[0]=cost[0]; - dp[1]=cost[1]; - cost.push_back(0); - for(int i=2;i &cost) { + vector dp(cost.size() + 1, 0); + dp[0] = cost[0]; + dp[1] = cost[1]; + cost.push_back(0); + for (int i = 2; i < dp.size(); ++i) + dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]; + cost.pop_back(); + return dp.back(); + } +}; diff --git a/cpp/747.LargestNumberAtLeastTwiceOfOthers/simple.cpp b/cpp/747.LargestNumberAtLeastTwiceOfOthers/simple.cpp deleted file mode 100644 index 79cb1b4..0000000 --- a/cpp/747.LargestNumberAtLeastTwiceOfOthers/simple.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int dominantIndex(vector& nums) { - auto it=max_element(begin(nums),end(nums)); - if(it==nums.end()) - return -1; - for(auto num:nums) - if(2*num>*it&&num!=*it) - return -1; - return distance(nums.begin(),it); - } -}; diff --git a/cpp/747.cpp b/cpp/747.cpp new file mode 100644 index 0000000..3b2604a --- /dev/null +++ b/cpp/747.cpp @@ -0,0 +1,13 @@ +// simple.cpp +class Solution { +public: + int dominantIndex(vector &nums) { + auto it = max_element(begin(nums), end(nums)); + if (it == nums.end()) + return -1; + for (auto num : nums) + if (2 * num > *it && num != *it) + return -1; + return distance(nums.begin(), it); + } +}; diff --git a/cpp/748.ShortestCompletingWord.cpp b/cpp/748.ShortestCompletingWord.cpp deleted file mode 100644 index f5d407e..0000000 --- a/cpp/748.ShortestCompletingWord.cpp +++ /dev/null @@ -1,55 +0,0 @@ -class Solution { //Runtime: 20 ms, faster than 80.96% of C++ online submissions for Shortest Completing Word. -public: - string shortestCompletingWord(string licensePlate, vector& words) { - vector cntlic(26, 0); - for (auto ch : licensePlate) - if (isalpha(ch)) - ++cntlic[tolower(ch) - 'a']; - string res="aaaaaaaaaaaaaaaa"; // the problem says max len is 15 - for (const auto& str : words) { - if(str.size()>res.size()) - continue; - vector cnt=cntlic; - for (const auto ch : str) - --cnt[ch - 'a']; - auto it=find_if(cnt.begin(),cnt.end(),[](const int val){ - return val>0; - }); - if (it==cnt.end() && str.length() < res.size()) - res = str; - } - return res; - } -}; -class Solution { // Runtime: 16 ms -public: - string shortestCompletingWord(string licensePlate, vector& words) { - vector cntlic(26, 0); - for (auto ch : licensePlate) { - if (isalpha(ch)) { - ++cntlic[tolower(ch) - 'a']; - } - } - // auto minL = numeric_limits::max(); - string res="aaaaaaaaaaaaaaaa"; - for (const auto& str : words) { - vector cnt(26, 0); - for (const auto ch : str) { - ++cnt[ch - 'a']; - } - bool complete = true; - for (int i = 0; i < 26; ++i) { - if (cnt[i] < cntlic[i]) { - complete = false; - break; - } - } - if (complete && str.length() < res.size()) { - res = str; - // minL = str.length(); - } - } - - return res; - } -}; \ No newline at end of file diff --git a/cpp/748.cpp b/cpp/748.cpp new file mode 100644 index 0000000..cf75645 --- /dev/null +++ b/cpp/748.cpp @@ -0,0 +1,55 @@ +class Solution { // Runtime: 20 ms, faster than 80.96% of C++ online submissions + // for Shortest Completing Word. +public: + string shortestCompletingWord(string licensePlate, vector &words) { + vector cntlic(26, 0); + for (auto ch : licensePlate) + if (isalpha(ch)) + ++cntlic[tolower(ch) - 'a']; + string res = "aaaaaaaaaaaaaaaa"; // the problem says max len is 15 + for (const auto &str : words) { + if (str.size() > res.size()) + continue; + vector cnt = cntlic; + for (const auto ch : str) + --cnt[ch - 'a']; + auto it = find_if(cnt.begin(), cnt.end(), + [](const int val) { return val > 0; }); + if (it == cnt.end() && str.length() < res.size()) + res = str; + } + return res; + } +}; +class Solution2 { // Runtime: 16 ms +public: + string shortestCompletingWord(string licensePlate, vector &words) { + vector cntlic(26, 0); + for (auto ch : licensePlate) { + if (isalpha(ch)) { + ++cntlic[tolower(ch) - 'a']; + } + } + // auto minL = numeric_limits::max(); + string res = "aaaaaaaaaaaaaaaa"; + for (const auto &str : words) { + vector cnt(26, 0); + for (const auto ch : str) { + ++cnt[ch - 'a']; + } + bool complete = true; + for (int i = 0; i < 26; ++i) { + if (cnt[i] < cntlic[i]) { + complete = false; + break; + } + } + if (complete && str.length() < res.size()) { + res = str; + // minL = str.length(); + } + } + + return res; + } +}; \ No newline at end of file diff --git a/cpp/75.SortColors.cpp b/cpp/75.SortColors.cpp deleted file mode 100644 index ac362bb..0000000 --- a/cpp/75.SortColors.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Sort Colors. -//Memory Usage: 8.7 MB, less than 14.74% of C++ online submissions for Sort Colors. -public: - void sortColors(vector& nums) { - int i=0,j=nums.size()-1; - int cur=i; - while(cur<=j){ - while(cur<=j&&nums[cur]==0) - swap(nums[cur++],nums[i++]); - while(cur<=j&&nums[cur]==1) - ++cur; - while(cur<=j&&nums[cur]==2) - swap(nums[cur],nums[j--]); - } - } -}; \ No newline at end of file diff --git a/cpp/75.cpp b/cpp/75.cpp new file mode 100644 index 0000000..762f776 --- /dev/null +++ b/cpp/75.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + void sortColors(vector& nums) { + int i = 0, j = nums.size() - 1; + int cur = i; + while (cur <= j) { + while (cur <= j && nums[cur] == 0) + swap(nums[cur++], nums[i++]); + while (cur <= j && nums[cur] == 1) + ++cur; + while (cur <= j && nums[cur] == 2) + swap(nums[cur], nums[j--]); + } + } +}; +class Solution2 { +public: + void sortColors(vector& nums) { + for (int i = 0, l = 0, r = nums.size() - 1; i <= r;) { + switch (nums[i]) { + case 0: + swap(nums[i], nums[l++]); + case 1: + i++; + break; + case 2: + swap(nums[i], nums[r--]); + break; + } + } + } +}; \ No newline at end of file diff --git a/cpp/76.MinimumWindowSubstring/hashmap.cpp b/cpp/76.MinimumWindowSubstring/hashmap.cpp deleted file mode 100644 index 2d0f493..0000000 --- a/cpp/76.MinimumWindowSubstring/hashmap.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution { - bool allContain(unordered_map&hash){ - for(auto p:hash) - if(p.second>0) - return 0; - return 1; - } -public: - string minWindow(string s, string t) { - int l=0,r=0,minLen=0x7fffffff,start; - unordered_maphash; - for(char ch:t) - hash[ch]++; - unordered_map::iterator it; - while(rsecond--; - while(lsecond++; - } - } - return minLen==0x7fffffff?"":s.substr(start,minLen); - } -}; diff --git a/cpp/76.MinimumWindowSubstring/simple.cpp b/cpp/76.MinimumWindowSubstring/simple.cpp deleted file mode 100644 index dd56f28..0000000 --- a/cpp/76.MinimumWindowSubstring/simple.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution { - bool allContain(vector&arr){ - for(auto num:arr) - if(num>0) - return 0; - return 1; - } -public: - string minWindow(string s, string t) { - int l=0,r=0,minLen=0x7fffffff,start; - vectorhash(128); - for(char ch:t) - hash[ch]++; - while(r &hash) { + for (auto p : hash) + if (p.second > 0) + return 0; + return 1; + } + +public: + string minWindow(string s, string t) { + int l = 0, r = 0, minLen = 0x7fffffff, start; + unordered_map hash; + for (char ch : t) + hash[ch]++; + unordered_map::iterator it; + while (r < s.size() || allContain(hash)) { + while (r < s.size() && !allContain(hash)) + if ((it = hash.find(s[r++])) != hash.end()) + it->second--; + while (l < r && allContain(hash)) { + if (r - l < minLen) { + minLen = r - l; + start = l; + } + if ((it = hash.find(s[l++])) != hash.end()) + it->second++; + } + } + return minLen == 0x7fffffff ? "" : s.substr(start, minLen); + } +}; +// simple.cpp +class Solution2 { + bool allContain(vector &arr) { + for (auto num : arr) + if (num > 0) + return 0; + return 1; + } + +public: + string minWindow(string s, string t) { + int l = 0, r = 0, minLen = 0x7fffffff, start; + vector hash(128); + for (char ch : t) + hash[ch]++; + while (r < s.size() || allContain(hash)) { + while (r < s.size() && !allContain(hash)) + hash[s[r++]]--; + while (l < r && allContain(hash)) { + if (r - l < minLen) { + minLen = r - l; + start = l; + } + hash[s[l++]]++; + } + } + return minLen == 0x7fffffff ? "" : s.substr(start, minLen); + } +}; +class Solution3 { +public: + string minWindow(string s, string t) { + unordered_map tMap; + for (char c : t) + tMap[c]++; + int i = 0; + string res = s + ' '; + while(i < s.size() && tMap.find(s[i]) == tMap.end()) + ++i; + auto moveLeftWindUtilNotMatch = [&tMap, &s](int &i, const int j) { + for (;i <= j; ++i) { + if (auto it = tMap.find(s[i]); it != tMap.end()) { + if (++it->second > 0) { + ++i; + break; + } + } + } + }; + for (int j = i, matchCnt = 0; j < s.size(); ++j) { + if (tMap.find(s[j]) != tMap.end() && --tMap[s[j]] == 0) { + matchCnt++; + if (matchCnt == tMap.size()) { + moveLeftWindUtilNotMatch(i, j); + matchCnt--; + if (j - i + 2 < res.length()) { + res = s.substr(i - 1, j - i + 2); + } + } + } + } + return res.size() > s.size() ? "" : res; + } +}; \ No newline at end of file diff --git a/cpp/762.PrimeNumberOfSetBitsInBinaryRepresentation/memorySearch.cpp b/cpp/762.PrimeNumberOfSetBitsInBinaryRepresentation/memorySearch.cpp deleted file mode 100644 index 81937c8..0000000 --- a/cpp/762.PrimeNumberOfSetBitsInBinaryRepresentation/memorySearch.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { - int memorySearch(unordered_map&hashmap,int val){ - auto it=hashmap.find(val); - if(it==hashmap.end()) - return hashmap[val]=memorySearch(hashmap,val&(val-1))+1; - return it->second; - } -public: - int countPrimeSetBits(int L, int R) { - int isPrime[21]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0}; - unordered_maphashmap; - hashmap[0]=0; - int count=0; - for(int i=L;i<=R;++i) - if(isPrime[memorySearch(hashmap,i)]) - ++count; - return count; - } -}; diff --git a/cpp/762.cpp b/cpp/762.cpp new file mode 100644 index 0000000..36dd301 --- /dev/null +++ b/cpp/762.cpp @@ -0,0 +1,22 @@ +// memorySearch.cpp +class Solution { + int memorySearch(unordered_map &hashmap, int val) { + auto it = hashmap.find(val); + if (it == hashmap.end()) + return hashmap[val] = memorySearch(hashmap, val & (val - 1)) + 1; + return it->second; + } + +public: + int countPrimeSetBits(int L, int R) { + int isPrime[21] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, + 1, 0, 1, 0, 0, 0, 1, 0, 1, 0}; + unordered_map hashmap; + hashmap[0] = 0; + int count = 0; + for (int i = L; i <= R; ++i) + if (isPrime[memorySearch(hashmap, i)]) + ++count; + return count; + } +}; diff --git a/cpp/763.PartitionLabels.cpp b/cpp/763.PartitionLabels.cpp deleted file mode 100644 index 6f6e00f..0000000 --- a/cpp/763.PartitionLabels.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -// Runtime: 4 ms, faster than 97.92% of C++ online submissions for Partition Labels. -// Memory Usage: 8.7 MB, less than 73.77% of C++ online submissions for Partition Labels. -public: - vector partitionLabels(string S) { - vector res, pos(26, 0); - for (auto i = 0; i < S.size(); ++i) - pos[S[i] - 'a'] = i; - for (auto i = 0, idx = INT_MIN, last_i = 0; i < S.size(); ++i) { - idx = max(idx, pos[S[i] - 'a']); - if (idx == i) - res.push_back(i - exchange(last_i, i + 1) + 1); - } - return res; - } -}; \ No newline at end of file diff --git a/cpp/763.cpp b/cpp/763.cpp new file mode 100644 index 0000000..122c9e0 --- /dev/null +++ b/cpp/763.cpp @@ -0,0 +1,17 @@ +class Solution { + // Runtime: 4 ms, faster than 97.92% of C++ online submissions for Partition + // Labels. Memory Usage: 8.7 MB, less than 73.77% of C++ online submissions + // for Partition Labels. +public: + vector partitionLabels(string S) { + vector res, pos(26, 0); + for (auto i = 0; i < S.size(); ++i) + pos[S[i] - 'a'] = i; + for (auto i = 0, idx = INT_MIN, last_i = 0; i < S.size(); ++i) { + idx = max(idx, pos[S[i] - 'a']); + if (idx == i) + res.push_back(i - exchange(last_i, i + 1) + 1); + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/766.ToeplitzMatrix/smart.cpp b/cpp/766.ToeplitzMatrix/smart.cpp deleted file mode 100644 index ca2b469..0000000 --- a/cpp/766.ToeplitzMatrix/smart.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - bool isToeplitzMatrix(vector>& matrix) { - for(int i=1;i> &matrix) { + for (int i = 1; i < matrix.size(); ++i) + for (int j = 1; j < matrix[i].size(); ++j) + if (matrix[i][j] != matrix[i - 1][j - 1]) + return false; + return true; + } +}; diff --git a/cpp/77.Combinations/dfs.cpp b/cpp/77.Combinations/dfs.cpp deleted file mode 100644 index f871508..0000000 --- a/cpp/77.Combinations/dfs.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - vector> combine(int n, int k) { - vectorcur; - vector>res; - dfs(cur,res,1,n,k); - return res; - } - void dfs(vector&cur,vector>&res,int i,int n,int k){ - if(cur.size()==k){ - res.push_back(cur); - return; - } - for(;i<=n;++i){ - cur.push_back(i); - dfs(cur,res,i+1,n,k); - cur.pop_back(); - } - } -}; diff --git a/cpp/77.Combinations/iteration.cpp b/cpp/77.Combinations/iteration.cpp deleted file mode 100644 index b0829d0..0000000 --- a/cpp/77.Combinations/iteration.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - vector> combine(int n, int k) { - vector> result; - int i = 0; - vector p(k, 0); - while (i >= 0) { - p[i]++; - if (p[i] > n) --i; - else if (i == k - 1) result.push_back(p); - else { - ++i; - p[i] = p[i - 1]; - } - } - return result; - } -}; diff --git a/cpp/77.cpp b/cpp/77.cpp new file mode 100644 index 0000000..9f2def4 --- /dev/null +++ b/cpp/77.cpp @@ -0,0 +1,43 @@ +// dfs.cpp +class Solution { + void dfs(vector& cur, vector>& res, int i, int n, int k) { + if (0 == k) { + res.push_back(cur); + return; + } + for (; i <= n && n - i + 1 >= k; ++i) { + cur.push_back(i); + dfs(cur, res, i + 1, n, k - 1); + cur.pop_back(); + } + } + +public: + vector> combine(int n, int k) { + vector cur; + vector> res; + dfs(cur, res, 1, n, k); + return res; + } +}; +// iteration.cpp +class Solution2 { +public: + vector> combine(int n, int k) { + vector> result; + int i = 0; + vector p(k, 0); + while (i >= 0) { + p[i]++; + if (p[i] > n) + --i; + else if (i == k - 1) + result.push_back(p); + else { + ++i; + p[i] = p[i - 1]; + } + } + return result; + } +}; diff --git a/cpp/771.JewelsAndStones/hashset.cpp b/cpp/771.JewelsAndStones/hashset.cpp deleted file mode 100644 index 0b23739..0000000 --- a/cpp/771.JewelsAndStones/hashset.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - int numJewelsInStones(string J, string S) { - int res=0; - unordered_sethashset(J.begin(),J.end()); - for(char ch:S) - if(hashset.find(ch)!=hashset.end()) - ++res; - return res; - } -}; diff --git a/cpp/771.cpp b/cpp/771.cpp new file mode 100644 index 0000000..c9647ac --- /dev/null +++ b/cpp/771.cpp @@ -0,0 +1,12 @@ +// hashset.cpp +class Solution { +public: + int numJewelsInStones(string J, string S) { + int res = 0; + unordered_set hashset(J.begin(), J.end()); + for (char ch : S) + if (hashset.find(ch) != hashset.end()) + ++res; + return res; + } +}; diff --git a/cpp/78.Subsets/dfs_recursion.cpp b/cpp/78.Subsets/dfs_recursion.cpp deleted file mode 100644 index d070b88..0000000 --- a/cpp/78.Subsets/dfs_recursion.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - vector> subsets(vector& nums) { - vectorcur; - vector>res; - dfs(cur,res,nums,0); - return res; - } - void dfs(vector&cur,vector>&res,vector&nums,int i){ - if(nums.size()==i){ - res.push_back(cur); - return; - } - cur.push_back(nums[i]); - dfs(cur,res,nums,i+1); - cur.pop_back(); - dfs(cur,res,nums,i+1); - } -}; diff --git a/cpp/78.Subsets/smart_iteration.cpp b/cpp/78.Subsets/smart_iteration.cpp deleted file mode 100644 index b5c793c..0000000 --- a/cpp/78.Subsets/smart_iteration.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - vector > subsets(vector &S) { - sort (S.begin(), S.end()); - int elem_num = S.size(); - int subset_num = pow (2, elem_num); - vector > subset_set (subset_num, vector()); - for (int i = 0; i < elem_num; i++) - for (int j = 0; j < subset_num; j++) - if ((j >> i) & 1) - subset_set[j].push_back (S[i]); - return subset_set; - } -}; diff --git a/cpp/78.cpp b/cpp/78.cpp new file mode 100644 index 0000000..8057494 --- /dev/null +++ b/cpp/78.cpp @@ -0,0 +1,37 @@ +// dfs_recursion.cpp +class Solution { + void dfs(vector& cur, vector>& res, vector& nums, + int i) { + if (nums.size() == i) { + res.push_back(cur); + return; + } + cur.push_back(nums[i]); + dfs(cur, res, nums, i + 1); + cur.pop_back(); + dfs(cur, res, nums, i + 1); + } + +public: + vector> subsets(vector& nums) { + vector cur; + vector> res; + dfs(cur, res, nums, 0); + return res; + } +}; +// smart_iteration.cpp +class Solution2 { +public: + vector> subsets(vector& S) { + sort(S.begin(), S.end()); + int elem_num = S.size(); + int subset_num = pow(2, elem_num); + vector> subset_set(subset_num, vector()); + for (int i = 0; i < elem_num; i++) + for (int j = 0; j < subset_num; j++) + if ((j >> i) & 1) + subset_set[j].push_back(S[i]); + return subset_set; + } +}; diff --git a/cpp/783.MinimumDistanceBetweenBSTNodes/sameAs530.cpp b/cpp/783.MinimumDistanceBetweenBSTNodes/sameAs530.cpp deleted file mode 100644 index 7023be9..0000000 --- a/cpp/783.MinimumDistanceBetweenBSTNodes/sameAs530.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - int min; - int lastValue; -public: - void getMinimum(TreeNode* root){ - if(root->left!=NULL) - getMinimum(root->left); - if( lastValue>=0 && abs(lastValue-root->val)val); - lastValue=root->val; - if(root->right!=NULL) - getMinimum(root->right); - } -public: - int minDiffInBST(TreeNode* root) { - min=INT_MAX; - lastValue=-1; - getMinimum(root); - return min; - } -}; diff --git a/cpp/783.cpp b/cpp/783.cpp new file mode 100644 index 0000000..7e5fd52 --- /dev/null +++ b/cpp/783.cpp @@ -0,0 +1,33 @@ +// sameAs530.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + int min; + int lastValue; + +public: + void getMinimum(TreeNode *root) { + if (root->left != NULL) + getMinimum(root->left); + if (lastValue >= 0 && abs(lastValue - root->val) < min) + min = abs(lastValue - root->val); + lastValue = root->val; + if (root->right != NULL) + getMinimum(root->right); + } + +public: + int minDiffInBST(TreeNode *root) { + min = INT_MAX; + lastValue = -1; + getMinimum(root); + return min; + } +}; diff --git a/cpp/784.LetterCasePermutation/dfs.cpp b/cpp/784.LetterCasePermutation/dfs.cpp deleted file mode 100644 index 674fca4..0000000 --- a/cpp/784.LetterCasePermutation/dfs.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { - void dfs(vector&res,string &s,int i){ - if(i==s.size()){ - res.push_back(s); - return; - } - dfs(res,s,i+1); - if(s[i]>='a'&&s[i]<='z'){ - s[i]+=-'a'+'A'; - dfs(res,s,i+1); - } - else if(s[i]>='A'&&s[i]<='Z'){ - s[i]+=-'A'+'a'; - dfs(res,s,i+1); - } - } -public: - vector letterCasePermutation(string S) { - vectorres; - dfs(res,S,0); - return res; - } -}; diff --git a/cpp/784.cpp b/cpp/784.cpp new file mode 100644 index 0000000..ba339fc --- /dev/null +++ b/cpp/784.cpp @@ -0,0 +1,24 @@ +// dfs.cpp +class Solution { + void dfs(vector &res, string &s, int i) { + if (i == s.size()) { + res.push_back(s); + return; + } + dfs(res, s, i + 1); + if (s[i] >= 'a' && s[i] <= 'z') { + s[i] += -'a' + 'A'; + dfs(res, s, i + 1); + } else if (s[i] >= 'A' && s[i] <= 'Z') { + s[i] += -'A' + 'a'; + dfs(res, s, i + 1); + } + } + +public: + vector letterCasePermutation(string S) { + vector res; + dfs(res, S, 0); + return res; + } +}; diff --git a/cpp/788.RotatedDigits/bruteForce.cpp b/cpp/788.RotatedDigits/bruteForce.cpp deleted file mode 100644 index 457831e..0000000 --- a/cpp/788.RotatedDigits/bruteForce.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution { - bool valid(int number){ - bool valid = false; - while(number){ - switch(number%10){ - case 2: - case 5: - case 6: - case 9:valid = true;break; - case 3: - case 4: - case 7:return false; - } - number/=10; - } - return valid; - } -public: - int rotatedDigits(int N) { - int count = 0; - for(int i=1;i<=N;++i) - if(valid(i)) - ++count; - return count; - } -}; diff --git a/cpp/788.cpp b/cpp/788.cpp new file mode 100644 index 0000000..12dbcfb --- /dev/null +++ b/cpp/788.cpp @@ -0,0 +1,31 @@ +// bruteForce.cpp +class Solution { + bool valid(int number) { + bool valid = false; + while (number) { + switch (number % 10) { + case 2: + case 5: + case 6: + case 9: + valid = true; + break; + case 3: + case 4: + case 7: + return false; + } + number /= 10; + } + return valid; + } + +public: + int rotatedDigits(int N) { + int count = 0; + for (int i = 1; i <= N; ++i) + if (valid(i)) + ++count; + return count; + } +}; diff --git a/cpp/79.WordSearch/dfs.cpp b/cpp/79.WordSearch/dfs.cpp deleted file mode 100644 index 5838a58..0000000 --- a/cpp/79.WordSearch/dfs.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { - bool find=0; -public: - bool exist(vector>& board, string word) { - int row=board.size(); - if(row==0||word.size()==0)return 0; - int col=board[0].size(); - vector>visited(row,vector(col,0)); - for(int i=0;i>& board, string& word,int i,int j,int k,vector>&visited){ - if(k==word.size()||find){ - find=1; - return; - } - if(i<0||i>=board.size()||j<0||j>=board[0].size()||board[i][j]!=word[k]||visited[i][j]) - return; - visited[i][j]=1; - dfs(board,word,i+1,j,k+1,visited); - dfs(board,word,i,j+1,k+1,visited); - dfs(board,word,i-1,j,k+1,visited); - dfs(board,word,i,j-1,k+1,visited); - visited[i][j]=0; - } -}; diff --git a/cpp/79.cpp b/cpp/79.cpp new file mode 100644 index 0000000..6939b64 --- /dev/null +++ b/cpp/79.cpp @@ -0,0 +1,35 @@ +// dfs.cpp +class Solution { + bool dfs(vector>& board, string& word, int i, int j, int k, + vector>& visited) { + if (k == word.size()) { + return true; + } + if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || + board[i][j] != word[k] || visited[i][j]) + return false; + visited[i][j] = 1; + if (dfs(board, word, i + 1, j, k + 1, visited) || + dfs(board, word, i, j + 1, k + 1, visited) || + dfs(board, word, i - 1, j, k + 1, visited) || + dfs(board, word, i, j - 1, k + 1, visited)) + return true; + visited[i][j] = 0; + return false; + } + +public: + bool exist(vector>& board, string word) { + int row = board.size(); + if (row == 0 || word.size() == 0) + return 0; + int col = board[0].size(); + vector> visited(row, vector(col, 0)); + for (int i = 0; i < row; ++i) + for (int j = 0; j < col; ++j) + if (board[i][j] == word[0] && + dfs(board, word, i, j, 0, visited)) + return true; + return false; + } +}; diff --git a/cpp/791.CustomSortString.cpp b/cpp/791.CustomSortString.cpp deleted file mode 100644 index 405b796..0000000 --- a/cpp/791.CustomSortString.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 84.35% of C++ online submissions for Custom Sort String. -//Memory Usage: 8.6 MB, less than 37.47% of C++ online submissions for Custom Sort String. -public: - string customSortString(string S, string T) { - unordered_map dir; - for (int i = 0; i < S.size(); ++i) - dir[S[i]]=i; - sort(T.begin(), T.end(),[&](char a, char b) { - return dir[a] < dir[b]; - }); - return T; - } -}; \ No newline at end of file diff --git a/cpp/791.cpp b/cpp/791.cpp new file mode 100644 index 0000000..4dc4eb4 --- /dev/null +++ b/cpp/791.cpp @@ -0,0 +1,13 @@ +class Solution { + // Runtime: 4 ms, faster than 84.35% of C++ online submissions for Custom Sort + // String. Memory Usage: 8.6 MB, less than 37.47% of C++ online submissions + // for Custom Sort String. +public: + string customSortString(string S, string T) { + unordered_map dir; + for (int i = 0; i < S.size(); ++i) + dir[S[i]] = i; + sort(T.begin(), T.end(), [&](char a, char b) { return dir[a] < dir[b]; }); + return T; + } +}; \ No newline at end of file diff --git a/cpp/796.RotateString/oneLine.cpp b/cpp/796.RotateString/oneLine.cpp deleted file mode 100644 index 770afe8..0000000 --- a/cpp/796.RotateString/oneLine.cpp +++ /dev/null @@ -1,6 +0,0 @@ -class Solution { -public: - bool rotateString(string A, string B) { - return (A.length() == B.length()) && ((A + A).find(B) != string::npos); - } -}; diff --git a/cpp/796.cpp b/cpp/796.cpp new file mode 100644 index 0000000..ec3d03d --- /dev/null +++ b/cpp/796.cpp @@ -0,0 +1,7 @@ +// oneLine.cpp +class Solution { +public: + bool rotateString(string A, string B) { + return (A.length() == B.length()) && ((A + A).find(B) != string::npos); + } +}; diff --git a/cpp/797.AllPathsFromSourcetoTarget.cpp b/cpp/797.AllPathsFromSourcetoTarget.cpp deleted file mode 100644 index 687b377..0000000 --- a/cpp/797.AllPathsFromSourcetoTarget.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -// Runtime: 72 ms, faster than 98.24% of C++ online submissions for All Paths From Source to Target. -// Memory Usage: 12.6 MB, less than 87.43% of C++ online submissions for All Paths From Source to Target. -public: - vector> allPathsSourceTarget(vector>& g) { - vector> res; - vector path; - function dfs = [&](int cur) { - path.push_back(cur); - if (cur == g.size() - 1) - res.push_back(path); - else for (auto dst:g[cur]) - dfs(dst); - path.pop_back(); - }; - dfs(0); - return res; - } -}; \ No newline at end of file diff --git a/cpp/797.cpp b/cpp/797.cpp new file mode 100644 index 0000000..9578380 --- /dev/null +++ b/cpp/797.cpp @@ -0,0 +1,21 @@ +class Solution { + // Runtime: 72 ms, faster than 98.24% of C++ online submissions for All Paths + // From Source to Target. Memory Usage: 12.6 MB, less than 87.43% of C++ + // online submissions for All Paths From Source to Target. +public: + vector> allPathsSourceTarget(vector> &g) { + vector> res; + vector path; + function dfs = [&](int cur) { + path.push_back(cur); + if (cur == g.size() - 1) + res.push_back(path); + else + for (auto dst : g[cur]) + dfs(dst); + path.pop_back(); + }; + dfs(0); + return res; + } +}; \ No newline at end of file diff --git a/cpp/8.StringToInteger_atoi/simple.cpp b/cpp/8.StringToInteger_atoi/simple.cpp deleted file mode 100644 index 2c360a2..0000000 --- a/cpp/8.StringToInteger_atoi/simple.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - int myAtoi(string str) { - int len=str.size(); - if(len==0)return 0; - int i,j; - for(j=0;j='0'&&str[j]<='9'))return 0; - for(i=j;i='0'&&str[i]<='9'))break; - int result=0; - while(jINT_MAX/10&&j'7')) - return sign==1?INT_MAX:INT_MIN; - } - return sign*result; - } - -}; diff --git a/cpp/8.cpp b/cpp/8.cpp new file mode 100644 index 0000000..e080377 --- /dev/null +++ b/cpp/8.cpp @@ -0,0 +1,30 @@ +// simple.cpp +class Solution { +public: + int myAtoi(string str) { + int len = str.size(); + if (len == 0) + return 0; + int i, j; + for (j = 0; j < len && str[j] == ' '; ++j) + ; + int sign = 1; + if (str[j] == '-' || str[j] == '+') { + sign = str[j] == '-' ? -1 : 1; + ++j; + } + if (!(str[j] >= '0' && str[j] <= '9')) + return 0; + for (i = j; i < len; ++i) + if (!(str[i] >= '0' && str[i] <= '9')) + break; + int result = 0; + while (j < i) { + result = result * 10 + str[j++] - '0'; + if ((result > INT_MAX / 10 && j < i) || + (result == INT_MAX / 10 && j < i && str[j] > '7')) + return sign == 1 ? INT_MAX : INT_MIN; + } + return sign * result; + } +}; diff --git a/cpp/80.RemoveDuplicatesFromSortedArrayII/hash-12ms.cpp b/cpp/80.RemoveDuplicatesFromSortedArrayII/hash-12ms.cpp deleted file mode 100644 index f873d9b..0000000 --- a/cpp/80.RemoveDuplicatesFromSortedArrayII/hash-12ms.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - int removeDuplicates(vector& nums) { - int n=nums.size(); - if(n==0)return 0; - int times=1,value=nums[0]; - int count=1; - for(int i=1;i& nums) { + int i = 1, l = 1; + for (bool twice = false; i < nums.size(); ++i) { + if (nums[i] == nums[i - 1]) { + if (twice) + continue; + twice = true; + } else { + twice = false; + } + nums[l++] = nums[i]; + } + return l; + } +}; \ No newline at end of file diff --git a/cpp/804.UniqueMorseCodeWords/hashset.cpp b/cpp/804.UniqueMorseCodeWords/hashset.cpp deleted file mode 100644 index 133a4e2..0000000 --- a/cpp/804.UniqueMorseCodeWords/hashset.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - int uniqueMorseRepresentations(vector& words) { - const static string morse[26]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; - unordered_setres; - for(auto &str:words){ - string s; - for(auto ch:str) - s+=morse[ch-'a']; - res.insert(s); - } - return res.size(); - } -}; diff --git a/cpp/804.cpp b/cpp/804.cpp new file mode 100644 index 0000000..5c46f33 --- /dev/null +++ b/cpp/804.cpp @@ -0,0 +1,18 @@ +// hashset.cpp +class Solution { +public: + int uniqueMorseRepresentations(vector &words) { + const static string morse[26] = { + ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", + ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", + "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; + unordered_set res; + for (auto &str : words) { + string s; + for (auto ch : str) + s += morse[ch - 'a']; + res.insert(s); + } + return res.size(); + } +}; diff --git a/cpp/806.NumberOfLinesToWriteString/simple.cpp b/cpp/806.NumberOfLinesToWriteString/simple.cpp deleted file mode 100644 index 34c7600..0000000 --- a/cpp/806.NumberOfLinesToWriteString/simple.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - vector numberOfLines(vector& widths, string S) { - int used=0,line=1; - for(auto ch:S){ - used+=widths[ch-'a']; - if(used>100){ - ++line; - used=widths[ch-'a']; - } - } - return vector{line,used}; - } -}; diff --git a/cpp/806.cpp b/cpp/806.cpp new file mode 100644 index 0000000..84e1714 --- /dev/null +++ b/cpp/806.cpp @@ -0,0 +1,15 @@ +// simple.cpp +class Solution { +public: + vector numberOfLines(vector &widths, string S) { + int used = 0, line = 1; + for (auto ch : S) { + used += widths[ch - 'a']; + if (used > 100) { + ++line; + used = widths[ch - 'a']; + } + } + return vector{line, used}; + } +}; diff --git a/cpp/81.SearchInRotatedSortedArrayII/confuse.cpp b/cpp/81.SearchInRotatedSortedArrayII/confuse.cpp deleted file mode 100644 index 54a799b..0000000 --- a/cpp/81.SearchInRotatedSortedArrayII/confuse.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution { -public: - bool search(vector& nums, int target) { - if(nums.size()==0) - return 0; - int l=0,r=nums.size()-1; - while(l<=r){ - int mid=(l+r)/2; - if(nums[mid]==target) - return 1; - if(nums[l]==nums[mid]&&nums[mid]==nums[r]) - ++l,--r; - else if(nums[mid]>=nums[l]){ - if(nums[l]<=target&&target &nums, int target) { + if (nums.size() == 0) + return 0; + int l = 0, r = nums.size() - 1; + while (l <= r) { + int mid = (l + r) / 2; + if (nums[mid] == target) + return 1; + if (nums[l] == nums[mid] && nums[mid] == nums[r]) + ++l, --r; + else if (nums[mid] >= nums[l]) { + if (nums[l] <= target && target < nums[mid]) + r = mid - 1; + else + l = mid + 1; + } else if (nums[mid] <= nums[r]) { + if (nums[mid] < target && target <= nums[r]) + l = mid + 1; + else + r = mid - 1; + } + } + return false; + } +}; diff --git a/cpp/811.SubdomainVisitCount/hashmap.cpp b/cpp/811.SubdomainVisitCount/hashmap.cpp deleted file mode 100644 index 4b45484..0000000 --- a/cpp/811.SubdomainVisitCount/hashmap.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - vector subdomainVisits(vector& cpdomains) { - unordered_maphashmap; - for(auto &str:cpdomains){ - int i=0,val; - stringstream ss(str); - ss>>val>>str; - do{ - hashmap[str.substr(i)]+=val; - }while((i=str.find('.',i)+1)!=string::npos+1); - } - vectorres; - for(auto &p:hashmap){ - res.push_back(to_string(p.second)+" "+p.first); - } - return res; - } -}; diff --git a/cpp/811.cpp b/cpp/811.cpp new file mode 100644 index 0000000..9902cb4 --- /dev/null +++ b/cpp/811.cpp @@ -0,0 +1,20 @@ +// hashmap.cpp +class Solution { +public: + vector subdomainVisits(vector &cpdomains) { + unordered_map hashmap; + for (auto &str : cpdomains) { + int i = 0, val; + stringstream ss(str); + ss >> val >> str; + do { + hashmap[str.substr(i)] += val; + } while ((i = str.find('.', i) + 1) != string::npos + 1); + } + vector res; + for (auto &p : hashmap) { + res.push_back(to_string(p.second) + " " + p.first); + } + return res; + } +}; diff --git a/cpp/812.LargestTriangleArea.cpp b/cpp/812.LargestTriangleArea.cpp deleted file mode 100644 index a1361cb..0000000 --- a/cpp/812.LargestTriangleArea.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - double largestTriangleArea(vector>& p) { - double res = 0; - for (auto &i : p) - for (auto &j : p) - for (auto &k : p) - res = max(res, 0.5 * (i[0] * j[1] + j[0] * k[1] + k[0] * i[1]- j[0] * i[1] - k[0] * j[1] - i[0] * k[1])); - return res; - } -}; \ No newline at end of file diff --git a/cpp/812.cpp b/cpp/812.cpp new file mode 100644 index 0000000..4414cde --- /dev/null +++ b/cpp/812.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + double largestTriangleArea(vector> &p) { + double res = 0; + for (auto &i : p) + for (auto &j : p) + for (auto &k : p) + res = max(res, 0.5 * (i[0] * j[1] + j[0] * k[1] + k[0] * i[1] - + j[0] * i[1] - k[0] * j[1] - i[0] * k[1])); + return res; + } +}; \ No newline at end of file diff --git a/cpp/814.BinaryTreePruning.cpp b/cpp/814.BinaryTreePruning.cpp deleted file mode 100644 index 03a60f6..0000000 --- a/cpp/814.BinaryTreePruning.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { //Runtime: 4 ms, faster than 91.95% of C++ online submissions for Binary Tree Pruning. -public: - TreeNode* pruneTree(TreeNode* root) { - function postorder=[&postorder](TreeNode* node){ - if(!node) - return true; - auto removeThis=node->val==0; - auto removeL=postorder(node->left); - if(removeL) - node->left=nullptr; - auto removeR=postorder(node->right); - if(removeR) - node->right=nullptr; - removeThis=removeThis and removeL and removeR; - return removeThis; - }; - return postorder(root)?nullptr:root; - } -}; \ No newline at end of file diff --git a/cpp/814.cpp b/cpp/814.cpp new file mode 100644 index 0000000..3f68244 --- /dev/null +++ b/cpp/814.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 4 ms, faster than 91.95% of C++ online submissions + // for Binary Tree Pruning. +public: + TreeNode *pruneTree(TreeNode *root) { + function postorder = [&postorder](TreeNode *node) { + if (!node) + return true; + auto removeThis = node->val == 0; + auto removeL = postorder(node->left); + if (removeL) + node->left = nullptr; + auto removeR = postorder(node->right); + if (removeR) + node->right = nullptr; + removeThis = removeThis and removeL and removeR; + return removeThis; + }; + return postorder(root) ? nullptr : root; + } +}; \ No newline at end of file diff --git a/cpp/819.MostCommonWord/hash.cpp b/cpp/819.MostCommonWord/hash.cpp deleted file mode 100644 index a851aa0..0000000 --- a/cpp/819.MostCommonWord/hash.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - string mostCommonWord(string paragraph, vector& banned) { - unordered_mapwordmap; - transform(paragraph.begin(),paragraph.end(),paragraph.begin(),[](char &ch)->char{ - switch(ch){ - case '!':case '?':case '\'':case ',':case ';':case '.':return ' '; - } - return tolower(ch); - }); - unordered_setbannedSet(banned.begin(),banned.end()); - stringstream ss(paragraph); - string str; - while(!ss.eof()){ - ss>>str; - if(bannedSet.find(str)==bannedSet.end()) - ++wordmap[str]; - } - return max_element(wordmap.begin(),wordmap.end(),[](const pair&a,const pair&b){ - return a.secondfirst; - } -}; diff --git a/cpp/819.cpp b/cpp/819.cpp new file mode 100644 index 0000000..c772227 --- /dev/null +++ b/cpp/819.cpp @@ -0,0 +1,34 @@ +// hash.cpp +class Solution { +public: + string mostCommonWord(string paragraph, vector &banned) { + unordered_map wordmap; + transform(paragraph.begin(), paragraph.end(), paragraph.begin(), + [](char &ch) -> char { + switch (ch) { + case '!': + case '?': + case '\'': + case ',': + case ';': + case '.': + return ' '; + } + return tolower(ch); + }); + unordered_set bannedSet(banned.begin(), banned.end()); + stringstream ss(paragraph); + string str; + while (!ss.eof()) { + ss >> str; + if (bannedSet.find(str) == bannedSet.end()) + ++wordmap[str]; + } + return max_element(wordmap.begin(), wordmap.end(), + [](const pair &a, + const pair &b) { + return a.second < b.second; + }) + ->first; + } +}; diff --git a/cpp/82.RemoveDuplicatesFromSortedListII/iteration.cpp b/cpp/82.RemoveDuplicatesFromSortedListII/iteration.cpp deleted file mode 100644 index d34389c..0000000 --- a/cpp/82.RemoveDuplicatesFromSortedListII/iteration.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* deleteDuplicates(ListNode* head) { - ListNode *p1=new ListNode(0),*p2; - p1->next=head; - p2=p1; - if(p1->next==NULL||p1->next->next==NULL)return p1->next; - while(p1->next&&p1->next->next) - if(p1->next->val!=p1->next->next->val) - p1=p1->next; - else - p1->next=deleteVal(p1->next,p1->next->val); - return p2->next; - } - ListNode* deleteVal(ListNode *head,int val){ - while(head!=NULL&&head->val==val) - if(head->next!=NULL) - *head=*(head->next); - else - return NULL; - return head; - } -}; diff --git a/cpp/82.cpp b/cpp/82.cpp new file mode 100644 index 0000000..a39a1b7 --- /dev/null +++ b/cpp/82.cpp @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode h(0, head); + for (auto p = &h; p->next;) { + if (auto temp = p->next->next; + temp != nullptr && p->next->val == temp->val) { + while (temp && p->next->val == temp->val) + temp = temp->next; + p->next = temp; + } else { + p = p->next; + } + } + return h.next; + } +}; \ No newline at end of file diff --git a/cpp/821.ShortestDistanceToACharacter/simple.cpp b/cpp/821.ShortestDistanceToACharacter/simple.cpp deleted file mode 100644 index d78d8e0..0000000 --- a/cpp/821.ShortestDistanceToACharacter/simple.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - vector shortestToChar(string S, char C) { - vectorres(S.size(),0); - int l=S.find_first_of(C),r=S.find_last_of(C); - for(int pos=l;pos>=0;--pos) - res[pos]=l-pos; - for(int pos=r;pos shortestToChar(string S, char C) { + vector res(S.size(), 0); + int l = S.find_first_of(C), r = S.find_last_of(C); + for (int pos = l; pos >= 0; --pos) + res[pos] = l - pos; + for (int pos = r; pos < S.size(); ++pos) + res[pos] = pos - r; + while (l != r) { + int mid = S.find_first_of(C, l + 1); + for (int i = l, j = mid, k = 0; i <= j;) + res[i++] = res[j--] = k++; + l = mid; + } + return res; + } +}; diff --git a/cpp/824.GoatLatin/simple.cpp b/cpp/824.GoatLatin/simple.cpp deleted file mode 100644 index 8193a73..0000000 --- a/cpp/824.GoatLatin/simple.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - string toGoatLatin(string S) { - stringstream ss(S); - string str,res; - int i =1; - while(!ss.eof()){ - ss>>str; - switch(tolower(str[0])){ - case 'a':case 'e':case 'i':case 'o':case 'u':{ - str+="ma"; - break; - } - default:str=string(str.begin()+1,str.end())+str[0]+"ma"; - } - str.append(i++,'a'); - res+=res==""?str:" "+str; - } - return res; - } -}; diff --git a/cpp/824.cpp b/cpp/824.cpp new file mode 100644 index 0000000..f986a78 --- /dev/null +++ b/cpp/824.cpp @@ -0,0 +1,27 @@ +// simple.cpp +class Solution { +public: + string toGoatLatin(string S) { + stringstream ss(S); + string str, res; + int i = 1; + while (!ss.eof()) { + ss >> str; + switch (tolower(str[0])) { + case 'a': + case 'e': + case 'i': + case 'o': + case 'u': { + str += "ma"; + break; + } + default: + str = string(str.begin() + 1, str.end()) + str[0] + "ma"; + } + str.append(i++, 'a'); + res += res == "" ? str : " " + str; + } + return res; + } +}; diff --git a/cpp/83.RemoveDuplicatesFromSortedList/iteration.cpp b/cpp/83.RemoveDuplicatesFromSortedList/iteration.cpp deleted file mode 100644 index 769a49d..0000000 --- a/cpp/83.RemoveDuplicatesFromSortedList/iteration.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* deleteDuplicates(ListNode* head) { - ListNode*p=head,*temp; - if(p==NULL)return p; - while(p->next!=NULL){ - if(p->next->val==p->val){ - p->next=p->next->next; - } - else - p=p->next; - } - return head; - } -}; diff --git a/cpp/83.cpp b/cpp/83.cpp new file mode 100644 index 0000000..689f880 --- /dev/null +++ b/cpp/83.cpp @@ -0,0 +1,23 @@ +// iteration.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if (head == nullptr) + return head; + for (auto p = head; p->next != nullptr;) { + if (p->next->val == p->val) + p->next = p->next->next; + else + p = p->next; + } + return head; + } +}; diff --git a/cpp/832.FlippingAnImage/singleScan.cpp b/cpp/832.FlippingAnImage/singleScan.cpp deleted file mode 100644 index adf67a0..0000000 --- a/cpp/832.FlippingAnImage/singleScan.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution { -public: - vector> flipAndInvertImage(vector>& A) { - for(auto &arr:A){ - int i=0,j=arr.size()-1; - for(;i> flipAndInvertImage(vector> &A) { + for (auto &arr : A) { + int i = 0, j = arr.size() - 1; + for (; i < j; ++i, --j) { + swap(arr[i], arr[j]); + arr[i] = !arr[i]; + arr[j] = !arr[j]; + } + if (i == j) + arr[i] = !arr[i]; + } + return A; + } +}; diff --git a/cpp/84.LargestRectangleInHistogram/stack.cpp b/cpp/84.LargestRectangleInHistogram/stack.cpp deleted file mode 100644 index a9ed3a7..0000000 --- a/cpp/84.LargestRectangleInHistogram/stack.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - int largestRectangleArea(vector& heights) { - stackst; - int n=heights.size(),maxArea=0; - for(int i=0;i &heights) { + stack st; + int n = heights.size(), maxArea = 0; + for (int i = 0; i < heights.size();) + if (st.empty() || heights[st.top()] <= heights[i]) + st.push(i++); + else { + int top = st.top(); + st.pop(); + maxArea = + max(maxArea, heights[top] * (st.empty() ? i : i - st.top() - 1)); + } + while (!st.empty()) { + int top = st.top(); + st.pop(); + maxArea = + max(maxArea, heights[top] * ((st.empty() ? n : n - st.top() - 1))); + } + return maxArea; + } +}; diff --git a/cpp/841.KeysAndRooms.cpp b/cpp/841.KeysAndRooms.cpp deleted file mode 100644 index a1d0230..0000000 --- a/cpp/841.KeysAndRooms.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -//Runtime: 8 ms, faster than 98.83% of C++ online submissions for Keys and Rooms. -//Memory Usage: 10.9 MB, less than 70.73% of C++ online submissions for Keys and Rooms. -public: - bool canVisitAllRooms(vector>& rooms) { - vector st = {0}; - unordered_set seen = {0}; - while (!st.empty()) { - int i = st.back(); - st.pop_back(); - for (int j : rooms[i]) - if (seen.count(j) == 0) { - st.push_back(j); - seen.insert(j); - if (rooms.size() == seen.size()) - return true; - } - } - return rooms.size() == seen.size(); - } -}; \ No newline at end of file diff --git a/cpp/841.cpp b/cpp/841.cpp new file mode 100644 index 0000000..89ecdee --- /dev/null +++ b/cpp/841.cpp @@ -0,0 +1,22 @@ +class Solution { + // Runtime: 8 ms, faster than 98.83% of C++ online submissions for Keys and + // Rooms. Memory Usage: 10.9 MB, less than 70.73% of C++ online submissions + // for Keys and Rooms. +public: + bool canVisitAllRooms(vector> &rooms) { + vector st = {0}; + unordered_set seen = {0}; + while (!st.empty()) { + int i = st.back(); + st.pop_back(); + for (int j : rooms[i]) + if (seen.count(j) == 0) { + st.push_back(j); + seen.insert(j); + if (rooms.size() == seen.size()) + return true; + } + } + return rooms.size() == seen.size(); + } +}; \ No newline at end of file diff --git a/cpp/852.PeakIndexinaMountainArray.cpp b/cpp/852.PeakIndexinaMountainArray.cpp deleted file mode 100644 index 4020277..0000000 --- a/cpp/852.PeakIndexinaMountainArray.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { //16ms -public: - int peakIndexInMountainArray(vector& A) { - int l=0,r=A.size()-1; - while(r-l>3){ - int ll=l+(r-l)/3; - int rr=l+(r-l)/3*2; - if(A[ll]>=A[rr]) - r=rr; - if(A[ll]<=A[rr]) - l=ll; - } - return max_element(A.begin()+l,A.begin()+r)-A.begin(); - } -}; \ No newline at end of file diff --git a/cpp/852.cpp b/cpp/852.cpp new file mode 100644 index 0000000..80d8f8a --- /dev/null +++ b/cpp/852.cpp @@ -0,0 +1,15 @@ +class Solution { // 16ms +public: + int peakIndexInMountainArray(vector &A) { + int l = 0, r = A.size() - 1; + while (r - l > 3) { + int ll = l + (r - l) / 3; + int rr = l + (r - l) / 3 * 2; + if (A[ll] >= A[rr]) + r = rr; + if (A[ll] <= A[rr]) + l = ll; + } + return max_element(A.begin() + l, A.begin() + r) - A.begin(); + } +}; \ No newline at end of file diff --git a/cpp/86.PartitionList/1.cpp b/cpp/86.PartitionList/1.cpp deleted file mode 100644 index 0fe9f24..0000000 --- a/cpp/86.PartitionList/1.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* partition(ListNode* head, int x) { - if(head==NULL||head->next==NULL)return head; - ListNode *small=new ListNode(0),*p1=small; - ListNode *big=new ListNode(0),*p2=big; - while(head){ - if(head->valnext=head; - p1=p1->next; - } - else{ - p2->next=head; - p2=p2->next; - } - head=head->next; - } - p1->next=big->next; - p2->next=NULL; - return small->next;; - } -}; \ No newline at end of file diff --git a/cpp/86.cpp b/cpp/86.cpp new file mode 100644 index 0000000..75eb4b9 --- /dev/null +++ b/cpp/86.cpp @@ -0,0 +1,29 @@ +// 1.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* partition(ListNode* head, int x) { + if (head == nullptr || head->next == nullptr) + return head; + auto small = ListNode(0), big = ListNode(0); + auto p1 = &small, p2 = &big; + while (head) { + if (head->val < x) { + p1 = p1->next = head; + } else { + p2 = p2->next = head; + } + head = head->next; + } + p1->next = big.next; + p2->next = nullptr; + return small.next; + } +}; \ No newline at end of file diff --git a/cpp/860.LemonadeChange.cpp b/cpp/860.LemonadeChange.cpp deleted file mode 100644 index 5026d82..0000000 --- a/cpp/860.LemonadeChange.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { // Runtime: 16 ms, faster than 93.61% of C++ online submissions for Lemonade Change. -public: - bool lemonadeChange(vector& bills) { - int five = 0, ten = 0; - for (int i : bills) { - if (i == 5) - five++; - else if (i == 10) - five--, ten++; - else if (ten > 0) - ten--, five--; - else - five -= 3; - if (five < 0) - return false; - } - return true; - } -}; \ No newline at end of file diff --git a/cpp/860.cpp b/cpp/860.cpp new file mode 100644 index 0000000..9c198c0 --- /dev/null +++ b/cpp/860.cpp @@ -0,0 +1,20 @@ +class Solution { // Runtime: 16 ms, faster than 93.61% of C++ online submissions + // for Lemonade Change. +public: + bool lemonadeChange(vector &bills) { + int five = 0, ten = 0; + for (int i : bills) { + if (i == 5) + five++; + else if (i == 10) + five--, ten++; + else if (ten > 0) + ten--, five--; + else + five -= 3; + if (five < 0) + return false; + } + return true; + } +}; \ No newline at end of file diff --git a/cpp/867.TransposeMatrix.cpp b/cpp/867.TransposeMatrix.cpp deleted file mode 100644 index 06279a8..0000000 --- a/cpp/867.TransposeMatrix.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { //24ms -public: - vector> transpose(vector>& A) { - int r=A.size(),c=A[0].size(); - vector> ret(c,vector(r)); - for(int i=0;i> transpose(vector> &A) { + int r = A.size(), c = A[0].size(); + vector> ret(c, vector(r)); + for (int i = 0; i < r; ++i) { + for (int j = 0; j < c; ++j) { + ret[j][i] = A[i][j]; + } + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/873.LengthOfLongestFibonacciSubsequence.cpp b/cpp/873.LengthOfLongestFibonacciSubsequence.cpp deleted file mode 100644 index 2fdfe1d..0000000 --- a/cpp/873.LengthOfLongestFibonacciSubsequence.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { -//Runtime: 224 ms, faster than 38.19% of C++ online submissions for Length of Longest Fibonacci Subsequence. -//Memory Usage: 62.6 MB, less than 7.11% of C++ online submissions for Length of Longest Fibonacci Subsequence. -public: - int lenLongestFibSubseq(vector& A) { - unordered_map val2idx; - for(int i=2;i> dp(A.size(),vector(A.size(),0)); - vector> st; - int ret=0; - for(int i=0;isecond; - } - else break; - } - while(st.size()){ - const auto [a,b]=st.back(); - st.pop_back(); - dp[a][b]=dp[b][val2idx[A[a]+A[b]]]==0?3:dp[b][val2idx[A[a]+A[b]]]+1; - ret=max(ret,dp[a][b]); - } - } - } - return ret; - } -}; \ No newline at end of file diff --git a/cpp/873.cpp b/cpp/873.cpp new file mode 100644 index 0000000..c6eefe3 --- /dev/null +++ b/cpp/873.cpp @@ -0,0 +1,36 @@ +class Solution { + // Runtime: 224 ms, faster than 38.19% of C++ online submissions for Length of + // Longest Fibonacci Subsequence. Memory Usage: 62.6 MB, less than 7.11% of + // C++ online submissions for Length of Longest Fibonacci Subsequence. +public: + int lenLongestFibSubseq(vector &A) { + unordered_map val2idx; + for (int i = 2; i < A.size(); ++i) + val2idx[A[i]] = i; + vector> dp(A.size(), vector(A.size(), 0)); + vector> st; + int ret = 0; + for (int i = 0; i < A.size(); ++i) { + for (int j = i + 1; j < A.size(); ++j) { + for (int a = i, b = j;;) { + if (auto it = val2idx.find(A[a] + A[b]); + it != end(val2idx) and dp[a][b] == 0) { + st.emplace_back(a, b); + a = b; + b = it->second; + } else + break; + } + while (st.size()) { + const auto [a, b] = st.back(); + st.pop_back(); + dp[a][b] = dp[b][val2idx[A[a] + A[b]]] == 0 + ? 3 + : dp[b][val2idx[A[a] + A[b]]] + 1; + ret = max(ret, dp[a][b]); + } + } + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/876.MiddleOfTheLinkedList/twoPointer.cpp b/cpp/876.MiddleOfTheLinkedList/twoPointer.cpp deleted file mode 100644 index b429fdf..0000000 --- a/cpp/876.MiddleOfTheLinkedList/twoPointer.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* middleNode(ListNode* head) { - auto pFront = head, pBack = head; - while(pBack){ - pBack=pBack->next; - if(!pBack) - break; - pFront=pFront->next; - pBack=pBack->next; - } - return pFront; - } -}; diff --git a/cpp/876.cpp b/cpp/876.cpp new file mode 100644 index 0000000..02ab36b --- /dev/null +++ b/cpp/876.cpp @@ -0,0 +1,23 @@ +// twoPointer.cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *middleNode(ListNode *head) { + auto pFront = head, pBack = head; + while (pBack) { + pBack = pBack->next; + if (!pBack) + break; + pFront = pFront->next; + pBack = pBack->next; + } + return pFront; + } +}; diff --git a/cpp/877.StoneGame.cpp b/cpp/877.StoneGame.cpp deleted file mode 100644 index 49d5651..0000000 --- a/cpp/877.StoneGame.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution { -/* -https://leetcode.com/problems/stone-game/discuss/154610/DP-or-Just-return-true -Alex is first to pick pile. -piles.length is even, and this lead to an interesting fact: -Alex can always pick odd piles or always pick even piles! - -For example, -If Alex wants to pick even indexed piles piles[0], piles[2], ....., piles[n-2], -he picks first piles[0], then Lee can pick either piles[1] or piles[n - 1]. -Every turn, Alex can always pick even indexed piles and Lee can only pick odd indexed piles. - -In the description, we know that sum(piles) is odd. -If sum(piles[even]) > sum(piles[odd]), Alex just picks all evens and wins. -If sum(piles[even]) < sum(piles[odd]), Alex just picks all odds and wins. - -So, Alex always defeats Lee in this game. -*/ -//Runtime: 4 ms, faster than 95.00% of C++ online submissions for Stone Game. -//Memory Usage: 8.7 MB, less than 58.60% of C++ online submissions for Stone Game. -public: - bool stoneGame(vector& piles) { - return true; - } -}; - -class Solution { // dp -public: - bool stoneGame(vector& piles) { - vector> dp(piles.size(),vector(piles.size(),0)); - for(int i=0;i0; - } -}; \ No newline at end of file diff --git a/cpp/877.cpp b/cpp/877.cpp new file mode 100644 index 0000000..5e341c2 --- /dev/null +++ b/cpp/877.cpp @@ -0,0 +1,39 @@ +class Solution { + /* + https://leetcode.com/problems/stone-game/discuss/154610/DP-or-Just-return-true + Alex is first to pick pile. + piles.length is even, and this lead to an interesting fact: + Alex can always pick odd piles or always pick even piles! + + For example, + If Alex wants to pick even indexed piles piles[0], piles[2], ....., + piles[n-2], he picks first piles[0], then Lee can pick either piles[1] or + piles[n - 1]. Every turn, Alex can always pick even indexed piles and Lee can + only pick odd indexed piles. + + In the description, we know that sum(piles) is odd. + If sum(piles[even]) > sum(piles[odd]), Alex just picks all evens and wins. + If sum(piles[even]) < sum(piles[odd]), Alex just picks all odds and wins. + + So, Alex always defeats Lee in this game. + */ + // Runtime: 4 ms, faster than 95.00% of C++ online submissions for Stone Game. + // Memory Usage: 8.7 MB, less than 58.60% of C++ online submissions for Stone + // Game. +public: + bool stoneGame(vector &piles) { return true; } +}; + +class Solution2 { // dp +public: + bool stoneGame(vector &piles) { + vector> dp(piles.size(), vector(piles.size(), 0)); + for (int i = 0; i < piles.size(); ++i) + dp[i][i] = piles[i]; + for (int i = 1; i < piles.size(); ++i) + for (int j = 0; j < piles.size() - i; ++j) + dp[j][i + j] = + max(piles[j] - dp[j + 1][i + j], piles[i + j] - dp[j][i + j - 1]); + return dp[0][piles.size() - 1] > 0; + } +}; \ No newline at end of file diff --git a/cpp/88.MergeSortedArray/iteration-3ms.cpp b/cpp/88.MergeSortedArray/iteration-3ms.cpp deleted file mode 100644 index 729577f..0000000 --- a/cpp/88.MergeSortedArray/iteration-3ms.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { -public: - void merge(vector& nums1, int m, vector& nums2, int n) { - int last=m+n-1; - --m,--n; - while(n>=0 && m>=0) - if(nums1[m]<=nums2[n]) - nums1[last--]=nums2[n--]; - else - nums1[last--]=nums1[m--]; - while(n>=0) - nums1[last--]=nums2[n--]; - } -}; diff --git a/cpp/88.cpp b/cpp/88.cpp new file mode 100644 index 0000000..2ed413a --- /dev/null +++ b/cpp/88.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int last = m + n - 1; + --m, --n; + while (n >= 0 && m >= 0) + nums1[last--] = nums1[m] <= nums2[n] ? nums2[n--] : nums1[m--]; + while (n >= 0) + nums1[last--] = nums2[n--]; + } +}; diff --git a/cpp/884.UncommonWordsfromTwoSentences.cpp b/cpp/884.UncommonWordsfromTwoSentences.cpp deleted file mode 100644 index 45b4c40..0000000 --- a/cpp/884.UncommonWordsfromTwoSentences.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution { // 0ms -public: - vector uncommonFromSentences(string A, string B) { - unordered_map count; - istringstream iss(A + " " + B); - while (iss >> A) - count[A]++; - vector res; - for (auto &w: count) - if (w.second == 1) - res.push_back(w.first); - return res; - } -}; \ No newline at end of file diff --git a/cpp/884.cpp b/cpp/884.cpp new file mode 100644 index 0000000..96b2520 --- /dev/null +++ b/cpp/884.cpp @@ -0,0 +1,14 @@ +class Solution { // 0ms +public: + vector uncommonFromSentences(string A, string B) { + unordered_map count; + istringstream iss(A + " " + B); + while (iss >> A) + count[A]++; + vector res; + for (auto &w : count) + if (w.second == 1) + res.push_back(w.first); + return res; + } +}; \ No newline at end of file diff --git a/cpp/885.SpiralMatrixIII.cpp b/cpp/885.SpiralMatrixIII.cpp deleted file mode 100644 index 590cf21..0000000 --- a/cpp/885.SpiralMatrixIII.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -//Runtime: 52 ms, faster than 99.27% of C++ online submissions for Spiral Matrix III. -//Memory Usage: 13.6 MB, less than 60.22% of C++ online submissions for Spiral Matrix III. -public: - vector> spiralMatrixIII(int R, int C, int r, int c) { - vector> res = {{r, c}}; - vector> dirs = {{1,0},{0,1},{-1,0},{0,-1}}; - int curDir = 0; - for (int n = 0; res.size() < R * C; ++n) { - auto [dirX,dirY] = dirs[curDir++%4]; - for (int i = 0; i < n / 2 + 1; ++i) { - r += dirY, c += dirX; - if (0 <= r && r < R && 0 <= c && c < C) - res.push_back({r, c}); - } - } - return res; - } -}; \ No newline at end of file diff --git a/cpp/885.cpp b/cpp/885.cpp new file mode 100644 index 0000000..f223d12 --- /dev/null +++ b/cpp/885.cpp @@ -0,0 +1,20 @@ +class Solution { + // Runtime: 52 ms, faster than 99.27% of C++ online submissions for Spiral + // Matrix III. Memory Usage: 13.6 MB, less than 60.22% of C++ online + // submissions for Spiral Matrix III. +public: + vector> spiralMatrixIII(int R, int C, int r, int c) { + vector> res = {{r, c}}; + vector> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + int curDir = 0; + for (int n = 0; res.size() < R * C; ++n) { + auto [dirX, dirY] = dirs[curDir++ % 4]; + for (int i = 0; i < n / 2 + 1; ++i) { + r += dirY, c += dirX; + if (0 <= r && r < R && 0 <= c && c < C) + res.push_back({r, c}); + } + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/89.GrayCode/findTheLaw.cpp b/cpp/89.GrayCode/findTheLaw.cpp deleted file mode 100644 index a38689c..0000000 --- a/cpp/89.GrayCode/findTheLaw.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - vector grayCode(int n) { - if(n<0) - return vector(); - vectorarr{0}; - for(int i=0;i=0){ - arr.push_back((1< grayCode(int n) { - if (n==0) - return {0}; - //Binary to grey code, num ^ (num >> 1); - vector res; - int count=1<> 1)); - } - return res; - } -}; diff --git a/cpp/89.cpp b/cpp/89.cpp new file mode 100644 index 0000000..72d965a --- /dev/null +++ b/cpp/89.cpp @@ -0,0 +1,31 @@ +// findTheLaw.cpp +class Solution { +public: + vector grayCode(int n) { + if (n < 0) + return vector(); + vector arr{0}; + for (int i = 0; i < n; ++i) { + int size = arr.size(); + while (--size >= 0) { + arr.push_back((1 << i) | arr[size]); + } + } + return arr; + } +}; +// usingMath.cpp +class Solution2 { +public: + vector grayCode(int n) { + if (n == 0) + return {0}; + // Binary to grey code, num ^ (num >> 1); + vector res; + int count = 1 << n; + for (int i = 0; i < count; i++) { + res.push_back(i ^ (i >> 1)); + } + return res; + } +}; diff --git a/cpp/892.SurfaceAreaof3DShapes.cpp b/cpp/892.SurfaceAreaof3DShapes.cpp deleted file mode 100644 index e993eb9..0000000 --- a/cpp/892.SurfaceAreaof3DShapes.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { // 8ms 97.15% -public: - int surfaceArea(vector> grid) { - int res = 0, n = grid.size(); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j]) - res += grid[i][j] * 4 + 2; - if (i) - res -= min(grid[i][j], grid[i - 1][j]) * 2; - if (j) - res -= min(grid[i][j], grid[i][j - 1]) * 2; - } - } - return res; - } -}; \ No newline at end of file diff --git a/cpp/892.cpp b/cpp/892.cpp new file mode 100644 index 0000000..6d82608 --- /dev/null +++ b/cpp/892.cpp @@ -0,0 +1,17 @@ +class Solution { // 8ms 97.15% +public: + int surfaceArea(vector> grid) { + int res = 0, n = grid.size(); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j]) + res += grid[i][j] * 4 + 2; + if (i) + res -= min(grid[i][j], grid[i - 1][j]) * 2; + if (j) + res -= min(grid[i][j], grid[i][j - 1]) * 2; + } + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/894.AllPossibleFullBinaryTrees.cpp b/cpp/894.AllPossibleFullBinaryTrees.cpp deleted file mode 100644 index 58bef32..0000000 --- a/cpp/894.AllPossibleFullBinaryTrees.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { //Runtime: 96 ms, faster than 95.53% of C++ online submissions for All Possible Full Binary Trees. -public: - vector allPossibleFBT(int N) { - vector>memory={{},{new TreeNode(0)},{}}; - for(int i=3;i<=N;++i){ - vectorcur; - for(int l=1,r=i-2;lleft=left; - root->right=right; - cur.push_back(root); - } - } - } - } - memory.push_back(move(cur)); - } - return memory[N]; - } -}; \ No newline at end of file diff --git a/cpp/894.cpp b/cpp/894.cpp new file mode 100644 index 0000000..4a726f5 --- /dev/null +++ b/cpp/894.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 96 ms, faster than 95.53% of C++ online submissions + // for All Possible Full Binary Trees. +public: + vector allPossibleFBT(int N) { + vector> memory = {{}, {new TreeNode(0)}, {}}; + for (int i = 3; i <= N; ++i) { + vector cur; + for (int l = 1, r = i - 2; l < i - 1; ++l, --r) { + if (memory[l].size() && memory[r].size()) { + for (auto left : memory[l]) { + for (auto right : memory[r]) { + auto root = new TreeNode(0); + root->left = left; + root->right = right; + cur.push_back(root); + } + } + } + } + memory.push_back(move(cur)); + } + return memory[N]; + } +}; \ No newline at end of file diff --git a/cpp/896.MonotonicArray.cpp b/cpp/896.MonotonicArray.cpp deleted file mode 100644 index 30a9d43..0000000 --- a/cpp/896.MonotonicArray.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { // Runtime: 88 ms, faster than 42.76% of C++ online submissions for Monotonic Array. -public: - bool isMonotonic(vector A) { - bool inc = true, dec = true; - for (int i = 1; i < A.size(); ++i){ - inc &= A[i - 1] <= A[i]; - dec &= A[i - 1] >= A[i]; - } - return inc || dec; - } -}; \ No newline at end of file diff --git a/cpp/896.cpp b/cpp/896.cpp new file mode 100644 index 0000000..90250fd --- /dev/null +++ b/cpp/896.cpp @@ -0,0 +1,12 @@ +class Solution { // Runtime: 88 ms, faster than 42.76% of C++ online submissions + // for Monotonic Array. +public: + bool isMonotonic(vector A) { + bool inc = true, dec = true; + for (int i = 1; i < A.size(); ++i) { + inc &= A[i - 1] <= A[i]; + dec &= A[i - 1] >= A[i]; + } + return inc || dec; + } +}; \ No newline at end of file diff --git a/cpp/897.IncreasingOrderSearchTree.cpp b/cpp/897.IncreasingOrderSearchTree.cpp deleted file mode 100644 index c22a5ba..0000000 --- a/cpp/897.IncreasingOrderSearchTree.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { // Runtime: 36 ms, faster than 94.74% of C++ online submissions for Increasing Order Search Tree. -public: - TreeNode* increasingBST(TreeNode* root) { - TreeNode* head = nullptr,*ret = nullptr; - function inorder = [&](auto node){ - if(not node) - return; - inorder(node->left); - if(not head) - ret = head = node; - else - head = head->right = node; - head->left = nullptr; - inorder(node->right); - }; - inorder(root); - return ret; - } -}; \ No newline at end of file diff --git a/cpp/897.cpp b/cpp/897.cpp new file mode 100644 index 0000000..0baac93 --- /dev/null +++ b/cpp/897.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 36 ms, faster than 94.74% of C++ online submissions + // for Increasing Order Search Tree. +public: + TreeNode *increasingBST(TreeNode *root) { + TreeNode *head = nullptr, *ret = nullptr; + function inorder = [&](auto node) { + if (not node) + return; + inorder(node->left); + if (not head) + ret = head = node; + else + head = head->right = node; + head->left = nullptr; + inorder(node->right); + }; + inorder(root); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/9.PalindromeNumber.cpp b/cpp/9.PalindromeNumber.cpp deleted file mode 100644 index 6caf018..0000000 --- a/cpp/9.PalindromeNumber.cpp +++ /dev/null @@ -1,9 +0,0 @@ -class Solution { //16ms -public: - bool isPalindrome(int x) { - if(x<0) - return false; - auto s=to_string(x); - return string(s.rbegin(),s.rend())==s; - } -}; \ No newline at end of file diff --git a/cpp/9.cpp b/cpp/9.cpp new file mode 100644 index 0000000..9051ada --- /dev/null +++ b/cpp/9.cpp @@ -0,0 +1,9 @@ +class Solution { // 16ms +public: + bool isPalindrome(int x) { + if (x < 0) + return false; + auto s = to_string(x); + return string(s.rbegin(), s.rend()) == s; + } +}; \ No newline at end of file diff --git a/cpp/90.SubsetsII/dfs.cpp b/cpp/90.SubsetsII/dfs.cpp deleted file mode 100644 index b9a952c..0000000 --- a/cpp/90.SubsetsII/dfs.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - vector> subsetsWithDup(vector& nums) { - sort(nums.begin(),nums.end()); - vector>res; - vectorcur; - dfs(nums,res,cur,0); - return res; - } - void dfs(vector&nums,vector>&res,vector&cur,int i){ - res.push_back(cur); - if(i==nums.size()) - return; - for(int start=i;istart&&nums[i]==nums[i-1])continue; - cur.push_back(nums[i]); - dfs(nums,res,cur,i+1); - cur.pop_back(); - } - } -}; diff --git a/cpp/90.cpp b/cpp/90.cpp new file mode 100644 index 0000000..0c16250 --- /dev/null +++ b/cpp/90.cpp @@ -0,0 +1,24 @@ +class Solution { + void dfs(vector& nums, vector>& res, vector& cur, + int i) { + res.push_back(cur); + if (i == nums.size()) + return; + for (int start = i; i < nums.size(); ++i) { + if (i > start && nums[i] == nums[i - 1]) + continue; + cur.push_back(nums[i]); + dfs(nums, res, cur, i + 1); + cur.pop_back(); + } + } + +public: + vector> subsetsWithDup(vector& nums) { + ranges::sort(nums); + vector> res; + vector cur; + dfs(nums, res, cur, 0); + return res; + } +}; diff --git a/cpp/905.SortArrayByParity/singleScan.cpp b/cpp/905.SortArrayByParity/singleScan.cpp deleted file mode 100644 index b735cb1..0000000 --- a/cpp/905.SortArrayByParity/singleScan.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - vector sortArrayByParity(vector& A) { - int i=0,j=A.size()-1; - while(i<=j) - if(A[i]&1) - swap(A[i],A[j--]); - else - ++i; - return A; - } -}; diff --git a/cpp/905.cpp b/cpp/905.cpp new file mode 100644 index 0000000..d1d0543 --- /dev/null +++ b/cpp/905.cpp @@ -0,0 +1,13 @@ +// singleScan.cpp +class Solution { +public: + vector sortArrayByParity(vector &A) { + int i = 0, j = A.size() - 1; + while (i <= j) + if (A[i] & 1) + swap(A[i], A[j--]); + else + ++i; + return A; + } +}; diff --git a/cpp/908.SmallestRangeI.cpp b/cpp/908.SmallestRangeI.cpp deleted file mode 100644 index 540d6c1..0000000 --- a/cpp/908.SmallestRangeI.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { // 24ms -public: - int smallestRangeI(vector& A, int K) { - return max(*max_element(A.begin(),A.end())-*min_element(A.begin(),A.end())-2*K,0); - } -}; -class Solution { //24ms -public: - int smallestRangeI(vector& A, int K) { - auto [minIt,maxIt]=minmax_element(A.begin(),A.end()); - return max(*maxIt-*minIt-2*K,0); - } -}; \ No newline at end of file diff --git a/cpp/908.cpp b/cpp/908.cpp new file mode 100644 index 0000000..9577d36 --- /dev/null +++ b/cpp/908.cpp @@ -0,0 +1,15 @@ +class Solution { // 24ms +public: + int smallestRangeI(vector &A, int K) { + return max(*max_element(A.begin(), A.end()) - + *min_element(A.begin(), A.end()) - 2 * K, + 0); + } +}; +class Solution2 { // 24ms +public: + int smallestRangeI(vector &A, int K) { + auto [minIt, maxIt] = minmax_element(A.begin(), A.end()); + return max(*maxIt - *minIt - 2 * K, 0); + } +}; \ No newline at end of file diff --git a/cpp/91.DecodeWays/DP.cpp b/cpp/91.DecodeWays/DP.cpp deleted file mode 100644 index 8692a45..0000000 --- a/cpp/91.DecodeWays/DP.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - int numDecodings(string s) { - if (s.empty() || (s.size()>=1 && s[0] == '0')) - return 0; - vector dp(s.size()+1, 0); - dp[0]=1; - for (int i=1; i1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6'))) - dp[i] += dp[i-2]; - } - return dp.back(); - } -}; diff --git a/cpp/91.DecodeWays/inverseDP.cpp b/cpp/91.DecodeWays/inverseDP.cpp deleted file mode 100644 index c637010..0000000 --- a/cpp/91.DecodeWays/inverseDP.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int numDecodings(string s) { - int n=s.size(); - if(n==0)return 0; - vectordp(n+1,0); - dp[n]=1; - dp[n-1]=s[n-1]=='0'?0:1; - for(int i=n-2;i>=0;--i){ - if(s[i]=='0')continue; - if( stoi(s.substr(i,2)) <=26){ - dp[i]+=dp[i+2]; - } - dp[i]+=dp[i+1]; - } - return dp[0]; - } -}; diff --git a/cpp/91.cpp b/cpp/91.cpp new file mode 100644 index 0000000..b66b28e --- /dev/null +++ b/cpp/91.cpp @@ -0,0 +1,37 @@ +// DP.cpp +class Solution { +public: + int numDecodings(string s) { + if (s.empty() || (s.size() >= 1 && s[0] == '0')) + return 0; + vector dp(s.size() + 1, 0); + dp[0] = 1; + for (int i = 1; i < dp.size(); i++) { + dp[i] += (s[i - 1] == '0') ? 0 : dp[i - 1]; + if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) + dp[i] += dp[i - 2]; + } + return dp.back(); + } +}; +// inverseDP.cpp +class Solution2 { +public: + int numDecodings(string s) { + int n = s.size(); + if (n == 0) + return 0; + vector dp(n + 1, 0); + dp[n] = 1; + dp[n - 1] = s[n - 1] == '0' ? 0 : 1; + for (int i = n - 2; i >= 0; --i) { + if (s[i] == '0') + continue; + if (stoi(s.substr(i, 2)) <= 26) { + dp[i] += dp[i + 2]; + } + dp[i] += dp[i + 1]; + } + return dp[0]; + } +}; diff --git a/cpp/912.SortanArray.cpp b/cpp/912.SortanArray.cpp deleted file mode 100644 index 5aa6745..0000000 --- a/cpp/912.SortanArray.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -//Runtime: 56 ms, faster than 95.85% of C++ online submissions for Sort an Array. -//Memory Usage: 17.2 MB, less than 13.35% of C++ online submissions for Sort an Array. -public: - vector sortArray(vector& nums) { - vector refmap(50000+50000+1,0); - for(int I:nums) - refmap[I+50000]++; - int idx=0; - for(int i=0;i sortArray(vector &nums) { + vector refmap(50000 + 50000 + 1, 0); + for (int I : nums) + refmap[I + 50000]++; + int idx = 0; + for (int i = 0; i < refmap.size(); i++) + while (refmap[i]--) + nums[idx++] = i - 50000; + return nums; + } +}; \ No newline at end of file diff --git a/cpp/917.ReverseOnlyLetters/twoPointer.cpp b/cpp/917.ReverseOnlyLetters/twoPointer.cpp deleted file mode 100644 index 0855232..0000000 --- a/cpp/917.ReverseOnlyLetters/twoPointer.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - string reverseOnlyLetters(string S) { - for(int i=0,j=S.size()-1;i='a'&&S[i]<='z')||(S[i]>='A'&&S[i]<='Z'))) - ++i; - while(i='a'&&S[j]<='z')||(S[j]>='A'&&S[j]<='Z'))) - --j; - swap(S[i++],S[j--]); - } - return S; - } -}; diff --git a/cpp/917.cpp b/cpp/917.cpp new file mode 100644 index 0000000..ad94930 --- /dev/null +++ b/cpp/917.cpp @@ -0,0 +1,16 @@ +// twoPointer.cpp +class Solution { +public: + string reverseOnlyLetters(string S) { + for (int i = 0, j = S.size() - 1; i < j;) { + while (i < j && + !((S[i] >= 'a' && S[i] <= 'z') || (S[i] >= 'A' && S[i] <= 'Z'))) + ++i; + while (i < j && + !((S[j] >= 'a' && S[j] <= 'z') || (S[j] >= 'A' && S[j] <= 'Z'))) + --j; + swap(S[i++], S[j--]); + } + return S; + } +}; diff --git a/cpp/92.ReverseLinkedListII/iteration.cpp b/cpp/92.ReverseLinkedListII/iteration.cpp deleted file mode 100644 index 9b01f5a..0000000 --- a/cpp/92.ReverseLinkedListII/iteration.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* reverseBetween(ListNode* head, int m, int n) { - if(m==n) - return head; - ListNode newhead(0); - newhead.next=head; - ListNode *left=&newhead; - n-=m-1; - while(--m) - left=left->next; - ListNode *right=left->next; - ListNode *pre=NULL,*now=right; - while(n--){ - ListNode *next=now->next; - now->next=pre; - pre=now; - now=next; - } - left->next=pre; - right->next=now; - return newhead.next; - } -}; diff --git a/cpp/92.cpp b/cpp/92.cpp new file mode 100644 index 0000000..d4a75a8 --- /dev/null +++ b/cpp/92.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + ListNode* reverseBetween(ListNode* head, int m, int n) { + if (m == n) + return head; + ListNode newhead(0, head); + auto left = &newhead; + n -= m - 1; + while (--m) + left = left->next; + auto right = left->next; + ListNode *pre = nullptr, *now = right; + while (n--) { + ListNode* next = now->next; + now->next = pre; + pre = now; + now = next; + } + left->next = pre; + right->next = now; + return newhead.next; + } +}; diff --git a/cpp/922.SortArrayByParityII/singleScan.cpp b/cpp/922.SortArrayByParityII/singleScan.cpp deleted file mode 100644 index d9e95df..0000000 --- a/cpp/922.SortArrayByParityII/singleScan.cpp +++ /dev/null @@ -1,13 +0,0 @@ -class Solution { -public: - vector sortArrayByParityII(vector& A) { - int i=0,j=1; - vector res(A.size()); - for(auto num:A){ - auto& index = num&1 ?j:i; - res[index]=num; - index+=2; - } - return res; - } -}; diff --git a/cpp/922.cpp b/cpp/922.cpp new file mode 100644 index 0000000..30bc653 --- /dev/null +++ b/cpp/922.cpp @@ -0,0 +1,14 @@ +// singleScan.cpp +class Solution { +public: + vector sortArrayByParityII(vector &A) { + int i = 0, j = 1; + vector res(A.size()); + for (auto num : A) { + auto &index = num & 1 ? j : i; + res[index] = num; + index += 2; + } + return res; + } +}; diff --git a/cpp/925.LongPressedName.cpp b/cpp/925.LongPressedName.cpp deleted file mode 100644 index b9d1d0a..0000000 --- a/cpp/925.LongPressedName.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Long Pressed Name. -//Memory Usage: 8.4 MB, less than 85.38% of C++ online submissions for Long Pressed Name. -public: - bool isLongPressedName(string_view name, string_view typed) { - int i=0,j=0; - while(i0&&name[i-1]==name[i]) - return false; - while(j 0 && name[i - 1] == name[i]) + return false; + while (j < typed.size() && name[i - 1] == typed[j]) + ++j; + } + return i == name.size() and j == typed.size(); + } +}; \ No newline at end of file diff --git a/cpp/929.UniqueEmailAddresses.cpp b/cpp/929.UniqueEmailAddresses.cpp deleted file mode 100644 index be965e9..0000000 --- a/cpp/929.UniqueEmailAddresses.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { // Runtime: 28 ms, faster than 97.38% of C++ online submissions for Unique Email Addresses. -public: - int numUniqueEmails(vector& emails) { - unordered_setunique; - for( auto& e: emails ){ - auto pivot = e.find_first_of( '@' ); - auto name = e.substr( 0, pivot ), - domain = e.substr( pivot ); - name.erase( remove( name.begin(), name.end(), '.' ), name.end() ); - auto pos = name.find_first_of( '+' ); - unique.insert( ( pos != string::npos )? name.substr( 0,pos ) + domain : name + domain ); - } - return unique.size(); - } -}; \ No newline at end of file diff --git a/cpp/929.cpp b/cpp/929.cpp new file mode 100644 index 0000000..4372c79 --- /dev/null +++ b/cpp/929.cpp @@ -0,0 +1,16 @@ +class Solution { // Runtime: 28 ms, faster than 97.38% of C++ online submissions + // for Unique Email Addresses. +public: + int numUniqueEmails(vector &emails) { + unordered_set unique; + for (auto &e : emails) { + auto pivot = e.find_first_of('@'); + auto name = e.substr(0, pivot), domain = e.substr(pivot); + name.erase(remove(name.begin(), name.end(), '.'), name.end()); + auto pos = name.find_first_of('+'); + unique.insert((pos != string::npos) ? name.substr(0, pos) + domain + : name + domain); + } + return unique.size(); + } +}; \ No newline at end of file diff --git a/cpp/93.RestoreIPAddresses/dfs.cpp b/cpp/93.RestoreIPAddresses/dfs.cpp deleted file mode 100644 index fe8d503..0000000 --- a/cpp/93.RestoreIPAddresses/dfs.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { - vectorres; -public: - vector restoreIpAddresses(string s) { - dfs("",s,0); - return res; - } - void dfs(string s,string t,int part){ - if(part==4&&t=="") - res.push_back(s); - if(part==4) - return; - if(s!="")s+="."; - for(int i=1;i<=3&&i<=t.size();++i){ - string temp=t.substr(0,i); - if(stoi(temp)>255)continue; - if(i>1&&t[0]=='0')break; - dfs(s+temp,t.substr(i),part+1); - } - } -}; diff --git a/cpp/93.cpp b/cpp/93.cpp new file mode 100644 index 0000000..69d0031 --- /dev/null +++ b/cpp/93.cpp @@ -0,0 +1,29 @@ +// dfs.cpp +class Solution { + vector res; + void dfs(string s, string_view t, int part) { + if (part == 4) { + if (t == "") + res.push_back(s); + return; + } + if (part > 0) + s += "."; + for (int i = 1, val; i <= 3 && i <= t.size(); ++i) { + if (i > 1 && t[0] == '0') + break; + string_view temp = t.substr(0, i); + from_chars(temp.data(), temp.data() + temp.size(), val); + if (val > 255) + break; + dfs(s + string(temp), t.substr(i), + part + 1); // string + string_view require c++26 + } + } + +public: + vector restoreIpAddresses(string s) { + dfs("", s, 0); + return res; + } +}; diff --git a/cpp/933.NumberofRecentCalls.cpp b/cpp/933.NumberofRecentCalls.cpp deleted file mode 100644 index 95e911c..0000000 --- a/cpp/933.NumberofRecentCalls.cpp +++ /dev/null @@ -1,52 +0,0 @@ -class RecentCounter { //188ms 95.89% - vectorbuf; - int lastCallIdx=0; - int binarySearch(int target){ - int l=lastCallIdx,r=buf.size(); - while(l=target) - r=m; - else - l=m+1; - } - return r; - } -public: - RecentCounter() { - - } - - int ping(int t) { - buf.push_back(t); - lastCallIdx=binarySearch(t-3000); - return buf.size()-lastCallIdx; - } -}; - -/** - * Your RecentCounter object will be instantiated and called as such: - * RecentCounter* obj = new RecentCounter(); - * int param_1 = obj->ping(t); - */ - - class RecentCounter { // 204ms with stl - vectorbuf; - int lastCallIdx=0; -public: - RecentCounter() { - - } - - int ping(int t) { - buf.push_back(t); - lastCallIdx=lower_bound(buf.begin()+lastCallIdx,buf.end(),t-3000)-buf.begin(); - return buf.size()-lastCallIdx; - } -}; - -/** - * Your RecentCounter object will be instantiated and called as such: - * RecentCounter* obj = new RecentCounter(); - * int param_1 = obj->ping(t); - */ \ No newline at end of file diff --git a/cpp/933.cpp b/cpp/933.cpp new file mode 100644 index 0000000..a308924 --- /dev/null +++ b/cpp/933.cpp @@ -0,0 +1,30 @@ +class RecentCounter { // 188ms 95.89% + vector buf; + int lastCallIdx = 0; + int binarySearch(int target) { + int l = lastCallIdx, r = buf.size(); + while (l < r) { + int m = l + (r - l) / 2; + if (buf[m] >= target) + r = m; + else + l = m + 1; + } + return r; + } + +public: + RecentCounter() {} + + int ping(int t) { + buf.push_back(t); + lastCallIdx = binarySearch(t - 3000); + return buf.size() - lastCallIdx; + } +}; + +/** + * Your RecentCounter object will be instantiated and called as such: + * RecentCounter* obj = new RecentCounter(); + * int param_1 = obj->ping(t); + */ \ No newline at end of file diff --git a/cpp/938.RangeSumofBST.cpp b/cpp/938.RangeSumofBST.cpp deleted file mode 100644 index 94c96a3..0000000 --- a/cpp/938.RangeSumofBST.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -public: - int rangeSumBST(TreeNode* root, int L, int R) { - if(!root) - return 0; - if(root->val>R) - return rangeSumBST(root->left,L,R); - if(root->valright,L,R); - return root->val+rangeSumBST(root->right,L,R)+rangeSumBST(root->left,L,R); - } -}; \ No newline at end of file diff --git a/cpp/938.cpp b/cpp/938.cpp new file mode 100644 index 0000000..70bd95b --- /dev/null +++ b/cpp/938.cpp @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int rangeSumBST(TreeNode *root, int L, int R) { + if (!root) + return 0; + if (root->val > R) + return rangeSumBST(root->left, L, R); + if (root->val < L) + return rangeSumBST(root->right, L, R); + return root->val + rangeSumBST(root->right, L, R) + + rangeSumBST(root->left, L, R); + } +}; \ No newline at end of file diff --git a/cpp/94.BinaryTreeInorderTraversal/iteration.cpp b/cpp/94.BinaryTreeInorderTraversal/iteration.cpp deleted file mode 100644 index 6549142..0000000 --- a/cpp/94.BinaryTreeInorderTraversal/iteration.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - vectorinorder; -public: - vector inorderTraversal(TreeNode* root) { - stackst; - while(1){ - while(root!=NULL){ - st.push(root); - root=root->left; - } - if(st.empty())break; - root=st.top(); - st.pop(); - inorder.push_back(root->val); - root=root->right; - } - return inorder; - } -}; diff --git a/cpp/94.cpp b/cpp/94.cpp new file mode 100644 index 0000000..362ce09 --- /dev/null +++ b/cpp/94.cpp @@ -0,0 +1,41 @@ +class Solution { + vector inorder; + +public: + vector inorderTraversal(TreeNode* root) { + stack st; + while (1) { + while (root != nullptr) { + st.push(root); + root = root->left; + } + if (st.empty()) + break; + root = st.top(); + st.pop(); + inorder.push_back(root->val); + root = root->right; + } + return inorder; + } +}; +class SolutionDFS { + void impl(vector& res, TreeNode* node) { + if (!node) + return; + if (node->left) { + impl(res, node->left); + } + res.push_back(node->val); + if (node->right) { + impl(res, node->right); + } + } + +public: + vector inorderTraversal(TreeNode* root) { + vector res; + impl(res, root); + return res; + } +}; \ No newline at end of file diff --git a/cpp/95.UniqueBinarySearchTreesII/dp+inorder.cpp b/cpp/95.UniqueBinarySearchTreesII/dp+inorder.cpp deleted file mode 100644 index 302d924..0000000 --- a/cpp/95.UniqueBinarySearchTreesII/dp+inorder.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - TreeNode* generate(TreeNode *root,int &val){ - if(root==nullptr) - return nullptr; - TreeNode *l=generate(root->left,val); - TreeNode *node=new TreeNode(val++); - TreeNode *r=generate(root->right,val); - node->left=l; - node->right=r; - return node; - } -public: - vector generateTrees(int n) { - if(n==0) - return vector(); - vector>dp(n+1,vector()); - dp[0].push_back(nullptr); - for(int i=1;i<=n;++i){ - int m=0,n=i-1; - while(n>=0){ - for(auto lchild:dp[m]){ - for(auto rchild:dp[n]){ - TreeNode *node=new TreeNode(0); - node->left=lchild; - node->right=rchild; - dp[i].push_back(node); - } - } - ++m,--n; - } - } - vectorres; - for(auto node:dp.back()){ - int i=1; - res.push_back( generate(node,i) ); - } - return res; - } -}; diff --git a/cpp/95.cpp b/cpp/95.cpp new file mode 100644 index 0000000..3e744b1 --- /dev/null +++ b/cpp/95.cpp @@ -0,0 +1,50 @@ +// dp+inorder.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + TreeNode* generate(TreeNode* root, int& val) { + if (root == nullptr) + return nullptr; + TreeNode* l = generate(root->left, val); + TreeNode* node = new TreeNode(val++); + TreeNode* r = generate(root->right, val); + node->left = l; + node->right = r; + return node; + } + +public: + vector generateTrees(int n) { + if (n == 0) + return {}; + vector> dp(n + 1, vector()); + dp[0].push_back(nullptr); + for (int i = 1; i <= n; ++i) { + int m = 0, n = i - 1; + while (n >= 0) { + for (auto lchild : dp[m]) { + for (auto rchild : dp[n]) { + TreeNode* node = new TreeNode(0); + node->left = lchild; + node->right = rchild; + dp[i].push_back(node); + } + } + ++m, --n; + } + } + vector res; + for (auto node : dp.back()) { + int i = 1; + res.push_back(generate(node, i)); + } + return res; + } +}; diff --git a/cpp/951.FlipEquivalentBinaryTrees.cpp b/cpp/951.FlipEquivalentBinaryTrees.cpp deleted file mode 100644 index 8a39bfa..0000000 --- a/cpp/951.FlipEquivalentBinaryTrees.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 4 ms, faster than 93.18% of C++ online submissions for Flip Equivalent Binary Trees. -//Memory Usage: 11.8 MB, less than 53.59% of C++ online submissions for Flip Equivalent Binary Trees. -public: - bool flipEquiv(TreeNode* root1, TreeNode* root2) { - if ((!root1 && root2) || (root1 && !root2)) - return false; - return (!root1)||((root1->val ==root2->val) && ( - (flipEquiv (root1->right, root2->left) && flipEquiv (root1->left, root2->right) ) || - (flipEquiv (root1->left, root2->left) && flipEquiv (root1->right, root2->right) ) )); - } -}; \ No newline at end of file diff --git a/cpp/951.cpp b/cpp/951.cpp new file mode 100644 index 0000000..43656ab --- /dev/null +++ b/cpp/951.cpp @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 4 ms, faster than 93.18% of C++ online submissions for Flip + // Equivalent Binary Trees. Memory Usage: 11.8 MB, less than 53.59% of C++ + // online submissions for Flip Equivalent Binary Trees. +public: + bool flipEquiv(TreeNode *root1, TreeNode *root2) { + if ((!root1 && root2) || (root1 && !root2)) + return false; + return (!root1) || ((root1->val == root2->val) && + ((flipEquiv(root1->right, root2->left) && + flipEquiv(root1->left, root2->right)) || + (flipEquiv(root1->left, root2->left) && + flipEquiv(root1->right, root2->right)))); + } +}; \ No newline at end of file diff --git a/cpp/953.VerifyinganAlienDictionary.cpp b/cpp/953.VerifyinganAlienDictionary.cpp deleted file mode 100644 index 3001f6d..0000000 --- a/cpp/953.VerifyinganAlienDictionary.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - bool isAlienSorted(vector &words, string order) { - size_t indices[26]{}; - for (size_t i = 0; i < order.size(); ++i) - indices[order[i] - 'a'] = i; - return is_sorted(words.begin(), words.end(), [&indices](const string &w1,const string &w2 - ) { - auto l1 = w1.size(), l2 = w2.size(); - for (auto i = 0; i < min(l1, l2); ++i) { - auto c1 = w1[i], c2 = w2[i]; - if (c1 != c2) - return indices[c1 - 'a'] < indices[c2 - 'a']; - } - return l1 < l2; - }); - } -}; \ No newline at end of file diff --git a/cpp/953.cpp b/cpp/953.cpp new file mode 100644 index 0000000..e614dba --- /dev/null +++ b/cpp/953.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool isAlienSorted(vector &words, string order) { + size_t indices[26]{}; + for (size_t i = 0; i < order.size(); ++i) + indices[order[i] - 'a'] = i; + return is_sorted(words.begin(), words.end(), + [&indices](const string &w1, const string &w2) { + auto l1 = w1.size(), l2 = w2.size(); + for (auto i = 0; i < min(l1, l2); ++i) { + auto c1 = w1[i], c2 = w2[i]; + if (c1 != c2) + return indices[c1 - 'a'] < indices[c2 - 'a']; + } + return l1 < l2; + }); + } +}; \ No newline at end of file diff --git a/cpp/96.UniqueBinarySearchTree/dp.cpp b/cpp/96.UniqueBinarySearchTree/dp.cpp deleted file mode 100644 index 0d66a09..0000000 --- a/cpp/96.UniqueBinarySearchTree/dp.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - int numTrees(int n) { - vectordp(n+1,0); - if(n<=1)return 1; - dp[0]=dp[1]=1; - for(int i=2;i<=n;++i) - for(int j=1;j<=i;++j) - dp[i]+=dp[j-1]*dp[i-j]; - return dp[n]; - } -}; diff --git a/cpp/96.cpp b/cpp/96.cpp new file mode 100644 index 0000000..63e58f2 --- /dev/null +++ b/cpp/96.cpp @@ -0,0 +1,14 @@ +// dp.cpp +class Solution { +public: + int numTrees(int n) { + vector dp(n + 1, 0); + if (n <= 1) + return 1; + dp[0] = dp[1] = 1; + for (int i = 2; i <= n; ++i) + for (int j = 1; j <= i; ++j) + dp[i] += dp[j - 1] * dp[i - j]; + return dp[n]; + } +}; diff --git a/cpp/961.N-RepeatedElementinSize2NArray.cpp b/cpp/961.N-RepeatedElementinSize2NArray.cpp deleted file mode 100644 index 9661321..0000000 --- a/cpp/961.N-RepeatedElementinSize2NArray.cpp +++ /dev/null @@ -1,8 +0,0 @@ -class Solution { //Runtime: 40 ms, faster than 93.40% of C++ online submissions for N-Repeated Element in Size 2N Array. -public: - int repeatedNTimes(vector& A) { - int i = 0, j = 0; - while (A[i = rand() % A.size()] != A[j = rand() % A.size()] || i == j); - return A[i]; - } -}; \ No newline at end of file diff --git a/cpp/961.cpp b/cpp/961.cpp new file mode 100644 index 0000000..43530b8 --- /dev/null +++ b/cpp/961.cpp @@ -0,0 +1,10 @@ +class Solution { // Runtime: 40 ms, faster than 93.40% of C++ online submissions + // for N-Repeated Element in Size 2N Array. +public: + int repeatedNTimes(vector &A) { + int i = 0, j = 0; + while (A[i = rand() % A.size()] != A[j = rand() % A.size()] || i == j) + ; + return A[i]; + } +}; \ No newline at end of file diff --git a/cpp/965.UnivaluedBinaryTree.cpp b/cpp/965.UnivaluedBinaryTree.cpp deleted file mode 100644 index 669461f..0000000 --- a/cpp/965.UnivaluedBinaryTree.cpp +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Univalued Binary Tree. -public: - bool isUnivalTree(TreeNode* root,TreeNode* parent=nullptr) { - if(not root) - return true; - return (parent?root->val==parent->val:true) and isUnivalTree(root->left,root) and isUnivalTree(root->right,root); - } -}; \ No newline at end of file diff --git a/cpp/965.cpp b/cpp/965.cpp new file mode 100644 index 0000000..b03d2ab --- /dev/null +++ b/cpp/965.cpp @@ -0,0 +1,19 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 0 ms, faster than 100.00% of C++ online submissions + // for Univalued Binary Tree. +public: + bool isUnivalTree(TreeNode *root, TreeNode *parent = nullptr) { + if (not root) + return true; + return (parent ? root->val == parent->val : true) and + isUnivalTree(root->left, root) and isUnivalTree(root->right, root); + } +}; \ No newline at end of file diff --git a/cpp/97.InterleavingString/TLE_dfs.cpp b/cpp/97.InterleavingString/TLE_dfs.cpp deleted file mode 100644 index 5c08e8a..0000000 --- a/cpp/97.InterleavingString/TLE_dfs.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - bool isInterleave(string s1, string s2, string s3) { - if(s1.size()+s2.size()!=s3.size()) - return 0; - return dfs(s1,s2,s3,0,0,0); - } - bool dfs(string& s1,string& s2,string& s3,int i,int j,int k){ - if(i==s1.size()&&j==s2.size()) - return true; - bool res=0; - if(i>dp(n1+1,vector(n2+1,0)); - dp[0][0]=1; - for(int i=0;i<=n1;++i) - for(int j=0;j<=n2;++j) - if(i>0&&dp[i-1][j]) - dp[i][j]=s3[i+j-1]==s1[i-1]; - else if(j>0&&dp[i][j-1]&&dp[i][j]!=1) - dp[i][j]=s3[i+j-1]==s2[j-1]; - return dp[n1][n2]; - } -}; diff --git a/cpp/97.cpp b/cpp/97.cpp new file mode 100644 index 0000000..ffa9db7 --- /dev/null +++ b/cpp/97.cpp @@ -0,0 +1,37 @@ +// dp.cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int n1 = s1.size(), n2 = s2.size(), n3 = s3.size(); + if (n1 + n2 != n3) + return 0; + vector> dp(n1 + 1, vector(n2 + 1, 0)); + dp[0][0] = 1; + for (int i = 0; i <= n1; ++i) + for (int j = 0; j <= n2; ++j) + if (i > 0 && dp[i - 1][j]) + dp[i][j] = s3[i + j - 1] == s1[i - 1]; + else if (j > 0 && dp[i][j - 1] && dp[i][j] != 1) + dp[i][j] = s3[i + j - 1] == s2[j - 1]; + return dp[n1][n2]; + } +}; +// TLE_dfs.cpp +class Solution2 { + bool impl(string_view s1, string_view s2, string_view s3) { + if (s1.size() == 0 && s2.size() == 0) + return true; + if (s1.size() && s1[0] == s3[0] && impl(s1.substr(1), s2, s3.substr(1))) + return true; + if (s2.size() && s2[0] == s3[0] && impl(s1, s2.substr(1), s3.substr(1))) + return true; + return false; + } + +public: + bool isInterleave(string s1, string s2, string s3) { + if (s1.size() + s2.size() != s3.size()) + return false; + return impl(s1, s2, s3); + } +}; diff --git a/cpp/973.KClosestPointstoOrigin.cpp b/cpp/973.KClosestPointstoOrigin.cpp deleted file mode 100644 index 60751e9..0000000 --- a/cpp/973.KClosestPointstoOrigin.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -//Runtime: 240 ms, faster than 80.16% of C++ online submissions for K Closest Points to Origin. -//Memory Usage: 36.9 MB, less than 92.75% of C++ online submissions for K Closest Points to Origin. -public: - vector> kClosest(vector>& points, int K) { - struct compare { - bool operator()(vector& p, vector& q) { - return p[0] * p[0] + p[1] * p[1] < q[0] * q[0] + q[1] * q[1]; - } - }cmp; - vector> heap(points.begin(),points.begin()+K); - make_heap(heap.begin(),heap.end(),cmp); - for (int i=K;i> kClosest(vector> &points, int K) { + struct compare { + bool operator()(vector &p, vector &q) { + return p[0] * p[0] + p[1] * p[1] < q[0] * q[0] + q[1] * q[1]; + } + } cmp; + vector> heap(points.begin(), points.begin() + K); + make_heap(heap.begin(), heap.end(), cmp); + for (int i = K; i < points.size(); ++i) + if (cmp(points[i], heap[0])) { + pop_heap(heap.begin(), heap.end(), cmp); + heap.pop_back(); + heap.push_back(move(points[i])); + push_heap(heap.begin(), heap.end(), cmp); + } + return heap; + } +}; \ No newline at end of file diff --git a/cpp/977.SquaresofaSortedArray.cpp b/cpp/977.SquaresofaSortedArray.cpp deleted file mode 100644 index 0eafe32..0000000 --- a/cpp/977.SquaresofaSortedArray.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { // Runtime: 100 ms, faster than 96.05% of C++ online submissions for Squares of a Sorted Array. -public: - vector sortedSquares(vector& A) { - vector res; - int mid = lower_bound(begin(A), end(A), 0) - begin(A); - for (int r = mid, l = mid - 1; r < A.size() || l >= 0;) { - int lval=l>=0?A[l]*A[l]:numeric_limits::max(); - int rval=r::max(); - if(lval sortedSquares(vector &A) { + vector res; + int mid = lower_bound(begin(A), end(A), 0) - begin(A); + for (int r = mid, l = mid - 1; r < A.size() || l >= 0;) { + int lval = l >= 0 ? A[l] * A[l] : numeric_limits::max(); + int rval = r < A.size() ? A[r] * A[r] : numeric_limits::max(); + if (lval < rval) { + res.push_back(lval); + --l; + } else { + res.push_back(rval); + ++r; + } + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/979.DistributeCoinsInBinaryTree.cpp b/cpp/979.DistributeCoinsInBinaryTree.cpp deleted file mode 100644 index e7c7df0..0000000 --- a/cpp/979.DistributeCoinsInBinaryTree.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { -//Runtime: 8 ms, faster than 88.79% of C++ online submissions for Distribute Coins in Binary Tree. -//Memory Usage: 13.2 MB, less than 59.61% of C++ online submissions for Distribute Coins in Binary Tree. -public: - int distributeCoins(TreeNode* root) { - int ret=0; - function recursion= [&ret,&recursion](TreeNode*root){ - if(!root) - return 0; - auto leftNeed=recursion(root->left); - auto rightNeed=recursion(root->right); - ret+=abs(leftNeed)+abs(rightNeed); - root->val-=leftNeed+rightNeed; - return 1-root->val; - }; - recursion(root); - return ret; - } -}; \ No newline at end of file diff --git a/cpp/979.cpp b/cpp/979.cpp new file mode 100644 index 0000000..e464cd5 --- /dev/null +++ b/cpp/979.cpp @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + // Runtime: 8 ms, faster than 88.79% of C++ online submissions for Distribute + // Coins in Binary Tree. Memory Usage: 13.2 MB, less than 59.61% of C++ online + // submissions for Distribute Coins in Binary Tree. +public: + int distributeCoins(TreeNode *root) { + int ret = 0; + function recursion = [&ret, &recursion](TreeNode *root) { + if (!root) + return 0; + auto leftNeed = recursion(root->left); + auto rightNeed = recursion(root->right); + ret += abs(leftNeed) + abs(rightNeed); + root->val -= leftNeed + rightNeed; + return 1 - root->val; + }; + recursion(root); + return ret; + } +}; \ No newline at end of file diff --git a/cpp/98.ValidateBinarySearchTree/inorderTraversal.cpp b/cpp/98.ValidateBinarySearchTree/inorderTraversal.cpp deleted file mode 100644 index 009d8f7..0000000 --- a/cpp/98.ValidateBinarySearchTree/inorderTraversal.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - long long int last=0x8000000000000000; - bool valid=1; -public: - bool isValidBST(TreeNode* root) { - if(root==NULL)return 1; - isValidBST(root->left); - valid=root->val>last?valid:0; - last=root->val; - isValidBST(root->right); - return valid; - } -}; diff --git a/cpp/98.cpp b/cpp/98.cpp new file mode 100644 index 0000000..a1f6d81 --- /dev/null +++ b/cpp/98.cpp @@ -0,0 +1,25 @@ +// inorderTraversal.cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { + long long int last = 0x8000000000000000; + bool valid = 1; + +public: + bool isValidBST(TreeNode* root) { + if (root == nullptr) + return 1; + isValidBST(root->left); + valid = root->val > last ? valid : 0; + last = root->val; + isValidBST(root->right); + return valid; + } +}; diff --git a/cpp/983.MinimumCostForTickets.cpp b/cpp/983.MinimumCostForTickets.cpp deleted file mode 100644 index 1d83c83..0000000 --- a/cpp/983.MinimumCostForTickets.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -//Runtime: 4 ms, faster than 91.52% of C++ online submissions for Minimum Cost For Tickets. -//Memory Usage: 9.2 MB, less than 35.23% of C++ online submissions for Minimum Cost For Tickets. -public: - int mincostTickets(vector& days, vector& costs) { - unordered_set travel(begin(days), end(days)); - int dp[366] = {}; - for (int i = 1; i < 366; ++i) - if (not travel.count(i)) - dp[i] = dp[i - 1]; - else - dp[i] = min({ dp[i - 1] + costs[0], dp[max(0, i - 7)] + costs[1], dp[max(0, i - 30)] + costs[2]}); - return dp[365]; - } -}; \ No newline at end of file diff --git a/cpp/983.cpp b/cpp/983.cpp new file mode 100644 index 0000000..05706a0 --- /dev/null +++ b/cpp/983.cpp @@ -0,0 +1,17 @@ +class Solution { + // Runtime: 4 ms, faster than 91.52% of C++ online submissions for Minimum + // Cost For Tickets. Memory Usage: 9.2 MB, less than 35.23% of C++ online + // submissions for Minimum Cost For Tickets. +public: + int mincostTickets(vector &days, vector &costs) { + unordered_set travel(begin(days), end(days)); + int dp[366] = {}; + for (int i = 1; i < 366; ++i) + if (not travel.count(i)) + dp[i] = dp[i - 1]; + else + dp[i] = min({dp[i - 1] + costs[0], dp[max(0, i - 7)] + costs[1], + dp[max(0, i - 30)] + costs[2]}); + return dp[365]; + } +}; \ No newline at end of file diff --git a/cpp/986.IntervalListIntersections.cpp b/cpp/986.IntervalListIntersections.cpp deleted file mode 100644 index d38f0b5..0000000 --- a/cpp/986.IntervalListIntersections.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - vector> intervalIntersection(vector>& A, vector>& B) { - vector> res; - for (auto i = 0, j = 0; i < A.size() && j < B.size(); ) { - if (A[i][1] < B[j][0]) - ++i; - else if (B[j][1] < A[i][0]) - ++j; - else { - res.push_back({ max(A[i][0], B[j][0]), min(A[i][1], B[j][1]) }); - if (A[i][1] < B[j][1]) - ++i; - else - ++j; - } - } - return res; - } -}; \ No newline at end of file diff --git a/cpp/986.cpp b/cpp/986.cpp new file mode 100644 index 0000000..c5e3f3b --- /dev/null +++ b/cpp/986.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector> intervalIntersection(vector> &A, + vector> &B) { + vector> res; + for (auto i = 0, j = 0; i < A.size() && j < B.size();) { + if (A[i][1] < B[j][0]) + ++i; + else if (B[j][1] < A[i][0]) + ++j; + else { + res.push_back({max(A[i][0], B[j][0]), min(A[i][1], B[j][1])}); + if (A[i][1] < B[j][1]) + ++i; + else + ++j; + } + } + return res; + } +}; \ No newline at end of file diff --git a/cpp/99.RecoverBinarySearchTree/inorder.cpp b/cpp/99.RecoverBinarySearchTree/inorder.cpp deleted file mode 100644 index d31a467..0000000 --- a/cpp/99.RecoverBinarySearchTree/inorder.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - TreeNode *m1,*m2,*pre=NULL; - bool firstOne=1; -public: - void recoverTree(TreeNode* root) { - inorder(root); - int temp=m1->val; - m1->val=m2->val; - m2->val=temp; - } - void inorder(TreeNode* root){ - if(root==NULL)return; - inorder(root->left); - if(pre){ - if(firstOne && root->val < pre->val){ - m1=pre; - firstOne=0; - } - if(!firstOne && root->val < pre->val){ - m2=root; - } - } - pre=root; - inorder(root->right); - } -}; diff --git a/cpp/99.cpp b/cpp/99.cpp new file mode 100644 index 0000000..549c717 --- /dev/null +++ b/cpp/99.cpp @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} + * }; + */ +class Solution { + TreeNode *m1 = nullptr, *m2 = nullptr, *pre = nullptr; + void inorder(TreeNode* root) { + if (root == nullptr) + return; + inorder(root->left); + if (pre) { + if (!m1 && root->val < pre->val) { + m1 = pre; + } + if (m1 && root->val < pre->val) { + m2 = root; + } + } + pre = root; + inorder(root->right); + } + +public: + void recoverTree(TreeNode* root) { + inorder(root); + swap(m1->val, m2->val); + } +}; diff --git a/cpp/993.CousinsinBinaryTree.cpp b/cpp/993.CousinsinBinaryTree.cpp deleted file mode 100644 index 8258910..0000000 --- a/cpp/993.CousinsinBinaryTree.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { // Runtime: 0 ms -public: - bool isCousins(TreeNode* root, int x, int y) { - queue q; - q.push(root); - int found = 0; - int p[2]={-2,-2}; - while (q.size()) { - auto size = q.size(); - while (size--) { - auto n = q.front(); - q.pop(); - if (n) { - if (n->val == x || n->val == y) - p[found++]=size; - q.push(n->left), q.push(n->right); - } - } - if(found) - return found == 2&&p[0]/2!=p[1]/2; - } - return false; - } -}; \ No newline at end of file diff --git a/cpp/993.cpp b/cpp/993.cpp new file mode 100644 index 0000000..c021df6 --- /dev/null +++ b/cpp/993.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { // Runtime: 0 ms +public: + bool isCousins(TreeNode *root, int x, int y) { + queue q; + q.push(root); + int found = 0; + int p[2] = {-2, -2}; + while (q.size()) { + auto size = q.size(); + while (size--) { + auto n = q.front(); + q.pop(); + if (n) { + if (n->val == x || n->val == y) + p[found++] = size; + q.push(n->left), q.push(n->right); + } + } + if (found) + return found == 2 && p[0] / 2 != p[1] / 2; + } + return false; + } +}; \ No newline at end of file diff --git a/cpp/999.AvailableCapturesforRook.cpp b/cpp/999.AvailableCapturesforRook.cpp deleted file mode 100644 index 53b159f..0000000 --- a/cpp/999.AvailableCapturesforRook.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution { // 0ms -public: - int numRookCaptures(vector>& b) { - const vector> dir={{1,0},{0,1},{-1,0},{0,-1}}; - int ret=0; - for (auto i = 0; i < b.size(); ++i) - for (auto j = 0; j < b[i].size(); ++j) - if (b[i][j] == 'R'){ - for(const auto [dx,dy]:dir){ - int x=i,y=j; - while (x >= 0 && x < b.size() && y >= 0 && y < b[x].size() && b[x][y] != 'B'){ - if (b[x][y] == 'p'){ - ++ret; - break; - } - x += dx; - y += dy; - } - } - break; - } - return ret; - } -}; \ No newline at end of file diff --git a/cpp/999.cpp b/cpp/999.cpp new file mode 100644 index 0000000..9ded798 --- /dev/null +++ b/cpp/999.cpp @@ -0,0 +1,25 @@ +class Solution { // 0ms +public: + int numRookCaptures(vector> &b) { + const vector> dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + int ret = 0; + for (auto i = 0; i < b.size(); ++i) + for (auto j = 0; j < b[i].size(); ++j) + if (b[i][j] == 'R') { + for (const auto [dx, dy] : dir) { + int x = i, y = j; + while (x >= 0 && x < b.size() && y >= 0 && y < b[x].size() && + b[x][y] != 'B') { + if (b[x][y] == 'p') { + ++ret; + break; + } + x += dx; + y += dy; + } + } + break; + } + return ret; + } +}; \ No newline at end of file diff --git a/cpp/rename.py b/cpp/rename.py deleted file mode 100644 index 62942dc..0000000 --- a/cpp/rename.py +++ /dev/null @@ -1,13 +0,0 @@ -import shutil -import os - - -files = os.listdir(os.path.dirname(__file__)) -files = list(filter(lambda f:" " in f,files)) - -for f in files: - newname = "".join(f.title().split(" ")) - if not newname.endswith(".cpp"): - newname += ".cpp" - print(f,"=>",newname) - shutil.move(f,newname) \ No newline at end of file diff --git a/cpp/trick.cpp b/cpp/trick.cpp new file mode 100644 index 0000000..f652ef1 --- /dev/null +++ b/cpp/trick.cpp @@ -0,0 +1,9 @@ +int x = []() { + std::ios::sync_with_stdio(false); + cin.tie(NULL); + return 0; +}(); + +class Solution { +public: +}; diff --git "a/cpp/\351\252\232\346\223\215\344\275\234.cpp" "b/cpp/\351\252\232\346\223\215\344\275\234.cpp" deleted file mode 100644 index 047aa31..0000000 --- "a/cpp/\351\252\232\346\223\215\344\275\234.cpp" +++ /dev/null @@ -1,9 +0,0 @@ -int x=[](){ - std::ios::sync_with_stdio(false); - cin.tie(NULL); - return 0; -}(); - -class Solution { -public: -}; diff --git a/genmarkdown.py b/genmarkdown.py new file mode 100644 index 0000000..712f8d4 --- /dev/null +++ b/genmarkdown.py @@ -0,0 +1,44 @@ +import os + +import requests + +print('reading problems list...') +api = "https://leetcode.com/api/problems/all/" +r = requests.get(api) + +j = r.json() +problems = [{'id': problem['stat']['question_id'], 'title': problem['stat']['question__title'], 'difficulty':problem['difficulty']['level'], 'vip':problem['paid_only']} + for problem in j['stat_status_pairs']] +problems.sort(key=lambda x: x['id']) + +print('generate markdown...') +md = ''' +![Build](https://github.com/HONGJICAI/LeetCode/actions/workflows/ci-cpp.yml/badge.svg) + +# LeetCode + +my solution for LeetCode + +# Problem List + +| id | title | language | difficulty | +| ---- | ---- | ---- | ---- | +''' +difficultyMap = {1: 'easy', 2: 'medium', 3: 'hard'} +solvedIds = {} +for f in os.listdir('cpp') + os.listdir('sql'): + id, ext = os.path.splitext(f) + ext = ext[1:] + if str.isdigit(id): + if int(id) not in solvedIds: + solvedIds[int(id)] = f'[{ext}]({ext}/{id}.{ext})' + else: + solvedIds[int(id)] += f' [{ext}]({ext}/{id}.{ext})' + +for problem in filter(lambda x: int(x['id']) <= max(solvedIds), problems): + id = problem['id'] + language = solvedIds[id] if id in solvedIds else '' + md += f"| {id} | {problem['title']} | {language} | {difficultyMap[problem['difficulty']]} |\n" + +with open('README.md', 'w') as f: + f.write(md) diff --git a/python3/1.TwoSum.py b/python3/1.TwoSum.py deleted file mode 100644 index 1ef47d5..0000000 --- a/python3/1.TwoSum.py +++ /dev/null @@ -1,12 +0,0 @@ -class Solution: - def twoSum(self, nums, target): - """ - :type nums: List[int] - :type target: int - :rtype: List[int] - """ - d={} - for i in range(len(nums)): - if target - nums[i] in d: - return d[target-nums[i]],i - d[nums[i]]=i \ No newline at end of file diff --git a/sql/175.sql b/sql/175.sql new file mode 100644 index 0000000..094bda1 --- /dev/null +++ b/sql/175.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +select p.FirstName, p.LastName, a.City, a.State +from Person p left join Address a +on p.PersonId = a.PersonId \ No newline at end of file diff --git a/sql/176.sql b/sql/176.sql new file mode 100644 index 0000000..c8b875b --- /dev/null +++ b/sql/176.sql @@ -0,0 +1,2 @@ +# Write your MySQL query statement below +SELECT MAX(salary) AS SecondHighestSalary FROM Employee WHERE salary < (SELECT MAX(salary)FROM Employee); diff --git a/sql/177.sql b/sql/177.sql new file mode 100644 index 0000000..494ae5d --- /dev/null +++ b/sql/177.sql @@ -0,0 +1,8 @@ +CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT +BEGIN +set N = N - 1; + RETURN ( + # Write your MySQL query statement below. + select distinct Salary from Employee order by Salary desc limit 1 offset N + ); +END \ No newline at end of file diff --git a/sql/181.sql b/sql/181.sql new file mode 100644 index 0000000..7259435 --- /dev/null +++ b/sql/181.sql @@ -0,0 +1,5 @@ +# Write your MySQL query statement below +select e1.name as Employee +from employee e1 inner join employee e2 +on e1.managerId = e2.id +where e1.salary > e2.salary \ No newline at end of file diff --git a/sql/182.sql b/sql/182.sql new file mode 100644 index 0000000..d93a168 --- /dev/null +++ b/sql/182.sql @@ -0,0 +1,7 @@ +# Write your MySQL query statement below +select Email +from +(select Email, count(*) as C +from Person +group by email) P +where C > 1 \ No newline at end of file diff --git a/sql/183.sql b/sql/183.sql new file mode 100644 index 0000000..ce80957 --- /dev/null +++ b/sql/183.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +select name as Customers +from Customers +where id not in (select distinct customerId from Orders) \ No newline at end of file diff --git a/sql/184.sql b/sql/184.sql new file mode 100644 index 0000000..89e58ec --- /dev/null +++ b/sql/184.sql @@ -0,0 +1,9 @@ +# Write your MySQL query statement below +select dname as Department, e.name as Employee, e.salary +from Employee e +inner join +(select d.name as dname, d.Id as did, max(e.Salary) as MaxSalary +from Employee e inner join Department d +on departmentId = d.id +group by d.name, d.id) DepartmentMaxSalary +on e.departmentId = did and e.salary = MaxSalary \ No newline at end of file diff --git a/sql/196.sql b/sql/196.sql new file mode 100644 index 0000000..1793fa6 --- /dev/null +++ b/sql/196.sql @@ -0,0 +1,9 @@ +# Write your MySQL query statement below +delete +from Person +where id not in ( + select * from( + select min(id) + from Person p + group by email)p +) \ No newline at end of file diff --git a/sql/197.sql b/sql/197.sql new file mode 100644 index 0000000..a3e2aa7 --- /dev/null +++ b/sql/197.sql @@ -0,0 +1,4 @@ +# Write your MySQL query statement below +select w2.Id +from Weather w1 inner join Weather w2 +where adddate(w1.recordDate, 1) = w2.recordDate and w1.temperature < w2.temperature \ No newline at end of file