├── 1. Two Sums.md ├── 10. Regular Expression Matching.md ├── 100. Same Tree.md ├── 1007. Minimum Domino Rotations For Equal Row.md ├── 101. Symmetric Tree.md ├── 1011. Capacity To Ship Packages Within D Days.md ├── 102. Binary Tree Level Order Traversal.md ├── 1028. Recover a Tree From Preorder Traversal.md ├── 1029. Two City Scheduling.md ├── 103. Binary Tree Zigzag Level Order Traversal.md ├── 1030. Matrix Cells in Distance Order.md ├── 104. Maximum Depth of Binary Tree.md ├── 1042. Flower Planting With No Adjacent.md ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.md ├── 1057.Campus Bikes.md ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.md ├── 1066. 校园自行车分配 II.md ├── 107. Binary Tree Level Order Traversal II.md ├── 108. Convert Sorted Array to Binary Search Tree.md ├── 109. Convert Sorted List to Binary Search Tree.md ├── 11. Container With Most Water.md ├── 110. Balanced Binary Tree.md ├── 111. Minimum Depth of Binary Tree.md ├── 112. Path Sum.md ├── 113. Path Sum II.md ├── 1130. Minimum Cost Tree From Leaf Values.md ├── 114. Flatten Binary Tree to Linked List.md ├── 115. Distinct Subsequences.md ├── 116. Populating Next Right Pointers in Each Node.md ├── 118. Pascal's Triangle.md ├── 119. Pascal's Triangle II.md ├── 12. Integer to Roman.md ├── 120. Triangle.md ├── 1207. Unique Number of Occurrences.md ├── 1208. Get Equal Substrings Within Budget.md ├── 1209. Remove All Adjacent Duplicates in String II.md ├── 121. Best Time to Buy and Sell Stock.md ├── 122. Best Time to Buy and Sell Stock II.md ├── 123. Best Time to Buy and Sell Stock III.md ├── 124. Binary Tree Maximum Path Sum.md ├── 125. Valid Palindrome.md ├── 126. Word Ladder II.md ├── 128. Longest Consecutive Sequence.md ├── 129. Sum Root to Leaf Numbers.md ├── 13. Roman to Integer.md ├── 130. Surrounded Regions.md ├── 131. Palindrome Partitioning.md ├── 132. Palindrome Partitioning II.md ├── 133. Clone Graph.md ├── 134. Gas Station.md ├── 135. Candy.md ├── 136. Single Number.md ├── 137. Single Number II.md ├── 138. Copy List with Random Pointer.md ├── 139. Word Break.md ├── 14. Longest Common Prefix.md ├── 140. Word Break II.md ├── 141. Linked List Cycle.md ├── 142. Linked List Cycle II.md ├── 143. Reorder List.md ├── 145. Binary Tree Postorder Traversal.md ├── 146. LRU Cache.md ├── 147. Insertion Sort List.md ├── 148. Sort List.md ├── 15. 3Sum.md ├── 150. Evaluate Reverse Polish Notation.md ├── 151. Reverse Words in a String.md ├── 152. Maximum Product Subarray.md ├── 153. Find Minimum in Rotated Sorted Array.md ├── 154. Find Minimum in Rotated Sorted Array II.md ├── 155. Min Stack.md ├── 16. 3Sum Closest.md ├── 160. Intersection of Two Linked Lists.md ├── 161. One Edit Distance.md ├── 162. Find Peak Element.md ├── 163. Missing Ranges.md ├── 167. Two Sum II - Input array is sorted.md ├── 168. Excel Sheet Column Title.md ├── 169. Majority Element.md ├── 171. Excel Sheet Column Number.md ├── 172. Factorial Trailing Zeroes.md ├── 173. Binary Search Tree Iterator.md ├── 18. 4Sum.md ├── 189. Rotate Array.md ├── 19. Remove Nth Node From End of List.md ├── 190. Reverse Bits.md ├── 191. Number of 1 Bits.md ├── 198. House Robber.md ├── 199. Binary Tree Right Side View.md ├── 2. Add Two Numbers.md ├── 20. Valid Parentheses.md ├── 200. Number of Islands.md ├── 201. Bitwise AND of Numbers Range.md ├── 2018_Practice_ProblemA_GBus count ├── A-large-practice.in ├── A-small-practice.in ├── Solution_1.py ├── Solution_2.py ├── out_large_1.txt ├── out_large_2.txt ├── out_small.txt └── out_small_2.txt ├── 2018_Practice_ProblemB_Googol String ├── B-large-practice.in ├── B-small-practice.in ├── out_large.txt ├── out_small.txt └── solution_1.py ├── 2018_Practice_ProblemC_SortItinerary ├── C-large-practice.in ├── C-small-practice.in ├── out-large.txt ├── out-small.txt ├── solution_1.py └── test.in ├── 2018_Practice_ProblemD_SumofSum ├── D-large-practice.in ├── D-out-large.txt ├── D-out-small.txt ├── D-small-practice.in └── solution_1.py ├── 2018_RoundB_ProblemA_No_Nice ├── A-small-practice.in ├── A-small-practice.out └── No_Nice.py ├── 2018_RoundB_ProblemB_Sherlock_and the Bit Strings ├── B-large-practice.in ├── B-large-practice.out ├── B-small-practice.in ├── B-small-practice.out └── solution.py ├── 2018_RoundH_ProblemA_BigButtons ├── A-large-practice.in ├── A-large-practice.out ├── A-small-practice.in ├── A-small-practice.out ├── readme.md └── solution.py ├── 2018_RoundH_ProblemB_Mural ├── B-large-practice.in ├── B-large-practice.out ├── B-small-practice.in ├── B-small-practice.out ├── readme.md └── solution.py ├── 2018_RoundH_ProblemC_LetMeCountTheWays ├── C-large-practice.in ├── C-small-practice.in ├── readme.md └── solution.py ├── 202. Happy Number.md ├── 203. Remove Linked List Elements.md ├── 204. Count Primes.md ├── 205. Isomorphic Strings.md ├── 206. Reverse Linked List.md ├── 207. Course Schedule.md ├── 208. Implement Trie (Prefix Tree).md ├── 209. Minimum Size Subarray Sum.md ├── 21. Merge Two Sorted Lists.md ├── 210. Course Schedule II.md ├── 211. Add and Search Word - Data structure design.md ├── 212. Word Search II.md ├── 213. House Robber II.md ├── 214. Shortest Palindrome.md ├── 215. Kth Largest Element in an Array.md ├── 216. Combination Sum III.md ├── 217. Contains Duplicate.md ├── 219. Contains Duplicate II.md ├── 22. Generate Parentheses.md ├── 220. Contains Duplicate III.md ├── 221. Maximal Square.md ├── 222. Count Complete Tree Nodes.md ├── 223. Rectangle Area.md ├── 225. Implement Stack using Queues.md ├── 226. Invert Binary Tree.md ├── 228. Summary Ranges.md ├── 229. Majority Element II.md ├── 23. Merge k Sorted Lists.md ├── 230. Kth Smallest Element in a BST.md ├── 231. Power of Two.md ├── 232. Implement Queue using Stacks.md ├── 234. Palindrome Linked List.md ├── 235. Lowest Common Ancestor of a Binary Search Tree.md ├── 236. Lowest Common Ancestor of a Binary Tree.md ├── 237. Delete Node in a Linked List.md ├── 238. Product of Array Except Self.md ├── 239. Sliding Window Maximum.md ├── 24. Swap Nodes in Pairs.md ├── 240. Search a 2D Matrix II.md ├── 241. Different Ways to Add Parentheses.md ├── 242. Valid Anagram.md ├── 246. Strobogrammatic Number.md ├── 247. Strobogrammatic Number II.md ├── 248. Strobogrammatic Number III.md ├── 25. Reverse Nodes in k-Group.md ├── 251. Flatten 2D Vector.md ├── 252. Meeting Rooms.md ├── 253. Meeting Rooms II.md ├── 257. Binary Tree Paths.md ├── 258. Add Digits.md ├── 26. Remove Duplicates from Sorted Array.md ├── 260. Single Number III.md ├── 263. Ugly Number.md ├── 264. Ugly Number II.md ├── 266. Palindrome Permutation.md ├── 268. Missing Number.md ├── 269. Alien Dictionary 另类字典.md ├── 270. Closest Binary Search Tree Value.md ├── 273. Integer to English Words.md ├── 274. H-Index.md ├── 277. Find the Celebrity.md ├── 278. First Bad Version.md ├── 279. Perfect Squares.md ├── 282. Expression Add Operators.md ├── 283. Move Zeroes.md ├── 284. Peeking Iterator.md ├── 285. Inorder Successor in BST.md ├── 286. Walls and Gates.md ├── 287. Find the Duplicate Number.md ├── 289. Game of Life.md ├── 29. Divide Two Integers.md ├── 290. Word Pattern.md ├── 292. Nim Game.md ├── 295. Find Median from Data Stream.md ├── 296. Best Meeting Point 最佳开会地点.md ├── 297. Serialize and Deserialize Binary Tree.md ├── 299. Bulls and Cows.md ├── 3. Longest Substring Without Repeating Characters.md ├── 30. Substring with Concatenation of All Words.md ├── 300. Longest Increasing Subsequence.md ├── 303. Range Sum Query - Immutable.md ├── 304. Range Sum Query 2D - Immutable.md ├── 306. Additive Number.md ├── 309. Best Time to Buy and Sell Stock with Cooldown.md ├── 31. Next Permutation.md ├── 31. Partition Array.md ├── 310. Minimum Height Trees.md ├── 311. Sparse Matrix Multiplication.md ├── 313. Super Ugly Number.md ├── 314. Binary Tree Vertical Order Traversal.md ├── 315. Count of Smaller Numbers After Self.md ├── 316. Remove Duplicate Letters.md ├── 317.Shortest Distance from All Buildings.md ├── 318. Maximum Product of Word Lengths.md ├── 319. Bulb Switcher.md ├── 32. Longest Valid Parentheses.md ├── 321. Create Maximum Number.md ├── 322. Coin Change.md ├── 326. Power of Three.md ├── 327. Count of Range Sum.md ├── 328. Odd Even Linked List.md ├── 329. Longest Increasing Path in a Matrix.md ├── 33. Search in Rotated Sorted Array.md ├── 330. Patching Array.md ├── 332. Reconstruct Itinerary.md ├── 334. Increasing Triplet Subsequence.md ├── 335. Self Crossing.md ├── 336. Palindrome Pairs.md ├── 337. House Robber III.md ├── 338. Counting Bits.md ├── 34. Find First and Last Position of Element in Sorted Array.md ├── 340. Longest Substring with At Most K Distinct Characters.md ├── 342. Power of Four.md ├── 344. Reverse String.md ├── 347. Top K Frequent Elements.md ├── 349. Intersection of Two Arrays.md ├── 35. Search Insert Position.md ├── 350. Intersection of Two Arrays II.md ├── 354. Russian Doll Envelopes.md ├── 357. Count Numbers with Unique Digits.md ├── 36. Valid Sudoku.md ├── 363. Max Sum of Rectangle No Larger Than K.md ├── 365. Water and Jug Problem.md ├── 367. Valid Perfect Square.md ├── 368. Largest Divisible Subset.md ├── 372. Super Pow.md ├── 374. Guess Number Higher or Lower.md ├── 375. Guess Number Higher or Lower II.md ├── 376. Wiggle Subsequence.md ├── 377. Combination Sum IV.md ├── 378. Kth Smallest Element in a Sorted Matrix.md ├── 38. Count and Say.md ├── 380. Insert Delete GetRandom O(1).md ├── 382. Linked List Random Node.md ├── 383. Ransom Note.md ├── 385. Mini Parser.md ├── 387. First Unique Character in a String.md ├── 389. Find the Difference.md ├── 39. Combination Sum.md ├── 390. Elimination Game.md ├── 394. Decode String.md ├── 395. Longest Substring with At Least K Repeating Characters.md ├── 396. Rotate Function.md ├── 397. Integer Replacement.md ├── 398. Random Pick Index.md ├── 399. Evaluate Division.md ├── 4. Median of Two Sorted Arrays.md ├── 40. Combination Sum II.md ├── 400. Nth Digit.md ├── 401. Binary Watch.md ├── 402. Remove K Digits.md ├── 403. Frog Jump.md ├── 404. Sum of Left Leaves.md ├── 405. Convert a Number to Hexadecimal.md ├── 408. valid word abbreviation.md ├── 409. Longest Palindrome.md ├── 41. First Missing Positive.md ├── 410. Split Array Largest Sum.md ├── 413. Arithmetic Slices.md ├── 414. Third Maximum Number.md ├── 415. Add Strings.md ├── 416. Partition Equal Subset Sum.md ├── 419. Battleships in a Board.md ├── 42. Trapping Rain Water.md ├── 420. Strong Password Checker.md ├── 423. Reconstruct Original Digits from English.md ├── 424. Longest Repeating Character Replacement.md ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List.md ├── 427. Construct Quad Tree.md ├── 429. N-ary Tree Level Order Traversal.md ├── 43. Multiply Strings.md ├── 430. Flatten a Multilevel Doubly Linked List.md ├── 433. Minimum Genetic Mutation.md ├── 434. Number of Segments in a String.md ├── 435. Non-overlapping Intervals.md ├── 437. Path Sum III.md ├── 438. Find All Anagrams in a String.md ├── 440. K-th Smallest in Lexicographical Order.md ├── 441. Arranging Coins.md ├── 442. Find All Duplicates in an Array.md ├── 443. String Compression.md ├── 446. Arithmetic Slices II - Subsequence.md ├── 447. Number of Boomerangs.md ├── 448. Find All Numbers Disappeared in an Array.md ├── 449. Serialize and Deserialize BST.md ├── 45. Jump Game II.md ├── 450. Delete Node in a BST.md ├── 451. Sort Characters By Frequency.md ├── 452. Minimum Number of Arrows to Burst Balloons.md ├── 453. Minimum Moves to Equal Array Elements.md ├── 454. 4Sum II.md ├── 455. Assign Cookies.md ├── 456. 132 Pattern.md ├── 459. Repeated Substring Pattern.md ├── 46. Permutations.md ├── 461. Hamming Distance.md ├── 462. Minimum Moves to Equal Array Elements II.md ├── 463. Island Perimeter.md ├── 464. Can I Win.md ├── 465. Optimal Account Balancing 最优账户平衡.md ├── 467. Unique Substrings in Wraparound String.md ├── 47. Permutations II.md ├── 470. Implement Rand10() Using Rand7().md ├── 472. Concatenated Words.md ├── 473. Matchsticks to Square.md ├── 474. Ones and Zeroes.md ├── 475. Heaters.md ├── 476. Number Complement.md ├── 477. Total Hamming Distance.md ├── 478. Generate Random Point in a Circle.md ├── 48. Rotate Image.md ├── 480. Sliding Window Median.md ├── 481. Magical String.md ├── 482. License Key Formatting.md ├── 485. Max Consecutive Ones.md ├── 486. Predict the Winner.md ├── 49. Group Anagrams.md ├── 490.The Maze.md ├── 492. Construct the Rectangle.md ├── 493. Reverse Pairs.md ├── 494. Target Sum.md ├── 495. Teemo Attacking.md ├── 496. Next Greater Element I.md ├── 498. Diagonal Traverse.md ├── 5. Longest Palindromic Substring.md ├── 50. Pow(x, n).md ├── 501. Find Mode in Binary Search Tree.md ├── 503. Next Greater Element II.md ├── 504. Base 7.md ├── 505. The Maze II.md ├── 506. Relative Ranks.md ├── 507. Perfect Number.md ├── 508. Most Frequent Subtree Sum.md ├── 510. Inorder Successor in BST II.md ├── 513. Find Bottom Left Tree Value.md ├── 514. Freedom Trail.md ├── 515. Find Largest Value in Each Tree Row.md ├── 516. Longest Palindromic Subsequence.md ├── 518. Coin Change 2.md ├── 520. Detect Capital.md ├── 5213. Play with Chips.md ├── 5214. Longest Arithmetic Subsequence of Given Difference.md ├── 5215. Path with Maximum Gold.md ├── 5216. Count Vowels Permutation.md ├── 523. Continuous Subarray Sum.md ├── 524. Longest Word in Dictionary through Deleting.md ├── 525. Contiguous Array.md ├── 527. Word Abbreviation.md ├── 528. Random Pick with Weight.md ├── 53. Maximum Subarray.md ├── 531. Lonely Pixel I.md ├── 532. K-diff Pairs in an Array.md ├── 532. Reverse Pairs.md ├── 533. Lonely Pixel II.md ├── 536. Construct Binary Tree from String.md ├── 537. Complex Number Multiplication.md ├── 538. Convert BST to Greater Tree.md ├── 539. Minimum Time Difference.md ├── 54. Spiral Matrix.md ├── 540. Single Element in a Sorted Array.md ├── 541. Reverse String II.md ├── 542. 01 Matrix.md ├── 544. Output Contest Matches.md ├── 545. Boundary of Binary Tree.md ├── 548. Split Array with Equal Sum.md ├── 55. Jump Game.md ├── 554. Brick Wall.md ├── 556. Next Greater Element III .md ├── 557. Reverse Words in a String III.md ├── 56. Merge Intervals.md ├── 560. Subarray Sum Equals K.md ├── 562.Longest Line of Consecutive One in Matrix.md ├── 567. Permutation in String.md ├── 57. Insert Interval.md ├── 572. Subtree of Another Tree.md ├── 59. Spiral Matrix II.md ├── 6. ZigZag Conversion.md ├── 60. Permutation Sequence.md ├── 609. Find Duplicate File in System.md ├── 61. Rotate List.md ├── 62. Unique Paths.md ├── 621. Task Scheduler.md ├── 622. Design Circular Queue.md ├── 63. Unique Paths II.md ├── 632. Smallest Range Covering Elements from K Lists.md ├── 636. Exclusive Time of Functions.md ├── 639. Decode Ways II.md ├── 64. Minimum Path Sum.md ├── 658. Find K Closest Elements.md ├── 671. Second Minimum Node In a Binary Tree.md ├── 673. Number of Longest Increasing Subsequence.md ├── 678. Valid Parenthesis String.md ├── 68. Text Justification.md ├── 680. Valid Palindrome II.md ├── 681. Next Closest Time.md ├── 688. Knight Probability in Chessboard.md ├── 689. Maximum Sum of 3 Non-Overlapping Subarrays.md ├── 69. Sqrt(x).md ├── 694. Number of Distinct Islands.md ├── 697. Degree of an Array.md ├── 7. Reverse Integer.md ├── 70. Climbing Stairs.md ├── 703. Kth Largest Element in a Stream.md ├── 706. Design HashMap.md ├── 708. Insert into a Cyclic Sorted List.md ├── 71. Simplify Path.md ├── 72. Edit Distance.md ├── 721. Accounts Merge.md ├── 73. Set Matrix Zeroes.md ├── 74. Search a 2D Matrix.md ├── 75. Sort Colors.md ├── 752. Open the Lock .md ├── 76. Minimum Window Substring.md ├── 77. Combinations.md ├── 77. Combinations_.md ├── 777. Swap Adjacent in LR String.md ├── 78. Subsets.md ├── 780. Reaching Points.md ├── 783. Minimum Distance Between BST Nodes.md ├── 785. Is Graph Bipartite.md ├── 79. Word Search.md ├── 791. Custom Sort String.md ├── 8. String to Integer (atoi).md ├── 80. Remove Duplicates from Sorted Array II.md ├── 809. Expressive Words.md ├── 82. Remove Duplicates from Sorted List II.md ├── 824. Goat Latin.md ├── 825. Friends Of Appropriate Ages.md ├── 83. Remove Duplicates from Sorted List.md ├── 833. Find And Replace in String.md ├── 84. Largest Rectangle in Histogram.md ├── 844. Backspace String Compare.md ├── 849. Maximize Distance to Closest Person.md ├── 857. Minimum Cost to Hire K Workers.md ├── 86. Partition List.md ├── 862. Shortest Subarray with Sum at Least K.md ├── 865. Smallest Subtree with all the Deepest Nodes.md ├── 88. Lowest Common Ancestor of a Binary Tree.md ├── 88. Merge Sorted Array.md ├── 89. Gray Code.md ├── 894. All Possible Full Binary Trees.md ├── 896. Monotonic Array.md ├── 9. Palindrome Number.md ├── 90. Subsets II.md ├── 900. RLE Iterator.md ├── 904. Fruit Into Baskets.md ├── 91. Decode Ways.md ├── 918. Maximum Sum Circular Subarray.md ├── 92. Reverse Linked List II.md ├── 921. Minimum Add to Make Parentheses Valid.md ├── 929. Unique Email Addresses.md ├── 935. Knight Dialer.md ├── 939. Minimum Area Rectangle.md ├── 94. Binary Tree Inorder Traversal.md ├── 947. Most Stones Removed with Same Row or Column.md ├── 95. Unique Binary Search Trees II.md ├── 953. Verifying an Alien Dictionary.md ├── 958. Check Completeness of a Binary Tree.md ├── 973. K Closest Points to Origin.md ├── 975. Odd Even Jump.md ├── 977. Squares of a Sorted Array.md ├── 98. Validate Binary Search Tree.md ├── 986. Interval List Intersections.md ├── 987. Vertical Order Traversal of a Binary Tree.md ├── 99. Recover Binary Search Tree.md ├── Amazon OA 2019 763. Partition Labels.md ├── Amazon OA 2019 957. Prison Cells After N Days.md ├── Amazon OA 2019 Distance Between Nodes in BST.md ├── Amazon OA 2019 Favorite Genres.md ├── Amazon OA 2019 Find Pair With Max Appeal Sum.md ├── Amazon OA 2019 Min Cost to Connect All Nodes.md ├── Amazon OA 2019 Path With Maximum Score.md ├── Amazon OA 2019 Substrings of size K with K distinct chars.md ├── Amazon OA 2019 Substrings with exactly K distinct chars.md ├── Amazon OA 2019 Two Sum - Unique Pairs.md ├── Amazon 819. Most Common Word.md ├── Amazon Deside Up or Down.md ├── Amazon Find Median from Data Stream.md ├── Amazon Interview Question Add Water.md ├── Amazon Word Break and Concatenated Words.md ├── Amazon. 1192. Critical Connections in a Network.md ├── Amazon. 937. Reorder Data in Log Files.md ├── Amazon. Min Cost to Connect Ropes.md ├── Amazon. Movies on Flight.md ├── Amazon. Treasure Island II.md ├── Amazon. Treasure Island.md ├── Amazon.Optimal Utilization.md ├── ByteDance.md ├── ByteDance_Spider_Detector.md ├── ByteDance_Video_Interview.md ├── Count Print Characters.md ├── Facebook 1094. Car Pooling.md ├── Facebook Balance Parentheses.md ├── Facebook Caesar Cipher Encrpytion.md ├── Facebook Phone Screen CSV Dinosaurs.md ├── Facebook Phone Screen Redundant Paths.md ├── Google Interview Document.docx ├── Mathworks OA 2019 Traveling is Fun.md ├── Maximal value among shortest distances in a matrix.md ├── MemDev Find Perfect Substring.md ├── Minimum steps to reach target by a Knight.md ├── Number of subarrays having sum exactly equal to k.md ├── Power of Three.md ├── Quora OA.md ├── README.md ├── Twittwe. OA.md ├── Uber Follow-up of 122. Best Time to Buy and Sell Stock II.md ├── Uber Segerate Odd and Even.md ├── Uber Strange Pairs.md ├── Uber Valid Matrix.md ├── WeChat Image_20191027222101.jpg ├── [Google]ChocolateSweetness.md ├── [Google]Local Max.md ├── [Google]Software Version Generation.md ├── [Google]Water Flowers.md ├── [Quora]concatenationsSum.md ├── [Quora]countTinyPairs.md ├── [Quora]mergeStrings.md ├── [Quora]mutateTheArray.md ├── google电面.md ├── java_3150103638_hw1.pdf ├── kickstart2019_roundA_training.md └── kickstart_super_2048.md /1. Two Sums.md: -------------------------------------------------------------------------------- 1 | ## 1. Two Sum 2 | 3 | 4 | Given an array of integers, return **indices** of the two numbers such that they add up to a specific target. 5 | 6 | You may assume that each input would have **exactly** one solution, and you may not use the *same* element twice. 7 | 8 | **Example:** 9 | 10 | ``` 11 | Given nums = [2, 7, 11, 15], target = 9, 12 | 13 | Because nums[0] + nums[1] = 2 + 7 = 9, 14 | return [0, 1]. 15 | ``` 16 | 17 | **Solution:** 18 | 19 | 我怎么三个月前做过这道题,完全没印象。。。。 20 | 21 | 用map方法很精妙而且很快! 22 | 23 | 12/22 再看。一开始还是没想出来orz。 24 | 25 | **TIPS:** 26 | 27 | ``` 28 | cur = [1,2,3] 29 | 30 | tmp = cur # 浅拷贝 共享 31 | 32 | tmp = cur[:] # 深拷贝 33 | 34 | ``` 35 | 36 | **Code:** 37 | 38 | ``` 39 | class Solution: 40 | def twoSum(self, nums, target): 41 | """ 42 | :type nums: List[int] 43 | :type target: int 44 | :rtype: List[int] 45 | """ 46 | map = {} 47 | for t in range(len(nums)): 48 | if target - nums[t] in map: 49 | return [t, map[target-nums[t]]] 50 | else: 51 | map[nums[t]] = t 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /100. Same Tree.md: -------------------------------------------------------------------------------- 1 | # 100. Same Tree 2 | 3 | Given two binary trees, write a function to check if they are the same or not. 4 | 5 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 1 1 11 | / \ / \ 12 | 2 3 2 3 13 | 14 | [1,2,3], [1,2,3] 15 | 16 | Output: true 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: 1 1 23 | / \ 24 | 2 2 25 | 26 | [1,2], [1,null,2] 27 | 28 | Output: false 29 | ``` 30 | 31 | **Example 3:** 32 | 33 | ``` 34 | Input: 1 1 35 | / \ / \ 36 | 2 1 1 2 37 | 38 | [1,2,1], [1,1,2] 39 | 40 | Output: false 41 | ``` 42 | 43 | 44 | 45 | ## Solution 46 | 47 | 递归就好了。 48 | 49 | 不递归也不难,但是比较麻烦。 50 | 51 | 52 | 53 | ## Code 54 | 55 | ```python 56 | # Definition for a binary tree node. 57 | # class TreeNode: 58 | # def __init__(self, x): 59 | # self.val = x 60 | # self.left = None 61 | # self.right = None 62 | 63 | class Solution: 64 | def isSameTree(self, p, q): 65 | """ 66 | :type p: TreeNode 67 | :type q: TreeNode 68 | :rtype: bool 69 | """ 70 | if p is None and q is None: 71 | return True 72 | elif p is None or q is None: 73 | return False 74 | else: 75 | return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(q.right,p.right) 76 | ``` 77 | 78 | -------------------------------------------------------------------------------- /1029. Two City Scheduling.md: -------------------------------------------------------------------------------- 1 | # \1029. Two City Scheduling 2 | 3 | There are `2N` people a company is planning to interview. The cost of flying the `i`-th person to city `A` is `costs[i][0]`, and the cost of flying the `i`-th person to city `B` is `costs[i][1]`. 4 | 5 | Return the minimum cost to fly every person to a city such that exactly `N` people arrive in each city. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: [[10,20],[30,200],[400,50],[30,20]] 13 | Output: 110 14 | Explanation: 15 | The first person goes to city A for a cost of 10. 16 | The second person goes to city A for a cost of 30. 17 | The third person goes to city B for a cost of 50. 18 | The fourth person goes to city B for a cost of 20. 19 | 20 | The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. 21 | ``` 22 | 23 | 24 | 25 | **Note:** 26 | 27 | 1. `1 <= costs.length <= 100` 28 | 2. It is guaranteed that `costs.length` is even. 29 | 3. `1 <= costs[i][0], costs[i][1] <= 1000` 30 | 31 | 32 | 33 | ## Code 34 | 35 | ```python 36 | class Solution(object): 37 | def twoCitySchedCost(self, costs): 38 | """ 39 | :type costs: List[List[int]] 40 | :rtype: int 41 | """ 42 | length = len(costs) 43 | ranks = [] 44 | diff = [costs[i][1] - costs[i][0] for i in range(length)] 45 | result = sum(costs[i][0] for i in range(length)) 46 | diff.sort(reverse = True) 47 | result += sum(diff[length/2:]) 48 | return result 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /106. Construct Binary Tree from Inorder and Postorder Traversal.md: -------------------------------------------------------------------------------- 1 | # 106. Construct Binary Tree from Inorder and Postorder Traversal 2 | 3 | Given inorder and postorder traversal of a tree, construct the binary tree. 4 | 5 | **Note:** 6 | You may assume that duplicates do not exist in the tree. 7 | 8 | For example, given 9 | 10 | ``` 11 | inorder = [9,3,15,20,7] 12 | postorder = [9,15,7,20,3] 13 | ``` 14 | 15 | Return the following binary tree: 16 | 17 | ``` 18 | 3 19 | / \ 20 | 9 20 21 | / \ 22 | 15 7 23 | ``` 24 | 25 | 26 | 27 | ## Solution 28 | 29 | 和105几乎一样,preorde改成postorder那就从后面直接pop就好了。 30 | 31 | 32 | 33 | ## Code 34 | 35 | ```python 36 | # Definition for a binary tree node. 37 | # class TreeNode: 38 | # def __init__(self, x): 39 | # self.val = x 40 | # self.left = None 41 | # self.right = None 42 | 43 | class Solution: 44 | def buildTree(self, inorder, postorder): 45 | """ 46 | :type inorder: List[int] 47 | :type postorder: List[int] 48 | :rtype: TreeNode 49 | """ 50 | if len(inorder) == 0: 51 | root = None 52 | else: 53 | # print('i',inorder) 54 | # print('p',postorder) 55 | root_val = postorder[-1] 56 | index = inorder.index(root_val) 57 | root = TreeNode(root_val) 58 | root.left = self.buildTree(inorder[:index],postorder[:index]) 59 | root.right = self.buildTree(inorder[index+1:],postorder[index:-1]) 60 | 61 | return root 62 | ``` 63 | 64 | -------------------------------------------------------------------------------- /108. Convert Sorted Array to Binary Search Tree.md: -------------------------------------------------------------------------------- 1 | # 108. Convert Sorted Array to Binary Search Tree 2 | 3 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 4 | 5 | For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of *every* node never differ by more than 1. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Given the sorted array: [-10,-3,0,5,9], 11 | 12 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 13 | 14 | 0 15 | / \ 16 | -3 9 17 | / / 18 | -10 5 19 | ``` 20 | 21 | 22 | 23 | ## Solution 24 | 25 | Tree这边递归真是好用到所有题都是easy模式> < 26 | 27 | 28 | 29 | ## Code 30 | 31 | ```python 32 | # Definition for a binary tree node. 33 | # class TreeNode: 34 | # def __init__(self, x): 35 | # self.val = x 36 | # self.left = None 37 | # self.right = None 38 | 39 | class Solution: 40 | def sortedArrayToBST(self, nums): 41 | """ 42 | :type nums: List[int] 43 | :rtype: TreeNode 44 | """ 45 | if nums: 46 | index = len(nums)//2 47 | root = TreeNode(nums[index]) 48 | root.left = self.sortedArrayToBST(nums[:index]) 49 | root.right = self.sortedArrayToBST(nums[index+1:]) 50 | 51 | return root 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /11. Container With Most Water.md: -------------------------------------------------------------------------------- 1 | ## 11. Container With Most Water 2 | 3 | Given *n* non-negative integers *a1*, *a2*, ..., *an* , where each represents a point at coordinate (*i*, *ai*). *n* vertical lines are drawn such that the two endpoints of line *i* is at (*i*, *ai*) and (*i*, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 4 | 5 | **Note:** You may not slant the container and *n* is at least 2. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: [1,8,6,2,5,4,8,3,7] 11 | Output: 49 12 | ``` 13 | 14 | **Resolution:** 15 | 16 | 在list起始位置设置两个指针 i 和 j ,如果 a[i] < a[j],则 i++, 否则 j++,直到两个指针相遇。 17 | 18 | 方法来源戳[这里](https://www.acwing.com/solution/leetcode/content/100/)。 19 | 20 | 太机智了orz,自己推一下推导过程。 21 | 22 | 23 | 24 | **Code:** 25 | 26 | ```python 27 | class Solution: 28 | def maxArea(self, height): 29 | """ 30 | :type height: List[int] 31 | :rtype: int 32 | """ 33 | result = 0 34 | i = 0 35 | j = len(height)-1 36 | while i < j: 37 | result = max(result, min(height[i], height[j])*(j-i)) 38 | if height[i] < height[j]: 39 | i += 1 40 | else: 41 | j -= 1 42 | return int(result) 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /118. Pascal's Triangle.md: -------------------------------------------------------------------------------- 1 | # 118. Pascal's Triangle 2 | 3 | Given a non-negative integer *numRows*, generate the first *numRows* of Pascal's triangle. 4 | 5 | ![img](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) 6 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 7 | 8 | **Example:** 9 | 10 | ``` 11 | Input: 5 12 | Output: 13 | [ 14 | [1], 15 | [1,1], 16 | [1,2,1], 17 | [1,3,3,1], 18 | [1,4,6,4,1] 19 | ] 20 | ``` 21 | 22 | 23 | 24 | ## Code: 25 | 26 | ```python 27 | class Solution(object): 28 | def generate(self, numRows): 29 | """ 30 | :type numRows: int 31 | :rtype: List[List[int]] 32 | """ 33 | result = [] 34 | if numRows == 0: 35 | return result 36 | for i in range(numRows): 37 | ls = [] 38 | if i == 0: 39 | ls.append(1) 40 | else: 41 | ls.append(1) 42 | for k in range(i-1): 43 | ls.append(result[-1][k]+result[-1][k+1]) 44 | ls.append(1) 45 | 46 | result.append(ls) 47 | return(result) 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /119. Pascal's Triangle II.md: -------------------------------------------------------------------------------- 1 | # 119. Pascal's Triangle II 2 | 3 | Given a non-negative index *k* where *k* ≤ 33, return the *k*th index row of the Pascal's triangle. 4 | 5 | Note that the row index starts from 0. 6 | 7 | ![img](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) 8 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 9 | 10 | **Example:** 11 | 12 | ``` 13 | Input: 3 14 | Output: [1,3,3,1] 15 | ``` 16 | 17 | ## Solution: 18 | 19 | 最简单的就code1,和118的方法一样。 20 | 21 | 如果要求O(k)的额外空间,就只保留当前层和上一层就好了呀。 22 | 23 | 24 | 25 | ## Code: 26 | 27 | ```python 28 | class Solution(object): 29 | def getRow(self, rowIndex): 30 | """ 31 | :type rowIndex: int 32 | :rtype: List[int] 33 | """ 34 | result = [] 35 | for i in range(rowIndex+1): 36 | ls = [] 37 | if i == 0: 38 | ls.append(1) 39 | else: 40 | ls.append(1) 41 | for k in range(i-1): 42 | ls.append(result[-1][k]+result[-1][k+1]) 43 | ls.append(1) 44 | result.append(ls) 45 | return(ls) 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /1207. Unique Number of Occurrences.md: -------------------------------------------------------------------------------- 1 | # 1207. Unique Number of Occurrences 2 | 3 | Given an array of integers `arr`, write a function that returns `true` if and only if the number of occurrences of each value in the array is unique. 4 | 5 | 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: arr = [1,2,2,1,1,3] 11 | Output: true 12 | Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. 13 | ``` 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: arr = [1,2] 19 | Output: false 20 | ``` 21 | 22 | **Example 3:** 23 | 24 | ``` 25 | Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] 26 | Output: true 27 | ``` 28 | 29 | 30 | 31 | **Constraints:** 32 | 33 | - `1 <= arr.length <= 1000` 34 | - `-1000 <= arr[i] <= 1000` 35 | 36 | 37 | 38 | ## Code 39 | 40 | ```python 41 | class Solution(object): 42 | def uniqueOccurrences(self, arr): 43 | """ 44 | :type arr: List[int] 45 | :rtype: bool 46 | """ 47 | map = {} 48 | for num in arr: 49 | map[num] = map.get(num,0) + 1 50 | 51 | nums = map.values() 52 | res = set() 53 | for num in nums: 54 | if num in res: 55 | return False 56 | else: 57 | res.add(num) 58 | return True 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /125. Valid Palindrome.md: -------------------------------------------------------------------------------- 1 | # 125. Valid Palindrome 2 | 3 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 4 | 5 | **Note:** For the purpose of this problem, we define empty string as valid palindrome. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: "A man, a plan, a canal: Panama" 11 | Output: true 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: "race a car" 18 | Output: false 19 | ``` 20 | 21 | 22 | 23 | ## Solution 24 | 25 | 两指针指向头尾,往中间靠拢,直到两边都是字母/数字,比较,相同就continue,不同就break。 26 | 27 | ## Code 28 | 29 | ```python 30 | class Solution(object): 31 | def isPalindrome(self, s): 32 | """ 33 | :type s: str 34 | :rtype: bool 35 | """ 36 | length = len(s) 37 | flag = True 38 | if length <= 1: 39 | return flag 40 | head = 0 41 | tail = length-1 42 | s = s.lower() 43 | while head < tail: 44 | while head=0 and not s[tail].isalnum(): 47 | tail -= 1 48 | if head=0: 49 | if s[head] == s[tail]: 50 | tail -= 1 51 | head += 1 52 | continue 53 | else: 54 | flag = False 55 | break 56 | 57 | return flag 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /131. Palindrome Partitioning.md: -------------------------------------------------------------------------------- 1 | # 131. Palindrome Partitioning 2 | 3 | Given a string *s*, partition *s* such that every substring of the partition is a palindrome. 4 | 5 | Return all possible palindrome partitioning of *s*. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: "aab" 11 | Output: 12 | [ 13 | ["aa","b"], 14 | ["a","a","b"] 15 | ] 16 | ``` 17 | 18 | 19 | 20 | ## Solution 21 | 22 | 完全想不出的机智做法QuQ 23 | 24 | 25 | 26 | ## Code 27 | 28 | ```python 29 | class Solution(object): 30 | def partition(self, s): 31 | def dfs(s, path, res): 32 | if not s: 33 | res.append(path[:]) 34 | # print(res) 35 | return 36 | for i in range(1, len(s)+1): 37 | if s[:i] == s[i-1::-1]: 38 | path.append(s[:i]) 39 | dfs(s[i:], path, res) 40 | path.pop() 41 | res = [] 42 | dfs(s, [], res) 43 | return res 44 | ``` 45 | 46 | -------------------------------------------------------------------------------- /137. Single Number II.md: -------------------------------------------------------------------------------- 1 | # 137. Single Number II 2 | 3 | Given a **non-empty** array of integers, every element appears *three* times except for one, which appears exactly once. Find that single one. 4 | 5 | **Note:** 6 | 7 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: [2,2,3,2] 13 | Output: 3 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: [0,1,0,1,0,1,99] 20 | Output: 99 21 | ``` 22 | 23 | 24 | 25 | ## Code 26 | 27 | ```python 28 | class Solution(object): 29 | def singleNumber(self, nums): 30 | """ 31 | :type nums: List[int] 32 | :rtype: int 33 | """ 34 | dic = {} 35 | for num in nums: 36 | dic[num] = dic.get(num,0)+1 37 | for key,val in dic.items(): 38 | if val == 1: 39 | return key 40 | ``` 41 | 42 | 43 | 44 | ## Code-Java 45 | 46 | ```java 47 | class Solution { 48 | public int singleNumber(int[] nums) { 49 | Map map = new HashMap(); 50 | for(int num : nums) 51 | { 52 | if(map.get(num)==null) 53 | map.put(num,1); 54 | else 55 | map.replace(num,map.get(num)+1); 56 | } 57 | int result = -1; 58 | for(int k : map.keySet()) 59 | if(map.get(k)==1) 60 | { 61 | result = k; 62 | break; 63 | } 64 | return result; 65 | 66 | } 67 | } 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /14. Longest Common Prefix.md: -------------------------------------------------------------------------------- 1 | # 14. Longest Common Prefix 2 | 3 | Write a function to find the longest common prefix string amongst an array of strings. 4 | 5 | If there is no common prefix, return an empty string `""`. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: ["flower","flow","flight"] 11 | Output: "fl" 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: ["dog","racecar","car"] 18 | Output: "" 19 | Explanation: There is no common prefix among the input strings. 20 | ``` 21 | 22 | **Note:** 23 | 24 | All given inputs are in lowercase letters `a-z`. 25 | 26 | 27 | 28 | ## Solution: 29 | 30 | easy 31 | 32 | ## Code: 33 | 34 | ```python 35 | class Solution: 36 | def longestCommonPrefix(self, strs): 37 | """ 38 | :type strs: List[str] 39 | :rtype: str 40 | """ 41 | if len(strs) == 0: 42 | return '' 43 | if len(strs) == 1: 44 | return strs[0] 45 | 46 | min_len = min([len(x) for x in strs]) 47 | if min_len == 0: 48 | return '' 49 | 50 | result = [] 51 | for idx in range(min_len): 52 | c = '' 53 | for str in strs: 54 | if len(c) == 0: 55 | c = str[idx] 56 | elif str[idx] != c: 57 | return strs[0][:idx] 58 | return strs[0][:idx+1] 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /152. Maximum Product Subarray.md: -------------------------------------------------------------------------------- 1 | # 152. Maximum Product Subarray 2 | 3 | Given an integer array `nums`, find the contiguous subarray within an array (containing at least one number) which has the largest product. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: [2,3,-2,4] 9 | Output: 6 10 | Explanation: [2,3] has the largest product 6. 11 | ``` 12 | 13 | **Example 2:** 14 | 15 | ``` 16 | Input: [-2,0,-1] 17 | Output: 0 18 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 19 | ``` 20 | 21 | 22 | 23 | ## Solution 24 | 25 | 就,一开始没想出来。看了discussion发现其实也不太难。 26 | 27 | emmmm以后想十五分钟想不出来再看答案好了。 28 | 29 | 30 | 31 | 32 | 33 | ## Code 34 | 35 | ```java 36 | class Solution { 37 | public int maxProduct(int[] nums) { 38 | if(nums.length==0) 39 | return 0; 40 | 41 | int[] maxs = new int[nums.length]; 42 | int[] mins = new int[nums.length]; 43 | maxs[0] = nums[0]; 44 | mins[0] = nums[0]; 45 | int res = nums[0]; 46 | 47 | for(int i=1;inums[st]) 54 | st = mid+1; 55 | } 56 | return Math.min(nums[st],nums[ed]); 57 | } 58 | } 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /163. Missing Ranges.md: -------------------------------------------------------------------------------- 1 | # 163. Missing Ranges 2 | 3 | Given a sorted integer array where the range of elements are [0, 99] inclusive, return its missing ranges. 4 | For example, given [0, 1, 3, 50, 75], return [“2”, “4->49”, “51->74”, “76->99”] 5 | 6 | ### Example 7 | 8 | For example, given [0, 1, 3, 50, 75], return [“2”, “4->49”, “51->74”, “76->99”] 9 | 10 | 11 | 12 | ## Code 13 | 14 | ```python 15 | nums = [0, 1, 3, 50, 75] 16 | output = [] 17 | nums.insert(0,-1) 18 | nums.append(100) 19 | length = len(nums) 20 | for i in range(1,length): 21 | if nums[i]-nums[i-1]>2: 22 | output.append(str(nums[i-1]+1)+"->"+str(nums[i]-1)) 23 | elif nums[i]-nums[i-1]==2: 24 | output.append(str(nums[i-1]+1)) 25 | print(output) 26 | ``` 27 | 28 | -------------------------------------------------------------------------------- /167. Two Sum II - Input array is sorted.md: -------------------------------------------------------------------------------- 1 | # 167. Two Sum II - Input array is sorted 2 | 3 | Given an array of integers that is already **sorted in ascending order**, find two numbers such that they add up to a specific target number. 4 | 5 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. 6 | 7 | **Note:** 8 | 9 | - Your returned answers (both index1 and index2) are not zero-based. 10 | - You may assume that each input would have *exactly* one solution and you may not use the *same* element twice. 11 | 12 | **Example:** 13 | 14 | ``` 15 | Input: numbers = [2,7,11,15], target = 9 16 | Output: [1,2] 17 | Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 18 | ``` 19 | 20 | 21 | 22 | ## Solution 23 | 24 | 是没见过这么easy的题目。 25 | 26 | 27 | 28 | ## Code 29 | 30 | ```java 31 | class Solution { 32 | public int[] twoSum(int[] numbers, int target) { 33 | int st = 0; 34 | int ed = numbers.length-1; 35 | int[] res = new int[2]; 36 | while(sttarget) 39 | ed --; 40 | else if(numbers[st]+numbers[ed] A 9 | 2 -> B 10 | 3 -> C 11 | ... 12 | 26 -> Z 13 | 27 -> AA 14 | 28 -> AB 15 | ... 16 | ``` 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: 1 22 | Output: "A" 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: 28 29 | Output: "AB" 30 | ``` 31 | 32 | **Example 3:** 33 | 34 | ``` 35 | Input: 701 36 | Output: "ZY" 37 | ``` 38 | 39 | 40 | 41 | ## Solution 42 | 43 | 一直想不明白为什么要n-- 44 | 45 | 一个数字对26取余得到[0, 25],但是我们需要的是[1,26].并且如果是26的话就不需要进位,所以我们减一以后再运算. 46 | 47 | > I think the reason we do n-- is that number 0 is not included in this sheet. We can consider this transformation as base-26. However, classic base-26 consists of number from 0 to 25, and in this case we have numbers from 1 to 26. Now n-- seems intuitive and reasonable. 48 | 49 | 50 | 51 | ## Code 52 | 53 | ```java 54 | class Solution { 55 | public String convertToTitle(int n) { 56 | StringBuilder str = new StringBuilder(); 57 | while(n>0) 58 | { 59 | n--; 60 | int cur = n%26; 61 | str.insert(0,(char)('A'+cur)); 62 | n = n / 26; 63 | } 64 | return str.toString(); 65 | } 66 | } 67 | ``` 68 | 69 | -------------------------------------------------------------------------------- /171. Excel Sheet Column Number.md: -------------------------------------------------------------------------------- 1 | # 171. Excel Sheet Column Number 2 | 3 | Given a column title as appear in an Excel sheet, return its corresponding column number. 4 | 5 | For example: 6 | 7 | ``` 8 | A -> 1 9 | B -> 2 10 | C -> 3 11 | ... 12 | Z -> 26 13 | AA -> 27 14 | AB -> 28 15 | ... 16 | ``` 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: "A" 22 | Output: 1 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: "AB" 29 | Output: 28 30 | ``` 31 | 32 | **Example 3:** 33 | 34 | ``` 35 | Input: "ZY" 36 | Output: 701 37 | ``` 38 | 39 | 40 | 41 | ## Solution 42 | 43 | 没难度的easy题 44 | 45 | 46 | 47 | ## Code 48 | 49 | ```java 50 | class Solution { 51 | public int titleToNumber(String s) { 52 | int len = s.length(); 53 | Character cur; 54 | int res = 0; 55 | 56 | for(int i=0;i0) 36 | { 37 | n /= 5; 38 | res += n; 39 | } 40 | return res; 41 | } 42 | } 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /19. Remove Nth Node From End of List.md: -------------------------------------------------------------------------------- 1 | ## 19. Remove Nth Node From End of List 2 | 3 | Given a linked list, remove the *n*-th node from the end of list and return its head. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Given linked list: 1->2->3->4->5, and n = 2. 9 | 10 | After removing the second node from the end, the linked list becomes 1->2->3->5. 11 | ``` 12 | 13 | **Note:** 14 | 15 | Given *n* will always be valid. 16 | 17 | 18 | 19 | **Resolution:** 20 | 21 | 像是数据结构课上的作业orz 22 | 23 | 24 | 25 | **Code:** 26 | 27 | ```python 28 | class Solution: 29 | def removeNthFromEnd(self, head, n): 30 | """ 31 | :type head: ListNode 32 | :type n: int 33 | :rtype: ListNode 34 | """ 35 | dummy = ListNode(0); 36 | dummy.next = head 37 | 38 | last = dummy 39 | first = dummy 40 | if last.next is None: 41 | return head 42 | 43 | for k in range(n): 44 | last = last.next 45 | while last.next: 46 | last = last.next 47 | first = first.next 48 | # if first.next is not None: 49 | first.next = first.next.next 50 | # else: 51 | # first.next = None 52 | return dummy.next 53 | ``` 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /198. House Robber.md: -------------------------------------------------------------------------------- 1 | # 198. House Robber 2 | 3 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. 4 | 5 | Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight **without alerting the police**. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [1,2,3,1] 11 | Output: 4 12 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 13 | Total amount you can rob = 1 + 3 = 4. 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: [2,7,9,3,1] 20 | Output: 12 21 | Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 22 | Total amount you can rob = 2 + 9 + 1 = 12. 23 | ``` 24 | 25 | 26 | 27 | ## Solution 28 | 29 | DP 30 | 31 | 32 | 33 | ## Code 34 | 35 | ```java 36 | class Solution { 37 | public int rob(int[] nums) { 38 | int len = nums.length; 39 | int[] res = new int[len]; 40 | if(len==0) 41 | return 0; 42 | if(len==1) 43 | return nums[0]; 44 | 45 | res[0] = nums[0]; 46 | res[1] = Math.max(nums[1],res[0]); 47 | for(int i=2;i>= 1; 43 | n >>= 1; 44 | tmp <<= 1; 45 | } 46 | return m*tmp; 47 | } 48 | } 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /2018_Practice_ProblemA_GBus count/Solution_1.py: -------------------------------------------------------------------------------- 1 | # https://github.com/alexwaweru/kickstart_practice_2018/blob/master/kickstart_practice_round_2018/GBus_count/solution.py 2 | import numpy as np 3 | 4 | output = open("./out_large.txt", 'w+') 5 | with open('A-large-practice.in') as fp: 6 | T = int(fp.readline()) 7 | cur_rd = 1 8 | while cur_rd <= T: 9 | key = 'Case #'+str(int(cur_rd))+':' 10 | cur_rd += 1 11 | bus_num = int(fp.readline()) 12 | 13 | bus_stop_list = fp.readline() 14 | bus_stop = [int(n) for n in bus_stop_list.split()] 15 | 16 | test_num = int(fp.readline()) 17 | count = 0 18 | test_arr = np.zeros(test_num) 19 | while count < test_num: 20 | test_arr[count] = int(fp.readline()) 21 | count = count + 1 22 | 23 | max_num = np.max(bus_stop) 24 | bus_num_arr = np.zeros([max_num+1]) 25 | for t in range(0, len(bus_stop)): 26 | if t % 2 == 1: 27 | continue 28 | for i in range(bus_stop[t], bus_stop[t+1]+1): 29 | bus_num_arr[i] = bus_num_arr[i]+1 30 | 31 | count = 0 32 | total = '' 33 | while count < test_num: 34 | cur_city = int(test_arr[count]) 35 | if cur_city > max_num: 36 | value = 0 37 | else: 38 | value = bus_num_arr[cur_city] 39 | total = total + ' ' + str(int(value)) 40 | count += 1 41 | 42 | print(key + total) 43 | print('{0}'.format(key+total), file=output) 44 | blank = fp.readline() 45 | 46 | 47 | -------------------------------------------------------------------------------- /2018_Practice_ProblemA_GBus count/Solution_2.py: -------------------------------------------------------------------------------- 1 | # https://github.com/alexwaweru/kickstart_practice_2018/blob/master/kickstart_practice_round_2018/GBus_count/solution.py 2 | import numpy as np 3 | 4 | output = open("./out_small_2.txt", 'w+') 5 | with open('A-small-practice.in') as fp: 6 | T = int(fp.readline()) 7 | cur_rd = 1 8 | while cur_rd <= T: 9 | key = 'Case #'+str(int(cur_rd))+':' 10 | cur_rd += 1 11 | bus_num = int(fp.readline()) 12 | 13 | bus_stop_list = fp.readline() 14 | bus_stop = [int(n) for n in bus_stop_list.split()] 15 | 16 | stop_start = [bus_stop[k] for k in range(0, len(bus_stop), 2)] 17 | stop_end = [bus_stop[k] for k in range(1, len(bus_stop), 2)] 18 | test_num = int(fp.readline()) 19 | count = 0 20 | test_arr = np.zeros(test_num) 21 | while count < test_num: 22 | test_arr[count] = int(fp.readline()) 23 | count = count + 1 24 | 25 | count = 0 26 | total = '' 27 | while count < test_num: 28 | cur_city = int(test_arr[count]) 29 | value = 0 30 | for item in range(0, len(stop_start)): 31 | if stop_end[item] >= cur_city >= stop_start[item]: 32 | value += 1 33 | 34 | total = total + ' ' + str(int(value)) 35 | count += 1 36 | 37 | print(key + total) 38 | print('{0}'.format(key+total), file=output) 39 | blank = fp.readline() 40 | 41 | 42 | -------------------------------------------------------------------------------- /2018_Practice_ProblemA_GBus count/out_small.txt: -------------------------------------------------------------------------------- 1 | Case #1: 0 1 6 0 0 2 | Case #2: 8 0 8 10 5 0 10 7 6 2 4 0 3 8 6 0 12 12 8 3 5 12 12 1 12 3 | Case #3: 2 4 22 19 27 25 10 22 3 27 10 24 3 4 2 4 19 27 19 3 22 27 4 27 24 24 27 8 24 25 18 1 4 23 13 20 1 7 24 4 9 2 2 10 25 27 16 7 3 2 4 | Case #4: 2 1 2 4 3 7 2 6 5 | Case #5: 9 6 0 4 3 10 12 12 5 3 12 11 4 10 4 6 | Case #6: 5 8 4 2 2 5 2 0 -------------------------------------------------------------------------------- /2018_Practice_ProblemA_GBus count/out_small_2.txt: -------------------------------------------------------------------------------- 1 | Case #1: 0 1 6 0 0 2 | Case #2: 8 0 8 10 5 0 10 7 6 2 4 0 3 8 6 0 12 12 8 3 5 12 12 1 12 3 | Case #3: 2 4 22 19 27 25 10 22 3 27 10 24 3 4 2 4 19 27 19 3 22 27 4 27 24 24 27 8 24 25 18 1 4 23 13 20 1 7 24 4 9 2 2 10 25 27 16 7 3 2 4 | Case #4: 2 1 2 4 3 7 2 6 5 | Case #5: 9 6 0 4 3 10 12 12 5 3 12 11 4 10 4 6 | Case #6: 5 8 4 2 2 5 2 0 7 | -------------------------------------------------------------------------------- /2018_Practice_ProblemB_Googol String/B-small-practice.in: -------------------------------------------------------------------------------- 1 | 100 2 | 28314 3 | 86993 4 | 93172 5 | 56618 6 | 38867 7 | 78715 8 | 91775 9 | 32557 10 | 4096 11 | 55028 12 | 24217 13 | 94913 14 | 47929 15 | 75322 16 | 73895 17 | 93491 18 | 85358 19 | 64153 20 | 90464 21 | 41424 22 | 96796 23 | 13835 24 | 1 25 | 34064 26 | 53094 27 | 72221 28 | 800 29 | 64498 30 | 13111 31 | 66052 32 | 6751 33 | 4096 34 | 2983 35 | 72893 36 | 52463 37 | 67170 38 | 47144 39 | 574 40 | 58872 41 | 2586 42 | 18968 43 | 31159 44 | 98761 45 | 67127 46 | 43102 47 | 40283 48 | 93898 49 | 32181 50 | 2 51 | 23235 52 | 5275 53 | 1024 54 | 32768 55 | 98189 56 | 476 57 | 4 58 | 94617 59 | 44403 60 | 25302 61 | 84289 62 | 41619 63 | 97175 64 | 94154 65 | 95449 66 | 95678 67 | 28462 68 | 97005 69 | 90393 70 | 77794 71 | 10 72 | 41780 73 | 12696 74 | 49359 75 | 93854 76 | 920 77 | 93630 78 | 96919 79 | 75249 80 | 30992 81 | 90885 82 | 4096 83 | 29963 84 | 5000 85 | 10539 86 | 60683 87 | 27185 88 | 62660 89 | 55584 90 | 96052 91 | 98275 92 | 15829 93 | 83793 94 | 3 95 | 47591 96 | 91304 97 | 71941 98 | 98544 99 | 93847 100 | 99089 101 | 60280 102 | -------------------------------------------------------------------------------- /2018_Practice_ProblemB_Googol String/solution_1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import math 3 | output = open("./out_large.txt", 'w+') 4 | 5 | with open('./B-large-practice.in') as fp: 6 | T = int(fp.readline()) 7 | cur_rd = 1 8 | total = '' 9 | while cur_rd <= T: 10 | key = 'Case #'+str(int(cur_rd))+': ' 11 | k = int(fp.readline()) 12 | t = pow(10, 100) 13 | # St and k 14 | flag = 0 15 | while 1: 16 | # if middle 17 | if math.log(k, 2) == t-1 or k==0: 18 | break 19 | # if left part 20 | elif math.log(k, 2) < t-1: 21 | t = math.ceil(math.log(k+1, 2)) 22 | elif math.log(k, 2) > t-1: 23 | # if right part 24 | k = pow(2, t) - k 25 | if k == 0: 26 | break 27 | t -= 1 28 | if flag == 1: 29 | flag = 0 30 | else: 31 | flag = 1 32 | # print('t = ',str(t), '; k = ',str(k)) 33 | print(key + str(int(flag))) 34 | print('{0}'.format(key+str(int(flag))), file=output) 35 | cur_rd += 1 36 | blank = fp.readline() 37 | -------------------------------------------------------------------------------- /2018_Practice_ProblemC_SortItinerary/test.in: -------------------------------------------------------------------------------- 1 | 2 2 | 1 3 | SFO 4 | DFW 5 | 4 6 | MIA 7 | ORD 8 | DFW 9 | JFK 10 | SFO 11 | DFW 12 | JFK 13 | MIA -------------------------------------------------------------------------------- /2018_Practice_ProblemD_SumofSum/D-out-large.txt: -------------------------------------------------------------------------------- 1 | Case #1: 2 | 155553 3 | 154362 4 | 153649 5 | 145004 6 | 145175 7 | 163468 8 | 155793 9 | 155868 10 | 143167 11 | 158880 12 | 138703 13 | 149790 14 | 156570 15 | 146715 16 | 157476 17 | 147182 18 | 163592 19 | 139159 20 | 148156 21 | 144887 22 | Case #2: 23 | 121756 24 | 106682 25 | 100632 26 | 117520 27 | 118428 28 | 107478 29 | 116551 30 | 104794 31 | 106707 32 | 101785 33 | 112019 34 | 103443 35 | 114762 36 | 115574 37 | 116148 38 | 122502 39 | 100839 40 | 120154 41 | 116918 42 | 110141 43 | Case #3: 44 | 8640450208 45 | 8657894710 46 | 8629986592 47 | 8641802613 48 | 8653064071 49 | 8613166061 50 | 8639174239 51 | 8615422006 52 | 8618443235 53 | 8636459791 54 | 8644935193 55 | 8639170775 56 | 8645772649 57 | 8651134877 58 | 8630294381 59 | 8613179531 60 | 8644435786 61 | 8621966769 62 | 8619498072 63 | 8646903409 64 | -------------------------------------------------------------------------------- /2018_Practice_ProblemD_SumofSum/solution_1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | output = open("./D-out-large.txt", 'w+') 4 | with open('D-large-practice.in') as fp: 5 | T = int(fp.readline()) 6 | cur_rd = 1 7 | while cur_rd <= T: 8 | key = 'Case #'+str(int(cur_rd))+':' 9 | total = '' 10 | cur_rd += 1 11 | list = fp.readline().strip('\n').split(' ') 12 | N = int(list[0]) 13 | Q = int(list[1]) 14 | array_list = fp.readline().strip('\n') 15 | ini_array = [int(n) for n in array_list.split()] 16 | array = np.zeros(int(N*(N+1)/2)) 17 | count = 0 18 | for t in range(0, len(ini_array)): 19 | for tt in range(t, len(ini_array)): 20 | array[count] = sum(ini_array[t:tt+1]) 21 | count += 1 22 | array.sort() 23 | count = 0 24 | start_arr = np.zeros(Q) 25 | end_arr = np.zeros(Q) 26 | while count < Q: 27 | tmp = fp.readline().strip('\n') 28 | [st, ed] = [int(n) for n in tmp.split()] 29 | count = count + 1 30 | cur = sum(array[st-1:ed]) 31 | total = total + '\n' + str(int(cur)) 32 | 33 | print(key + total) 34 | print('{0}'.format(key+total), file=output) 35 | # blank = fp.readline() 36 | -------------------------------------------------------------------------------- /2018_RoundB_ProblemA_No_Nice/No_Nice.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import string 3 | 4 | output = open("./A-small-practice.out", 'w+') 5 | with open('A-small-practice.in') as fp: 6 | T = int(fp.readline()) 7 | cur_rd = 1 8 | while cur_rd <= T: 9 | key = 'Case #'+str(int(cur_rd))+': ' 10 | cur_rd += 1 11 | list = fp.readline().strip('\n') 12 | [s, e] = [int(n) for n in list.split()] 13 | count = 0 14 | for i in range(s, e+1): 15 | digit_sum = 0 16 | arr = str(i) 17 | if arr.find('9') != -1: 18 | continue 19 | for n in range(0, len(arr)): 20 | digit_sum += int(arr[n]) 21 | if digit_sum % 9 != 0: 22 | count += 1 23 | count_str = str(count) 24 | print(key + count_str) 25 | print('{0}'.format(key+count_str), file=output) 26 | -------------------------------------------------------------------------------- /2018_RoundH_ProblemA_BigButtons/solution.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import numpy as np 3 | output = open("./A-large-practice.out", 'w+') 4 | with open('A-large-practice.in') as fp: 5 | T = int(fp.readline()) 6 | cur_rd = 1 7 | while cur_rd <= T: 8 | key = 'Case #'+str(int(cur_rd))+': ' 9 | cur_rd += 1 10 | NP = fp.readline().strip('\n') 11 | [N, P] = [int(n) for n in NP.split()] 12 | 13 | count = 0 14 | suffix = [] 15 | while count < P: 16 | count = count + 1 17 | print('Count:\t', count) 18 | cur = fp.readline().strip('\n') 19 | flag = 1 20 | if len(suffix) == 0: 21 | suffix.append(cur) 22 | print('Add:\t', cur) 23 | else: 24 | for suf in suffix: 25 | if cur.startswith(suf): 26 | flag = 0 27 | break 28 | elif suf.startswith(cur): 29 | suffix.remove(suf) 30 | print('Rem:\t', suf) 31 | if flag is 1: 32 | suffix.append(cur) 33 | print('Add:\t', cur) 34 | 35 | 36 | # then calculate the number of possible combinations 37 | total = pow(2, N) 38 | for suf in suffix: 39 | cur_len = len(suf) 40 | total -= pow(2, N-cur_len) 41 | 42 | total_str = str(total) 43 | print(key + total_str) 44 | print('{0}'.format(key+total_str), file=output) 45 | -------------------------------------------------------------------------------- /2018_RoundH_ProblemB_Mural/solution.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import math 3 | 4 | # 想清楚之后就是找最大连续子列的问题 5 | # 洪水无法侵蚀已经画过的墙,所以找到子列以后一定可以全部画满 6 | 7 | # 时间复杂度O(N) 8 | output = open("./B-large-practice.out", 'w+') 9 | with open('./B-large-practice.in') as fp: 10 | T = int(fp.readline()) 11 | cur_rd = 1 12 | while cur_rd <= T: 13 | key = 'Case #'+str(int(cur_rd))+': ' 14 | cur_rd += 1 15 | N = int(fp.readline().strip('\n')) 16 | wall = fp.readline().strip('\n') 17 | paint_num = int((len(wall)+1)/2) 18 | cur = sum([int(n) for n in wall[0:paint_num]]) 19 | total = cur 20 | for t in range(0, len(wall)-paint_num): 21 | cur = cur - int(wall[t]) + int(wall[paint_num+t]) 22 | total = max(total, cur) 23 | total_str = str(total) 24 | print(key+total_str) 25 | print('{0}'.format(key+total_str), file=output) 26 | -------------------------------------------------------------------------------- /2018_RoundH_ProblemC_LetMeCountTheWays/C-small-practice.in: -------------------------------------------------------------------------------- 1 | 100 2 | 2 1 3 | 2 2 4 | 3 1 5 | 3 2 6 | 10 5 7 | 100 1 8 | 100 100 9 | 100 50 10 | 80 64 11 | 88 65 12 | 96 72 13 | 95 26 14 | 94 93 15 | 83 56 16 | 94 32 17 | 90 84 18 | 96 78 19 | 88 34 20 | 81 66 21 | 80 59 22 | 81 9 23 | 86 45 24 | 100 78 25 | 99 76 26 | 81 26 27 | 90 13 28 | 94 52 29 | 87 38 30 | 87 75 31 | 88 40 32 | 100 54 33 | 99 36 34 | 84 26 35 | 81 1 36 | 88 17 37 | 81 5 38 | 94 76 39 | 90 28 40 | 92 2 41 | 99 23 42 | 80 8 43 | 81 55 44 | 92 12 45 | 90 72 46 | 91 33 47 | 80 80 48 | 82 14 49 | 82 61 50 | 100 27 51 | 96 25 52 | 98 90 53 | 81 49 54 | 93 15 55 | 100 9 56 | 85 50 57 | 97 86 58 | 99 11 59 | 82 24 60 | 92 6 61 | 84 14 62 | 95 46 63 | 88 47 64 | 89 19 65 | 92 38 66 | 89 47 67 | 81 28 68 | 85 72 69 | 81 76 70 | 95 58 71 | 85 78 72 | 81 10 73 | 97 32 74 | 82 21 75 | 94 65 76 | 84 69 77 | 81 33 78 | 100 96 79 | 82 71 80 | 99 9 81 | 100 33 82 | 99 21 83 | 86 68 84 | 92 1 85 | 80 17 86 | 80 30 87 | 85 46 88 | 81 34 89 | 90 65 90 | 96 60 91 | 88 82 92 | 82 18 93 | 80 9 94 | 88 27 95 | 90 7 96 | 84 75 97 | 82 63 98 | 87 1 99 | 88 80 100 | 98 74 101 | 98 5 102 | -------------------------------------------------------------------------------- /2018_RoundH_ProblemC_LetMeCountTheWays/solution.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import math 3 | 4 | # 算半个小时也没算出来公式 5 | # 于是找了答案,哎 6 | # 放在高考前我一定能半小时算出这个排列组合的>< 7 | # 算公式的方法在large数据集上超时了emmm 8 | # todo: 之后看懂计算公式 + 不超时的方法 9 | 10 | 11 | def c(m, n): 12 | return int(math.factorial(m) / (math.factorial(n) * math.factorial(m - n))) 13 | 14 | 15 | output = open("./C-large-practice.out", 'w+') 16 | with open('./C-large-practice.in') as fp: 17 | T = int(fp.readline()) 18 | cur_rd = 1 19 | while cur_rd <= T: 20 | key = 'Case #'+str(int(cur_rd))+': ' 21 | cur_rd += 1 22 | NM = fp.readline().strip('\n') 23 | [N, M] = [int(n) for n in NM.split()] 24 | L = 2 * N 25 | flag = -1 26 | total = 0 27 | for i in range(M+1): 28 | flag = -flag 29 | a = c(M, i) 30 | b = int(math.factorial(L-i)) 31 | d = 2 ** i 32 | total += int(int(flag) * a * b * d) 33 | total -= (total // 1000000007) * 1000000007 34 | 35 | total = int(total % 1000000007) 36 | 37 | total_str = str(total) 38 | print(key+total_str) 39 | print('{0}'.format(key+total_str), file=output) 40 | -------------------------------------------------------------------------------- /202. Happy Number.md: -------------------------------------------------------------------------------- 1 | # 202. Happy Number 2 | 3 | Write an algorithm to determine if a number is "happy". 4 | 5 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: 19 11 | Output: true 12 | Explanation: 13 | 12 + 92 = 82 14 | 82 + 22 = 68 15 | 62 + 82 = 100 16 | 12 + 02 + 02 = 1 17 | ``` 18 | 19 | 20 | 21 | 22 | 23 | ## Solution 24 | 25 | 用个hashset来记录有没有重复就行了。 26 | 27 | 28 | 29 | ## Code 30 | 31 | ```java 32 | class Solution { 33 | public boolean isHappy(int n) { 34 | HashSet set = new HashSet(); 35 | int m = 0; 36 | int rem=0; 37 | while(n!=1) 38 | { 39 | if(set.contains(n)) 40 | return false; 41 | set.add(n); 42 | m = 0; 43 | while(n>0) 44 | { 45 | rem = n % 10; 46 | n /= 10; 47 | m += rem*rem; 48 | } 49 | n = m; 50 | } 51 | return n==1; 52 | } 53 | } 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /203. Remove Linked List Elements.md: -------------------------------------------------------------------------------- 1 | # 203. Remove Linked List Elements 2 | 3 | 4 | 5 | Remove all elements from a linked list of integers that have value **val**. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: 1->2->6->3->4->5->6, val = 6 11 | Output: 1->2->3->4->5 12 | ``` 13 | 14 | 15 | 16 | ## Code 17 | 18 | ```java 19 | /** 20 | * Definition for singly-linked list. 21 | * public class ListNode { 22 | * int val; 23 | * ListNode next; 24 | * ListNode(int x) { val = x; } 25 | * } 26 | */ 27 | class Solution { 28 | public ListNode removeElements(ListNode head, int val) { 29 | ListNode dummy = new ListNode(0); 30 | dummy.next = head; 31 | 32 | ListNode first = dummy; 33 | ListNode second = dummy.next; 34 | while(second!=null) 35 | { 36 | if(second.val==val) 37 | first.next = second.next; 38 | else 39 | first = second; 40 | second = second.next; 41 | } 42 | 43 | return dummy.next; 44 | } 45 | } 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /204. Count Primes.md: -------------------------------------------------------------------------------- 1 | # 204. Count Primes 2 | 3 | Count the number of prime numbers less than a non-negative number, **n**. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: 10 9 | Output: 4 10 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 11 | ``` 12 | 13 | 14 | 15 | ## Solution 16 | 17 | 最基础的了吧orz 18 | 19 | bugfree啊要 20 | 21 | code2是discussion里面的有趣的方法啊,速度很快,空间O(n). 22 | 23 | 24 | 25 | ## Code 26 | 27 | ```java 28 | class Solution { 29 | public int countPrimes(int n) { 30 | if(n<=2) 31 | return 0; 32 | if(n==3) 33 | return 1; 34 | int count = 1; 35 | boolean flag; 36 | for(int i=3;i=s) 44 | min_len = Math.min(min_len,ed-st); 45 | 46 | if(st2->4, 1->3->4 9 | Output: 1->1->2->3->4->4 10 | ``` 11 | 12 | 13 | 14 | ## Code: 15 | 16 | ```python 17 | # Definition for singly-linked list. 18 | # class ListNode: 19 | # def __init__(self, x): 20 | # self.val = x 21 | # self.next = None 22 | 23 | class Solution: 24 | def mergeTwoLists(self, l1, l2): 25 | """ 26 | :type l1: ListNode 27 | :type l2: ListNode 28 | :rtype: ListNode 29 | """ 30 | dummy = ListNode(0) 31 | cur = dummy 32 | p1 = l1 33 | p2 = l2 34 | while p1 and p2: 35 | if p1.val > p2.val: 36 | cur.next = p2 37 | cur = cur.next 38 | p2 = p2.next 39 | else: 40 | cur.next = p1 41 | cur = cur.next 42 | p1 = p1.next 43 | while p1: 44 | cur.next = p1 45 | cur = cur.next 46 | p1 = p1.next 47 | while p2: 48 | cur.next = p2 49 | cur = cur.next 50 | p2 = p2.next 51 | return dummy.next 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /216. Combination Sum III.md: -------------------------------------------------------------------------------- 1 | # 216. Combination Sum III 2 | 3 | Find all possible combinations of ***k*** numbers that add up to a number ***n***, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 4 | 5 | **Note:** 6 | 7 | - All numbers will be positive integers. 8 | - The solution set must not contain duplicate combinations. 9 | 10 | **Example 1:** 11 | 12 | ``` 13 | Input: k = 3, n = 7 14 | Output: [[1,2,4]] 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: k = 3, n = 9 21 | Output: [[1,2,6], [1,3,5], [2,3,4]] 22 | ``` 23 | 24 | 25 | 26 | ## Solution 27 | 28 | 自己写的递归过了耶 29 | 30 | 31 | 32 | ## Code 33 | 34 | ```java 35 | class Solution { 36 | private void helper(List> res, List path, int k, int n, int st) 37 | { 38 | if(n==0 && k==0) 39 | { 40 | res.add(new ArrayList(path)); 41 | return; 42 | } 43 | else if(n==0 && k!=0 || k==0 && n!=0) 44 | return; 45 | else 46 | { 47 | for(int i=st;i<=Math.min(n,9);i++) 48 | { 49 | path.add(i); 50 | helper(res, path, k-1, n-i,i+1); 51 | path.remove(path.size()-1); 52 | } 53 | 54 | } 55 | 56 | 57 | } 58 | public List> combinationSum3(int k, int n) { 59 | List> res = new ArrayList<>(); 60 | 61 | helper(res, new ArrayList(), k, n, 1); 62 | return res; 63 | } 64 | } 65 | ``` 66 | 67 | -------------------------------------------------------------------------------- /217. Contains Duplicate.md: -------------------------------------------------------------------------------- 1 | # 217. Contains Duplicate 2 | 3 | Given an array of integers, find if the array contains any duplicates. 4 | 5 | Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [1,2,3,1] 11 | Output: true 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: [1,2,3,4] 18 | Output: false 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: [1,1,1,3,3,4,3,2,4,2] 25 | Output: true 26 | ``` 27 | 28 | 29 | 30 | ## Code 31 | 32 | ```java 33 | class Solution { 34 | public boolean containsDuplicate(int[] nums) { 35 | HashSet set = new HashSet<>(); 36 | for(int num : nums) 37 | { 38 | if(set.contains(num)) 39 | return true; 40 | set.add(num); 41 | } 42 | return false; 43 | 44 | } 45 | } 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /219. Contains Duplicate II.md: -------------------------------------------------------------------------------- 1 | # 219. Contains Duplicate II 2 | 3 | Given an array of integers and an integer *k*, find out whether there are two distinct indices *i* and *j* in the array such that **nums[i] = nums[j]** and the **absolute** difference between *i* and *j* is at most *k*. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: nums = [1,2,3,1], k = 3 9 | Output: true 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: nums = [1,0,1,1], k = 1 16 | Output: true 17 | ``` 18 | 19 | **Example 3:** 20 | 21 | ``` 22 | Input: nums = [1,2,3,1,2,3], k = 2 23 | Output: false 24 | ``` 25 | 26 | 27 | 28 | ## Solution 29 | 30 | 简单到不需要solution。只需要记录最后一次的index。hashmap就完了。 31 | 32 | 33 | 34 | ## Code 35 | 36 | ```java 37 | class Solution { 38 | public boolean containsNearbyDuplicate(int[] nums, int k) { 39 | HashMap map = new HashMap<>(); 40 | for(int i=0;i2","4->5","7"] 10 | Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range. 11 | ``` 12 | 13 | **Example 2:** 14 | 15 | ``` 16 | Input: [0,2,3,4,6,8,9] 17 | Output: ["0","2->4","6","8->9"] 18 | Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range. 19 | ``` 20 | 21 | 22 | 23 | ## Code 24 | 25 | ```java 26 | class Solution { 27 | public List summaryRanges(int[] nums) { 28 | List res = new ArrayList(); 29 | 30 | int len = nums.length; 31 | int begin = 0; 32 | int st = 0; 33 | // int ed = len-1; 34 | 35 | while(begin < len) 36 | { 37 | st = begin; 38 | while(st"+nums[st]); 45 | 46 | begin = st + 1; 47 | } 48 | 49 | return res; 50 | } 51 | } 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /230. Kth Smallest Element in a BST.md: -------------------------------------------------------------------------------- 1 | # 230. Kth Smallest Element in a BST 2 | 3 | Given a binary search tree, write a function `kthSmallest` to find the **k**th smallest element in it. 4 | 5 | **Note:** 6 | You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 7 | 8 | **Example 1:** 9 | 10 | ``` 11 | Input: root = [3,1,4,null,2], k = 1 12 | 3 13 | / \ 14 | 1 4 15 | \ 16 | 2 17 | Output: 1 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: root = [5,3,6,2,4,null,null,1], k = 3 24 | 5 25 | / \ 26 | 3 6 27 | / \ 28 | 2 4 29 | / 30 | 1 31 | Output: 3 32 | ``` 33 | 34 | **Follow up:** 35 | What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? 36 | 37 | 38 | 39 | ## Code 40 | 41 | ```python 42 | # Definition for a binary tree node. 43 | # class TreeNode(object): 44 | # def __init__(self, x): 45 | # self.val = x 46 | # self.left = None 47 | # self.right = None 48 | 49 | class Solution(object): 50 | def kthSmallest(self, root, k): 51 | """ 52 | :type root: TreeNode 53 | :type k: int 54 | :rtype: int 55 | """ 56 | stack = [] 57 | node = root 58 | while stack or node: 59 | while node: 60 | stack.append(node) 61 | node = node.left 62 | node = stack.pop() 63 | k -= 1 64 | if k == 0: 65 | break 66 | node = node.right 67 | return node.val 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /231. Power of Two.md: -------------------------------------------------------------------------------- 1 | # 231. Power of Two 2 | 3 | Given an integer, write a function to determine if it is a power of two. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 1 9 | Output: true 10 | Explanation: 20 = 1 11 | ``` 12 | 13 | **Example 2:** 14 | 15 | ``` 16 | Input: 16 17 | Output: true 18 | Explanation: 24 = 16 19 | ``` 20 | 21 | **Example 3:** 22 | 23 | ``` 24 | Input: 218 25 | Output: false 26 | ``` 27 | 28 | 29 | 30 | ## Solution 31 | 32 | 普通做法(对2取余,右移,直到为**1**) 33 | 34 | 取巧做法: 35 | 36 | (n & (n-1)) = 1000000 & 0111111 = 0 37 | 38 | 39 | 40 | 41 | 42 | ## Code 43 | 44 | ```java 45 | class Solution { 46 | public boolean isPowerOfTwo(int n) { 47 | if(n<=0) 48 | return false; 49 | return (n&(n-1))==0; 50 | } 51 | 52 | public boolean isPowerOfTwo_self(int n) { 53 | if(n<=0) 54 | return false; 55 | while(n>1) 56 | { 57 | if(n%2!=0) 58 | return false; 59 | n >>= 1; 60 | } 61 | return true; 62 | } 63 | } 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /237. Delete Node in a Linked List.md: -------------------------------------------------------------------------------- 1 | # 237. Delete Node in a Linked List 2 | 3 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 4 | 5 | Given linked list -- head = [4,5,1,9], which looks like following: 6 | 7 | ![img](https://assets.leetcode.com/uploads/2018/12/28/237_example.png) 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: head = [4,5,1,9], node = 5 15 | Output: [4,1,9] 16 | Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: head = [4,5,1,9], node = 1 23 | Output: [4,5,9] 24 | Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. 25 | ``` 26 | 27 | 28 | 29 | **Note:** 30 | 31 | - The linked list will have at least two elements. 32 | - All of the nodes' values will be unique. 33 | - The given node will not be the tail and it will always be a valid node of the linked list. 34 | - Do not return anything from your function. 35 | 36 | 37 | 38 | ## Solution 39 | 40 | 这什么傻子题目。 41 | 42 | 43 | 44 | ## Code 45 | 46 | ```java 47 | class Solution { 48 | public void deleteNode(ListNode node) { 49 | node.val = node.next.val; 50 | node.next = node.next.next; 51 | } 52 | } 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /24. Swap Nodes in Pairs.md: -------------------------------------------------------------------------------- 1 | ## 24. Swap Nodes in Pairs 2 | 3 | Given a linked list, swap every two adjacent nodes and return its head. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Given 1->2->3->4, you should return the list as 2->1->4->3. 9 | ``` 10 | 11 | **Note:** 12 | 13 | - Your algorithm should use only constant extra space. 14 | - You may **not** modify the values in the list's nodes, only nodes itself may be changed. 15 | 16 | **Resolution:** 17 | 18 | 又仿佛数据结构的作业... 19 | 20 | 21 | 22 | **Code:** 23 | 24 | ```python 25 | # Definition for singly-linked list. 26 | # class ListNode: 27 | # def __init__(self, x): 28 | # self.val = x 29 | # self.next = None 30 | 31 | class Solution: 32 | def swapPairs(self, head): 33 | """ 34 | :type head: ListNode 35 | :rtype: ListNode 36 | """ 37 | dummy = ListNode(0) 38 | dummy.next = head 39 | # if zero or one node only 40 | if dummy.next is None or dummy.next.next is None: 41 | return dummy.next 42 | zeroth = dummy 43 | while zeroth.next and zeroth.next.next: 44 | first = zeroth.next 45 | second = first.next 46 | first.next = second.next 47 | zeroth.next = second 48 | second.next = first 49 | zeroth = zeroth.next.next 50 | return dummy.next 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /246. Strobogrammatic Number.md: -------------------------------------------------------------------------------- 1 | # 246. Strobogrammatic Number 2 | 3 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 4 | 5 | Write a function to determine if a number is strobogrammatic. The number is represented as a string. 6 | 7 | Example 1: 8 | 9 | ``` 10 | Input: "69" 11 | Output: true 12 | ``` 13 | 14 | Example 2: 15 | 16 | ``` 17 | Input: "88" 18 | Output: true 19 | ``` 20 | 21 | Example 3: 22 | 23 | ``` 24 | Input: "962" 25 | Output: false 26 | ``` 27 | 28 | 29 | 30 | ## Code 31 | 32 | ```python 33 | record = {'0':'0', '1':'1', '8':'8','6':'9','9':'6'} 34 | def isStrobogrammatic(num): 35 | length = len(num) 36 | st = 0 37 | ed = length-1 38 | while st < ed: 39 | if num[st] not in record or num[ed] not in record: 40 | return False 41 | return record[num[st]] == num[ed] 42 | 43 | print(isStrobogrammatic("111") 44 | ``` 45 | 46 | -------------------------------------------------------------------------------- /247. Strobogrammatic Number II.md: -------------------------------------------------------------------------------- 1 | # 247. Strobogrammatic Number II 2 | 3 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 4 | 5 | Find all strobogrammatic numbers that are of length = n. 6 | 7 | For example, 8 | Given n = 2, return `["11","69","88","96"]`. 9 | 10 | Hint: 11 | 12 | 1. Try to use recursion and notice that it should recurse with *n* - 2 instead of *n* - 1. 13 | 14 | 15 | 16 | ## Code 17 | 18 | ```python 19 | def generateStrobogrammatic(digit): 20 | if digit < 0: 21 | return [] 22 | elif digit == 1: 23 | return ["1", "8", "0"] 24 | elif digit == 2: 25 | return ["11", "88", "00", "69", "96"] 26 | else: 27 | res = [] 28 | for item in generateStrobogrammatic(digit-2): 29 | res.append("1" + item + "1") 30 | res.append("0" + item + "0") 31 | res.append("8" + item + "8") 32 | res.append("9" + item + "6") 33 | res.append("6" + item + "9") 34 | return res 35 | 36 | 37 | print([string for string in generateStrobogrammatic(2) if string[0]!="0"]) 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /248. Strobogrammatic Number III.md: -------------------------------------------------------------------------------- 1 | # [248. Strobogrammatic Number III 对称数之三](https://www.cnblogs.com/grandyang/p/5203228.html) 2 | 3 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 4 | 5 | Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high. 6 | 7 | Example: 8 | 9 | ``` 10 | Input: low = "50", high = "100" 11 | Output: 3 12 | Explanation: 69, 88, and 96 are three strobogrammatic numbers. 13 | ``` 14 | 15 | Note: 16 | Because the range might be a large number, the *low*and *high* numbers are represented as string. 17 | 18 | 19 | 20 | ## Code 21 | 22 | ```python 23 | def find_count(low, high, path): 24 | if len(high) >= len(path) >= len(low): 25 | if len(path)>1 and path[0]=='0': 26 | return 0 27 | if len(path) == len(low) and pathhigh: 28 | return 0 29 | print(path) 30 | return 1 31 | 32 | if len(path)+2<=len(high): 33 | res = 0 34 | res += find_count(low, high, "1" + path + "1") 35 | res += find_count(low, high, "0" + path + "0") 36 | res += find_count(low, high, "8" + path + "8") 37 | res += find_count(low, high, "6" + path + "9") 38 | res += find_count(low, high, "9" + path + "6") 39 | return res 40 | 41 | low = "50" 42 | high = "100" 43 | res = 0 44 | res += find_count(low, high, "") 45 | res += find_count(low, high, "0") 46 | res += find_count(low, high, "1") 47 | res += find_count(low, high, "8") 48 | 49 | print(res) 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /252. Meeting Rooms.md: -------------------------------------------------------------------------------- 1 | # 252. Meeting Rooms 2 | 3 | # Question 4 | 5 | Given an array of meeting time intervals consisting of start and end times `[[s1,e1],[s2,e2],...] (si < ei)`, determine if a person could attend all meetings. 6 | 7 | Example 1: 8 | 9 | ``` 10 | Input: [[0,30],[5,10],[15,20]] 11 | Output: false 12 | ``` 13 | 14 | Example 2: 15 | 16 | ``` 17 | Input: [[7,10],[2,4]] 18 | Output: true 19 | ``` 20 | 21 | 22 | 23 | ## Code 24 | 25 | ```python 26 | class Solution(object): 27 | def findMinArrowShots(self, points): 28 | """ 29 | :type points: List[List[int]] 30 | :rtype: int 31 | """ 32 | if len(points)==0: 33 | return 0 34 | 35 | points.sort(key = lambda x: x[1]) 36 | print(points) 37 | end = float('-inf') 38 | for point in points: 39 | if point[0]2->5", "1->3"] 19 | 20 | Explanation: All root-to-leaf paths are: 1->2->5, 1->3 21 | ``` 22 | 23 | 24 | 25 | ## Code 26 | 27 | ```java 28 | class Solution { 29 | private List res = new ArrayList(); 30 | private void helper(TreeNode root,String path) 31 | { 32 | if(root==null) 33 | return; 34 | path += "->" + Integer.toString(root.val); 35 | if(root.left==null && root.right==null) 36 | res.add(new String(path)); 37 | helper(root.left, path); 38 | helper(root.right, path); 39 | } 40 | public List binaryTreePaths(TreeNode root) { 41 | if(root==null) 42 | return new ArrayList(){}; 43 | String path = Integer.toString(root.val); 44 | if(root.left==null && root.right==null) 45 | { 46 | res.add(path); 47 | return res; 48 | } 49 | 50 | helper(root.left, path); 51 | helper(root.right, path); 52 | return res; 53 | } 54 | } 55 | ``` 56 | 57 | -------------------------------------------------------------------------------- /258. Add Digits.md: -------------------------------------------------------------------------------- 1 | # 258. Add Digits 2 | 3 | Given a non-negative integer `num`, repeatedly add all its digits until the result has only one digit. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: 38 9 | Output: 2 10 | Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 11 | Since 2 has only one digit, return it. 12 | ``` 13 | 14 | **Follow up:** 15 | Could you do it without any loop/recursion in O(1) runtime? 16 | 17 | 18 | 19 | ## Solution 20 | 21 | 可以看作一个数学问题,直接返回``(num-1)%9+1``也行,惊了这是什么套路..... 22 | 23 | 24 | 25 | 26 | 27 | ## Code 28 | 29 | ```java 30 | class Solution { 31 | public int addDigits(int num) { 32 | if(num<10) 33 | return num; 34 | 35 | int res = 0; 36 | while(num>=10) 37 | { 38 | res = 0; 39 | while(num>0) 40 | { 41 | res += num%10; 42 | num /= 10; 43 | } 44 | num = res; 45 | } 46 | return num; 47 | } 48 | } 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /263. Ugly Number.md: -------------------------------------------------------------------------------- 1 | # 263. Ugly Number 2 | 3 | Write a program to check whether a given number is an ugly number. 4 | 5 | Ugly numbers are **positive numbers** whose prime factors only include `2, 3, 5`. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 6 11 | Output: true 12 | Explanation: 6 = 2 × 3 13 | ``` 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: 8 19 | Output: true 20 | Explanation: 8 = 2 × 2 × 2 21 | ``` 22 | 23 | **Example 3:** 24 | 25 | ``` 26 | Input: 14 27 | Output: false 28 | Explanation: 14 is not ugly since it includes another prime factor 7. 29 | ``` 30 | 31 | 32 | 33 | ## Solution 34 | 35 | easy 36 | 37 | 38 | 39 | ## Code 40 | 41 | ```java 42 | class Solution { 43 | public boolean isUgly(int num) { 44 | int[] list = new int[]{2,3,5}; 45 | if(num==1||num==0) 46 | return num==1; 47 | 48 | for(int i=0;i<3;i++) 49 | { 50 | int factor = list[i]; 51 | int val = factor; 52 | while(num % factor == 0) 53 | { 54 | if(num%val==0) 55 | { 56 | num /= val; 57 | val *= val; 58 | } 59 | else 60 | { 61 | num /= factor; 62 | val = factor; 63 | } 64 | } 65 | if(num==1) 66 | return true; 67 | } 68 | 69 | 70 | return false; 71 | 72 | 73 | } 74 | } 75 | ``` 76 | 77 | -------------------------------------------------------------------------------- /264. Ugly Number II.md: -------------------------------------------------------------------------------- 1 | # 264. Ugly Number II 2 | 3 | Write a program to find the `n`-th ugly number. 4 | 5 | Ugly numbers are **positive numbers** whose prime factors only include `2, 3, 5`. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: n = 10 11 | Output: 12 12 | Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 13 | ``` 14 | 15 | **Note:** 16 | 17 | 1. `1` is typically treated as an ugly number. 18 | 2. `n` **does not exceed 1690**. 19 | 20 | 21 | 22 | ## Solution 23 | 24 | 我是一个只想得到思路的前40%的废人,对不起。 25 | 26 | 请重新写。 27 | 28 | 29 | 30 | ## Code 31 | 32 | ```java 33 | class Solution { 34 | public int nthUglyNumber(int n) { 35 | if(n==1) 36 | return 1; 37 | int[] ugly = new int[n]; 38 | 39 | int idx2 = 0; 40 | int idx3 = 0; 41 | int idx5 = 0; 42 | 43 | int factor2 = 2; 44 | int factor3 = 3; 45 | int factor5 = 5; 46 | for(int i=1;i0) 40 | return i; 41 | } 42 | return nums.length; 43 | } 44 | } 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /270. Closest Binary Search Tree Value.md: -------------------------------------------------------------------------------- 1 | # [Closest Binary Search Tree Value 最近的二分搜索树的值](https://www.cnblogs.com/grandyang/p/5237170.html) 2 | 3 | Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 4 | 5 | Note: 6 | 7 | - Given target value is a floating point. 8 | - You are guaranteed to have only one unique value in the BST that is closest to the target. 9 | 10 | 11 | 12 | ## Code 13 | 14 | ```python 15 | # Definition for a binary tree node. 16 | # class TreeNode(object): 17 | # def __init__(self, x): 18 | # self.val = x 19 | # self.left = None 20 | # self.right = None 21 | 22 | class Solution(object): 23 | def inorderTraversal(self, root): 24 | """ 25 | :type root: TreeNode 26 | :rtype: List[int] 27 | """ 28 | minval = 0 29 | mindiff = float('inf') 30 | node = root 31 | target = 5 32 | while node: 33 | diff = node.val - target 34 | if mindiff > abs(diff): 35 | mindiff = abs(diff) 36 | minval = node.val 37 | if diff > 0: 38 | node = node.left 39 | elif diff < 0: 40 | node = node.right 41 | else: 42 | break 43 | return minval 44 | ``` 45 | 46 | -------------------------------------------------------------------------------- /274. H-Index.md: -------------------------------------------------------------------------------- 1 | # 274. H-Index 2 | 3 | Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. 4 | 5 | According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): "A scientist has index *h* if *h* of his/her *N* papers have **at least** *h* citations each, and the other *N − h* papers have **no more than** *h* citations each." 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: citations = [3,0,6,1,5] 11 | Output: 3 12 | Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had 13 | received 3, 0, 6, 1, 5 citations respectively. 14 | Since the researcher has 3 papers with at least 3 citations each and the remaining 15 | two with no more than 3 citations each, her h-index is 3. 16 | ``` 17 | 18 | **Note:** If there are several possible values for *h*, the maximum one is taken as the h-index. 19 | 20 | 21 | 22 | ## Solution 23 | 24 | 犯懒没想直接看了discussion,挺正经的方法。 25 | 26 | 27 | 28 | ## Code 29 | 30 | ```java 31 | class Solution { 32 | public int hIndex(int[] citations) { 33 | Arrays.sort(citations); 34 | for(int i = citations.length - 1; i >= 0; i--) { 35 | if(citations[i] < citations.length - i) { 36 | return citations.length - i - 1; 37 | } 38 | } 39 | return citations.length; 40 | } 41 | } 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /283. Move Zeroes.md: -------------------------------------------------------------------------------- 1 | # 283. Move Zeroes 2 | 3 | Given an array `nums`, write a function to move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: [0,1,0,3,12] 9 | Output: [1,3,12,0,0] 10 | ``` 11 | 12 | **Note**: 13 | 14 | 1. You must do this **in-place** without making a copy of the array. 15 | 2. Minimize the total number of operations. 16 | 17 | 18 | 19 | ## Code 20 | 21 | ```java 22 | class Solution { 23 | private void swap(int[] nums, int i, int j) 24 | { 25 | int tmp = nums[i]; 26 | nums[i] = nums[j]; 27 | nums[j] = tmp; 28 | } 29 | public void moveZeroes(int[] nums) { 30 | int len = nums.length; 31 | int head = 0; 32 | for(int i=0;i 1 11 | sumRange(2, 5) -> -1 12 | sumRange(0, 5) -> -3 13 | ``` 14 | 15 | 16 | 17 | **Note:** 18 | 19 | 1. You may assume that the array does not change. 20 | 2. There are **many calls** to *sumRange* function. 21 | 22 | 23 | 24 | ## Solution 25 | 26 | 构造一个当前坐标左边所有值的array就行。 27 | 28 | 29 | 30 | ## Code 31 | 32 | ```java 33 | class NumArray { 34 | 35 | // int[] list; 36 | int[] sum; 37 | public NumArray(int[] nums) { 38 | int len = nums.length; 39 | sum = new int[len+1]; 40 | for(int i=0;i1) 60 | { 61 | 62 | if(n < cur) 63 | cur = 3; 64 | 65 | if(n % cur != 0) 66 | return false; 67 | 68 | n = n / cur; 69 | cur = cur * cur; 70 | 71 | } 72 | return true; 73 | } 74 | } 75 | ``` 76 | 77 | 78 | 79 | ## Code-不循环 80 | 81 | ```java 82 | class Solution { 83 | public boolean isPowerOfThree(int n) { 84 | if(n<=0) 85 | return false; 86 | return Math.pow(3,19)%n == 0; 87 | } 88 | } 89 | ``` 90 | 91 | -------------------------------------------------------------------------------- /334. Increasing Triplet Subsequence.md: -------------------------------------------------------------------------------- 1 | # 334. Increasing Triplet Subsequence 2 | 3 | Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 4 | 5 | Formally the function should: 6 | 7 | > Return true if there exists *i, j, k* 8 | > such that *arr[i]* < *arr[j]* < *arr[k]* given 0 ≤ *i* < *j* < *k* ≤ *n*-1 else return false. 9 | 10 | **Note:** Your algorithm should run in O(*n*) time complexity and O(*1*) space complexity. 11 | 12 | **Example 1:** 13 | 14 | ``` 15 | Input: [1,2,3,4,5] 16 | Output: true 17 | ``` 18 | 19 | **Example 2:** 20 | 21 | ``` 22 | Input: [5,4,3,2,1] 23 | Output: false 24 | ``` 25 | 26 | 27 | 28 | ## Solution 29 | 30 | 很机智的算法。注意思考。 31 | 32 | 33 | 34 | ## Code 35 | 36 | ```java 37 | class Solution { 38 | public boolean increasingTriplet(int[] nums) { 39 | 40 | long first = Long.MAX_VALUE; 41 | long second = Long.MAX_VALUE; 42 | for(int num : nums) 43 | { 44 | if(num<=first) 45 | first = num; 46 | else if(numsecond) 49 | return true; 50 | } 51 | return false; 52 | } 53 | } 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /338. Counting Bits.md: -------------------------------------------------------------------------------- 1 | # 338. Counting Bits 2 | 3 | Given a non negative integer number **num**. For every numbers **i** in the range **0 ≤ i ≤ num**calculate the number of 1's in their binary representation and return them as an array. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 2 9 | Output: [0,1,1] 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: 5 16 | Output: [0,1,1,2,1,2] 17 | ``` 18 | 19 | **Follow up:** 20 | 21 | - It is very easy to come up with a solution with run time **O(n\*sizeof(integer))**. But can you do it in linear time **O(n)** /possibly in a single pass? 22 | - Space complexity should be **O(n)**. 23 | - Can you do it like a boss? Do it without using any builtin function like **__builtin_popcount** in c++ or in any other language. 24 | 25 | 26 | 27 | ## Solution 28 | 29 | 找规律的小学奥数题啊!! 30 | 31 | 32 | 33 | ## Code 34 | 35 | ```java 36 | class Solution { 37 | public int[] countBits(int num) { 38 | int[] res = new int[num+1]; 39 | int len = 1; 40 | int st = 1; 41 | int i = 0; 42 | while(len<=num) 43 | { 44 | for(i=0;inum) 47 | break; 48 | res[len+i] = 1 + res[i]; 49 | } 50 | len*=2; 51 | } 52 | return res; 53 | } 54 | } 55 | ``` 56 | 57 | -------------------------------------------------------------------------------- /340. Longest Substring with At Most K Distinct Characters.md: -------------------------------------------------------------------------------- 1 | # [340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串](https://www.cnblogs.com/grandyang/p/5351347.html) 2 | 3 | Given a string, find the length of the longest substring T that contains at most *k* distinct characters. 4 | 5 | For example, Given s = `“eceba”` and k = 2, 6 | 7 | T is "ece" which its length is 3. 8 | 9 | 10 | 11 | ## Code 12 | 13 | ```python 14 | def longestsubstring(s, k): 15 | map = {} 16 | count = k 17 | longest = 0 18 | st = 0 19 | ed = 0 20 | length = len(s) 21 | while ed < length: 22 | ch = s[ed] 23 | ed += 1 24 | map[ch] = map.get(ch, 0) + 1 25 | if map[ch] == 1: 26 | count -= 1 27 | 28 | while count < 0: 29 | ch = s[st] 30 | map[ch] = map.get(ch, 0) - 1 31 | if map[ch]==0: 32 | count += 1 33 | st += 1 34 | 35 | if count >= 0: 36 | longest = max(longest, ed - st) 37 | return longest 38 | 39 | s = "eceba" 40 | k = 2 41 | print(longestsubstring(s, k)) 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /342. Power of Four.md: -------------------------------------------------------------------------------- 1 | # 342. Power of Four 2 | 3 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 16 9 | Output: true 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: 5 16 | Output: false 17 | ``` 18 | 19 | 20 | 21 | ## Code 22 | 23 | ```java 24 | class Solution { 25 | public boolean isPowerOfFour(int num) { 26 | if(num<=0) 27 | return false; 28 | int factor = 4; 29 | while(num>1) 30 | { 31 | factor *= 4; 32 | if(factor > num) 33 | factor = 4; 34 | 35 | if(num%factor!=0) 36 | return false; 37 | num /= 4; 38 | } 39 | return true; 40 | 41 | } 42 | } 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /344. Reverse String.md: -------------------------------------------------------------------------------- 1 | # 344. Reverse String 2 | 3 | Write a function that reverses a string. The input string is given as an array of characters `char[]`. 4 | 5 | Do not allocate extra space for another array, you must do this by **modifying the input array in-place** with O(1) extra memory. 6 | 7 | You may assume all the characters consist of [printable ascii characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters). 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: ["h","e","l","l","o"] 15 | Output: ["o","l","l","e","h"] 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: ["H","a","n","n","a","h"] 22 | Output: ["h","a","n","n","a","H"] 23 | ``` 24 | 25 | 26 | 27 | ## Code 28 | 29 | ```java 30 | class Solution { 31 | private void swap(char[] s, int st ,int ed) 32 | { 33 | char tmp = s[st]; 34 | s[st] = s[ed]; 35 | s[ed] = tmp; 36 | } 37 | public void reverseString(char[] s) { 38 | int ed = s.length-1; 39 | int st = 0; 40 | while(st set = new HashSet(); 27 | HashSet set2 = new HashSet(); 28 | List res = new ArrayList(); 29 | for(int num : nums1) 30 | set.add(num); 31 | for(int num : nums2) 32 | set2.add(num); 33 | for(int num : set2) 34 | { 35 | if(set.contains(num)) 36 | res.add(num); 37 | } 38 | int len = res.size(); 39 | int[] ret = new int[len]; 40 | for(int i=0;i=判断是为了考虑[1,2,3,4]找0 和 [6,7,8,9]找10的情况! 38 | 39 | **Code:** 40 | 41 | ``` 42 | class Solution: 43 | def searchInsert(self, nums, target): 44 | """ 45 | :type nums: List[int] 46 | :type target: int 47 | :rtype: int 48 | """ 49 | if len(nums) == 0: 50 | return 0 51 | 52 | st = 0 53 | ed = len(nums)-1 54 | while st < ed-1: 55 | mid = (st + ed) // 2 56 | if nums[mid] < target: 57 | st = mid + 1 58 | elif nums[mid] > target: 59 | ed = mid 60 | else: 61 | return mid 62 | if nums[st] >= target: 63 | return st 64 | elif nums[ed] >= target: 65 | return ed 66 | else: 67 | return ed+1 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /357. Count Numbers with Unique Digits.md: -------------------------------------------------------------------------------- 1 | # 357. Count Numbers with Unique Digits 2 | 3 | Given a **non-negative** integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: 2 9 | Output: 91 10 | Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, 11 | excluding 11,22,33,44,55,66,77,88,99 12 | ``` 13 | 14 | 15 | 16 | ## Solution 17 | 18 | 数学题。 19 | 20 | 21 | 22 | ## Code 23 | 24 | ```java 25 | class Solution { 26 | public int Amn(int m, int n) 27 | { 28 | if(m==0) 29 | return 0; 30 | int res = 1; 31 | while(m>0) 32 | { 33 | res *= n--; 34 | m--; 35 | } 36 | return res; 37 | 38 | } 39 | 40 | public int countNumbersWithUniqueDigits(int n) { 41 | if(n<0) 42 | return 0; 43 | if(n==0) 44 | return 1; 45 | int res = 0; 46 | int cur = Math.min(n,10); 47 | while(cur > 0) 48 | { 49 | res += Amn(cur,10) - Amn(cur-1,9); 50 | cur--; 51 | } 52 | return res; 53 | } 54 | } 55 | ``` 56 | 57 | -------------------------------------------------------------------------------- /374. Guess Number Higher or Lower.md: -------------------------------------------------------------------------------- 1 | # 374. Guess Number Higher or Lower 2 | 3 | We are playing the Guess Game. The game is as follows: 4 | 5 | I pick a number from **1** to **n**. You have to guess which number I picked. 6 | 7 | Every time you guess wrong, I'll tell you whether the number is higher or lower. 8 | 9 | You call a pre-defined API `guess(int num)` which returns 3 possible results (`-1`, `1`, or `0`): 10 | 11 | ``` 12 | -1 : My number is lower 13 | 1 : My number is higher 14 | 0 : Congrats! You got it! 15 | ``` 16 | 17 | **Example :** 18 | 19 | ``` 20 | Input: n = 10, pick = 6 21 | Output: 6 22 | ``` 23 | 24 | 25 | 26 | ## Code 27 | 28 | ```java 29 | public class Solution extends GuessGame { 30 | public int guessNumber(int n) { 31 | int st = 1; 32 | int ed = n; 33 | while(st < ed) 34 | { 35 | int mid = st + (ed - st)/2; 36 | // System.out.println(mid); 37 | int res = guess(mid); 38 | if(res==0) 39 | return mid; 40 | if(res == 1) 41 | st = mid+1; 42 | else 43 | ed = mid-1; 44 | } 45 | return st; 46 | } 47 | } 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /377. Combination Sum IV.md: -------------------------------------------------------------------------------- 1 | # 377. Combination Sum IV 2 | 3 | Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. 4 | 5 | **Example:** 6 | 7 | ``` 8 | nums = [1, 2, 3] 9 | target = 4 10 | 11 | The possible combination ways are: 12 | (1, 1, 1, 1) 13 | (1, 1, 2) 14 | (1, 2, 1) 15 | (1, 3) 16 | (2, 1, 1) 17 | (2, 2) 18 | (3, 1) 19 | 20 | Note that different sequences are counted as different combinations. 21 | 22 | Therefore the output is 7. 23 | ``` 24 | 25 | ## Solution 26 | 27 | 没有重复的数字,并且可以重复使用,并且排列顺序可以算不同种类,那就无脑递归即可。开一个map来避免重复运算。 28 | 29 | 30 | 31 | ## Code 32 | 33 | ```java 34 | class Solution { 35 | HashMap map = new HashMap(); 36 | public int combinationSum4(int[] nums, int target) { 37 | if(map.containsKey(target)) 38 | return (int)(map.get(target)); 39 | 40 | int len = nums.length; 41 | int res = 0; 42 | for(int i=0;i 4 -> 2 -> 1 18 | ``` 19 | 20 | 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: 26 | 7 27 | 28 | Output: 29 | 4 30 | 31 | Explanation: 32 | 7 -> 8 -> 4 -> 2 -> 1 33 | or 34 | 7 -> 6 -> 3 -> 2 -> 1 35 | ``` 36 | 37 | ## Solution 38 | 39 | 递归三行很简单。 40 | 41 | 位运算会更快(71%),也不难,有了思路就可。 42 | 43 | 44 | 45 | ## Code 46 | 47 | ```python 48 | class Solution(object): 49 | def integerReplacement(self, n): 50 | """ 51 | :type n: int 52 | :rtype: int 53 | """ 54 | count = 0 55 | while n > 1: 56 | if n & 1 == 0: 57 | n = n >> 1 58 | count += 1 59 | else: 60 | if n & 2 == 2: 61 | if n == 3: 62 | n -= 1 63 | else: 64 | n += 1 65 | count += 1 66 | else: 67 | n -= 1 68 | count += 1 69 | return count 70 | ``` 71 | 72 | -------------------------------------------------------------------------------- /398. Random Pick Index.md: -------------------------------------------------------------------------------- 1 | # [398. Random Pick Index](https://leetcode-cn.com/problems/random-pick-index/) 2 | 3 | Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. 4 | 5 | Note: 6 | The array size can be very large. Solution that uses too much extra space will not pass the judge. 7 | 8 | **Example:** 9 | 10 | ```python 11 | int[] nums = new int[] {1,2,3,3,3}; 12 | Solution solution = new Solution(nums); 13 | 14 | // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. 15 | solution.pick(3); 16 | 17 | // pick(1) should return 0. Since in the array only nums[0] is equal to 1. 18 | solution.pick(1); 19 | ``` 20 | 21 | 22 | 23 | 蓄水池采样问题 24 | 25 | ## Code 26 | 27 | ```python 28 | from random import randint 29 | class Solution(object): 30 | 31 | nums = [] 32 | def __init__(self, nums): 33 | """ 34 | :type nums: List[int] 35 | """ 36 | self.nums = nums 37 | 38 | def pick(self, target): 39 | """ 40 | :type target: int 41 | :rtype: int 42 | """ 43 | count = 0 44 | res = None 45 | for i, v in enumerate(self.nums): 46 | if v == target: 47 | if not randint(0,count): 48 | res = i 49 | count += 1 50 | return res 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /400. Nth Digit.md: -------------------------------------------------------------------------------- 1 | # [400. Nth Digit](https://leetcode-cn.com/problems/nth-digit/) 2 | 3 | Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 4 | 5 | Note: 6 | n is positive and will fit within the range of a 32-bit signed integer (n < 231). 7 | 8 | **Example 1:** 9 | 10 | ``` 11 | Input: 12 | 3 13 | 14 | Output: 15 | 3 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: 22 | 11 23 | 24 | Output: 25 | 0 26 | 27 | Explanation: 28 | The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. 29 | ``` 30 | 31 | 32 | 33 | ## Code 34 | 35 | ```python 36 | class Solution(object): 37 | def findNthDigit(self, n): 38 | """ 39 | :type n: int 40 | :rtype: int 41 | """ 42 | # 9个1位 43 | # 90个2位 44 | # 900个3位 45 | digit = 1 46 | precount = 0 47 | curcount = 9 48 | while n > curcount*digit: 49 | n -= curcount * digit 50 | digit += 1 51 | curcount *= 10 52 | # digit位的第count位 53 | baseline = pow(10,digit-1) 54 | addon = (n-1) / digit 55 | rem = (n-1) % digit 56 | rem = digit-rem-1 57 | curval = baseline + addon 58 | # res = 0 59 | while rem > 0: 60 | curval /= 10 61 | rem -= 1 62 | res = curval % 10 63 | return res 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /401. Binary Watch.md: -------------------------------------------------------------------------------- 1 | # [401. Binary Watch](https://leetcode-cn.com/problems/binary-watch/) 2 | 3 | A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). 4 | 5 | Each LED represents a zero or one, with the least significant bit on the right. 6 | 7 | 8 | For example, the above binary watch reads "3:25". 9 | 10 | Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. 11 | 12 | **Example:** 13 | 14 | ```python 15 | Input: n = 1 16 | Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] 17 | Note: 18 | The order of output does not matter. 19 | The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". 20 | The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". 21 | ``` 22 | 23 | 24 | 25 | ## Code 26 | 27 | ```python 28 | class Solution(object): 29 | def readBinaryWatch(self, num): 30 | """ 31 | :type num: int 32 | :rtype: List[str] 33 | """ 34 | return ["%d:%02d"%(i,j) for j in range(60) for i in range(12) if bin(i).count('1')+bin(j).count('1')==num] 35 | 36 | ``` 37 | 38 | -------------------------------------------------------------------------------- /404. Sum of Left Leaves.md: -------------------------------------------------------------------------------- 1 | # [404. Sum of Left Leaves](https://leetcode-cn.com/problems/sum-of-left-leaves/) 2 | 3 | Find the sum of all left leaves in a given binary tree. 4 | 5 | **Example:** 6 | 7 | 3 8 | / \ 9 | 9 20 10 | / \ 11 | 15 7 12 | 13 | 14 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 15 | 16 | 17 | 18 | ## Code 19 | 20 | ```python 21 | # Definition for a binary tree node. 22 | # class TreeNode(object): 23 | # def __init__(self, x): 24 | # self.val = x 25 | # self.left = None 26 | # self.right = None 27 | 28 | class Solution(object): 29 | def sumOfLeftLeaves(self, root): 30 | """ 31 | :type root: TreeNode 32 | :rtype: int 33 | """ 34 | def isleaf(root): 35 | if not root: 36 | return False 37 | if not root.left and not root.right: 38 | return True 39 | else: 40 | return False 41 | 42 | res = 0 43 | if not root: 44 | return res 45 | if root.left and isleaf(root.left): 46 | return root.left.val + self.sumOfLeftLeaves(root.right) 47 | else: 48 | return self.sumOfLeftLeaves(root.right) + self.sumOfLeftLeaves(root.left) 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /405. Convert a Number to Hexadecimal.md: -------------------------------------------------------------------------------- 1 | # [405. Convert a Number to Hexadecimal](https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal/) 2 | 3 | Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. 4 | 5 | Note: 6 | 7 | All letters in hexadecimal (a-f) must be in lowercase. 8 | The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character. 9 | The given number is guaranteed to fit within the range of a 32-bit signed integer. 10 | You must not use any method provided by the library which converts/formats the number to hex directly. 11 | **Example 1:** 12 | 13 | ``` 14 | Input: 15 | 26 16 | 17 | Output: 18 | "1a" 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: 25 | -1 26 | 27 | Output: 28 | "ffffffff" 29 | ``` 30 | 31 | ## Solution 32 | 33 | 移位or除法取余都可。 34 | 35 | 36 | 37 | ## Code 38 | 39 | ```python 40 | class Solution(object): 41 | def toHex(self, num): 42 | """ 43 | :type num: int 44 | :rtype: str 45 | """ 46 | if num == 0: 47 | return "0" 48 | res = "" 49 | table = "0123456789abcdef" 50 | while num and len(res)<8: 51 | cur = num & 15 52 | num >>= 4 53 | res += table[cur] 54 | return res[::-1] 55 | ``` 56 | 57 | -------------------------------------------------------------------------------- /414. Third Maximum Number.md: -------------------------------------------------------------------------------- 1 | # 414. Third Maximum Number 2 | 3 | Given a **non-empty** array of integers, return the **third** maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: [3, 2, 1] 9 | 10 | Output: 1 11 | 12 | Explanation: The third maximum is 1. 13 | ``` 14 | 15 | 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: [1, 2] 21 | 22 | Output: 2 23 | 24 | Explanation: The third maximum does not exist, so the maximum (2) is returned instead. 25 | ``` 26 | 27 | 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: [2, 2, 3, 1] 33 | 34 | Output: 1 35 | 36 | Explanation: Note that the third maximum here means the third maximum distinct number. 37 | Both numbers with value 2 are both considered as second maximum. 38 | ``` 39 | 40 | 41 | 42 | ## Code 43 | 44 | ```python 45 | class Solution(object): 46 | def thirdMax(self, nums): 47 | """ 48 | :type nums: List[int] 49 | :rtype: int 50 | """ 51 | res = [float('-inf'),float('-inf'),float('-inf')] 52 | for num in nums: 53 | if num not in res: 54 | if num > res[0]: 55 | res = [num,res[0],res[1]] 56 | elif num > res[1]: 57 | res = [res[0],num,res[1]] 58 | elif num > res[2]: 59 | res = [res[0],res[1],num] 60 | return res[2] if res[2]!=float('-inf') else res[0] 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /415. Add Strings.md: -------------------------------------------------------------------------------- 1 | # 415. Add Strings 2 | 3 | Given two non-negative integers `num1` and `num2` represented as string, return the sum of `num1` and `num2`. 4 | 5 | **Note:** 6 | 7 | 1. The length of both `num1` and `num2` is < 5100. 8 | 2. Both `num1` and `num2` contains only digits `0-9`. 9 | 3. Both `num1` and `num2` does not contain any leading zero. 10 | 4. You **must not use any built-in BigInteger library** or **convert the inputs to integer** directly. 11 | 12 | 13 | 14 | ## Code 15 | 16 | ```python 17 | class Solution(object): 18 | def addStrings(self, num1, num2): 19 | """ 20 | :type num1: str 21 | :type num2: str 22 | :rtype: str 23 | """ 24 | num1 = num1[::-1] 25 | num2 = num2[::-1] 26 | res = "" 27 | addon = 0 28 | len1 = len(num1) 29 | len2 = len(num2) 30 | length = max(len1,len2) 31 | for i in range(length): 32 | cur = addon 33 | addon = 0 34 | if i 0: 42 | res += (str(addon)) 43 | return res[::-1] 44 | ``` 45 | 46 | -------------------------------------------------------------------------------- /416. Partition Equal Subset Sum.md: -------------------------------------------------------------------------------- 1 | # 416. Partition Equal Subset Sum 2 | 3 | Given a **non-empty** array containing **only positive integers**, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. 4 | 5 | **Note:** 6 | 7 | 1. Each of the array element will not exceed 100. 8 | 2. The array size will not exceed 200. 9 | 10 | 11 | 12 | **Example 1:** 13 | 14 | ``` 15 | Input: [1, 5, 11, 5] 16 | 17 | Output: true 18 | 19 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 20 | ``` 21 | 22 | 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: [1, 2, 3, 5] 28 | 29 | Output: false 30 | 31 | Explanation: The array cannot be partitioned into equal sum subsets. 32 | ``` 33 | 34 | 35 | 36 | ## Solution 37 | 38 | 递归行不通会超时,DP好用(但是如果是两个大数,内存会不够吧)。 39 | 40 | 41 | 42 | ## Code 43 | 44 | ```python 45 | class Solution(object): 46 | def canPartition(self, nums): 47 | """ 48 | :type nums: List[int] 49 | :rtype: bool 50 | """ 51 | 52 | numsum = sum(nums) 53 | if numsum%2 == 1: 54 | return False 55 | target = numsum / 2 56 | table = [False for _ in range(target+1)] 57 | table[0] = True 58 | for num in nums: 59 | for i in range(target,-1,-1): 60 | if table[i]: 61 | if i+num<=target: 62 | table[i+num] = True 63 | elif i+num==target: 64 | return True 65 | 66 | return table[target] 67 | ``` 68 | 69 | -------------------------------------------------------------------------------- /429. N-ary Tree Level Order Traversal.md: -------------------------------------------------------------------------------- 1 | # 429. N-ary Tree Level Order Traversal 2 | 3 | Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 4 | 5 | For example, given a `3-ary` tree: 6 | 7 | 8 | 9 | ![img](https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png) 10 | 11 | 12 | 13 | We should return its level order traversal: 14 | 15 | ``` 16 | [ 17 | [1], 18 | [3,2,4], 19 | [5,6] 20 | ] 21 | ``` 22 | 23 | 24 | 25 | **Note:** 26 | 27 | 1. The depth of the tree is at most `1000`. 28 | 2. The total number of nodes is at most `5000`. 29 | 30 | ## Code 31 | 32 | ```python 33 | """ 34 | # Definition for a Node. 35 | class Node(object): 36 | def __init__(self, val, children): 37 | self.val = val 38 | self.children = children 39 | """ 40 | class Solution(object): 41 | def levelOrder(self, root): 42 | """ 43 | :type root: Node 44 | :rtype: List[List[int]] 45 | """ 46 | stack = [] 47 | depth = [] 48 | res = [] 49 | if not root: 50 | return res 51 | stack.append(root) 52 | depth.append(0) 53 | while stack: 54 | node = stack.pop(0) 55 | height = depth.pop(0) 56 | if height == len(res): 57 | res.append([node.val]) 58 | else: 59 | res[-1].append(node.val) 60 | for child in node.children: 61 | stack.append(child) 62 | depth.append(height+1) 63 | return res 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /434. Number of Segments in a String.md: -------------------------------------------------------------------------------- 1 | # [✅] 434. Number of Segments in a String 2 | 3 | Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 4 | 5 | Please note that the string does not contain any **non-printable** characters. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: "Hello, my name is John" 11 | Output: 5 12 | ``` 13 | 14 | 15 | 16 | ## Code 17 | 18 | ```python 19 | class Solution(object): 20 | def countSegments(self, s): 21 | """ 22 | :type s: str 23 | :rtype: int 24 | """ 25 | count = 0 26 | idx = 0 27 | while idx < len(s): 28 | if s[idx]!=' ': 29 | count += 1 30 | while idx < len(s) and s[idx]!=' ': 31 | idx += 1 32 | while idx < len(s) and s[idx]==' ': 33 | idx += 1 34 | return count 35 | ``` 36 | 37 | -------------------------------------------------------------------------------- /440. K-th Smallest in Lexicographical Order.md: -------------------------------------------------------------------------------- 1 | # 440. K-th Smallest in Lexicographical Order 2 | 3 | Given integers `n` and `k`, find the lexicographically k-th smallest integer in the range from `1` to `n`. 4 | 5 | Note: 1 ≤ k ≤ n ≤ 109. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: 11 | n: 13 k: 2 12 | 13 | Output: 14 | 10 15 | 16 | Explanation: 17 | The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. 18 | ``` 19 | 20 | 21 | 22 | ## Code 23 | 24 | ``` 25 | class Solution(object): 26 | def findKthNumber(self, n, k): 27 | """ 28 | :type n: int 29 | :type k: int 30 | :rtype: int 31 | """ 32 | res = [] 33 | def helper(curnum,n,k): 34 | for num in range(curnum,curnum+10): 35 | if num <= n: 36 | res.append(num) 37 | helper(num*10,n,k) 38 | 39 | helper(1,n,k) 40 | print(res) 41 | return res[k-1] 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /441. Arranging Coins.md: -------------------------------------------------------------------------------- 1 | # 441. Arranging Coins 2 | 3 | You have a total of *n* coins that you want to form in a staircase shape, where every *k*-th row must have exactly *k* coins. 4 | 5 | Given *n*, find the total number of **full** staircase rows that can be formed. 6 | 7 | *n* is a non-negative integer and fits within the range of a 32-bit signed integer. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | n = 5 13 | 14 | The coins can form the following rows: 15 | ¤ 16 | ¤ ¤ 17 | ¤ ¤ 18 | 19 | Because the 3rd row is incomplete, we return 2. 20 | ``` 21 | 22 | 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | n = 8 28 | 29 | The coins can form the following rows: 30 | ¤ 31 | ¤ ¤ 32 | ¤ ¤ ¤ 33 | ¤ ¤ 34 | 35 | Because the 4th row is incomplete, we return 3. 36 | ``` 37 | 38 | 39 | 40 | ## Code 41 | 42 | ```python 43 | class Solution(object): 44 | def arrangeCoins(self, n): 45 | """ 46 | :type n: int 47 | :rtype: int 48 | """ 49 | if n < 0: 50 | return 0 51 | st = 0 52 | ed = int(math.sqrt(2*n)) 53 | while st < ed: 54 | mid = (st+ed+1)/2 55 | if (1+mid)*mid/2 <= n: 56 | st = mid 57 | else: 58 | ed = mid - 1 59 | return st 60 | ``` 61 | 62 | -------------------------------------------------------------------------------- /442. Find All Duplicates in an Array.md: -------------------------------------------------------------------------------- 1 | # [✅] 442. Find All Duplicates in an Array 2 | 3 | Given an array of integers, 1 ≤ a[i] ≤ *n* (*n* = size of array), some elements appear **twice** and others appear **once**. 4 | 5 | Find all the elements that appear **twice** in this array. 6 | 7 | Could you do it without extra space and in O(*n*) runtime? 8 | 9 | 10 | 11 | **Example:** 12 | 13 | ``` 14 | Input: 15 | [4,3,2,7,8,2,3,1] 16 | 17 | Output: 18 | [2,3] 19 | ``` 20 | 21 | 22 | 23 | ## Code 24 | 25 | ```python 26 | class Solution(object): 27 | def findDuplicates(self, nums): 28 | """ 29 | :type nums: List[int] 30 | :rtype: List[int] 31 | """ 32 | res = [] 33 | for num in nums: 34 | if nums[abs(num)-1] < 0: 35 | res.append(abs(num)) 36 | else: 37 | nums[abs(num)-1] *= -1 38 | return res 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /447. Number of Boomerangs.md: -------------------------------------------------------------------------------- 1 | # 447. Number of Boomerangs 2 | 3 | Given *n* points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points `(i, j, k)` such that the distance between `i` and `j` equals the distance between `i` and `k` (**the order of the tuple matters**). 4 | 5 | Find the number of boomerangs. You may assume that *n* will be at most **500** and coordinates of points are all in the range **[-10000, 10000]** (inclusive). 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: 11 | [[0,0],[1,0],[2,0]] 12 | 13 | Output: 14 | 2 15 | 16 | Explanation: 17 | The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] 18 | ``` 19 | 20 | 21 | 22 | ## Solution 23 | 24 | 戳[这里](https://leetcode.com/problems/number-of-boomerangs/discuss/92868/Short-Python-O(n2)-hashmap-solution) 25 | 26 | 27 | 28 | ## Code 29 | 30 | ```python 31 | class Solution(object): 32 | def numberOfBoomerangs(self, points): 33 | """ 34 | :type points: List[List[int]] 35 | :rtype: int 36 | """ 37 | 38 | res = 0 39 | for pt in points: 40 | mapp = {} 41 | for pt2 in points: 42 | v1 = pt[0]-pt2[0] 43 | v2 = pt[1]-pt2[1] 44 | dist = v1*v1 + v2*v2 45 | mapp[dist] = mapp.get(dist,0) + 1 46 | for dist in mapp: 47 | res += mapp[dist]*(mapp[dist]-1) 48 | return res 49 | 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /448. Find All Numbers Disappeared in an Array.md: -------------------------------------------------------------------------------- 1 | # 448. Find All Numbers Disappeared in an Array 2 | 3 | Given an array of integers where 1 ≤ a[i] ≤ *n* (*n* = size of array), some elements appear twice and others appear once. 4 | 5 | Find all the elements of [1, *n*] inclusive that do not appear in this array. 6 | 7 | Could you do it without extra space and in O(*n*) runtime? You may assume the returned list does not count as extra space. 8 | 9 | **Example:** 10 | 11 | ``` 12 | Input: 13 | [4,3,2,7,8,2,3,1] 14 | 15 | Output: 16 | [5,6] 17 | ``` 18 | 19 | 20 | 21 | ## Code 22 | 23 | ```python 24 | class Solution(object): 25 | def findDisappearedNumbers(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: List[int] 29 | """ 30 | for num in nums: 31 | if nums[abs(num)-1] > 0: 32 | nums[abs(num)-1] *= -1 33 | 34 | res = [] 35 | for i in range(len(nums)): 36 | if nums[i]>0: 37 | res.append(i+1) 38 | return res 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /45. Jump Game II.md: -------------------------------------------------------------------------------- 1 | # 45. Jump Game II 2 | 3 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | 5 | Each element in the array represents your maximum jump length at that position. 6 | 7 | Your goal is to reach the last index in the minimum number of jumps. 8 | 9 | **Example:** 10 | 11 | ``` 12 | Input: [2,3,1,1,4] 13 | Output: 2 14 | Explanation: The minimum number of jumps to reach the last index is 2. 15 | Jump 1 step from index 0 to 1, then 3 steps to the last index. 16 | ``` 17 | 18 | **Note:** 19 | 20 | You can assume that you can always reach the last index. 21 | 22 | ## Solution: 23 | 24 | 哇这个解法...五体投地...也太精妙了吧ooooorz 25 | 26 | 贪心算法,希望每次都能走到最远的地方。 27 | 28 | 变量命名非常清楚了。 29 | 30 | previous_jump_max记录了上一次jump之后,可以到达的最远地方。 31 | 32 | current_jump_max记录了下一次jump之后,可以到达的最远地方。 33 | 34 | 每次如果抵达了上一次的最远点,就读取当前可以到的最远点,更新跳过去。 35 | 36 | 最后到了目的地的前一个点,如果没有更新jump,那就说明当前(倒数第二个点)不是上一次可以跳的最远点,也就是说上一次jump可以抵达最后一个点(目的地)。 37 | 38 | 啊惊叹。 39 | 40 | 41 | 42 | ## Code: 43 | 44 | ```python 45 | class Solution: 46 | def jump(self, nums): 47 | """ 48 | :type nums: List[int] 49 | :rtype: int 50 | """ 51 | jumps = 0 52 | current_jump_max = 0 53 | previous_jump_max = 0 54 | 55 | for i in range(len(nums) - 1): 56 | current_jump_max = max(current_jump_max, i + nums[i]) 57 | #Note 1 58 | if i == previous_jump_max: 59 | jumps += 1 60 | previous_jump_max = current_jump_max 61 | #Note 2 62 | return jumps 63 | ``` 64 | 65 | -------------------------------------------------------------------------------- /453. Minimum Moves to Equal Array Elements.md: -------------------------------------------------------------------------------- 1 | # 453. Minimum Moves to Equal Array Elements 2 | 3 | Given a **non-empty** integer array of size *n*, find the minimum number of moves required to make all array elements equal, where a move is incrementing *n* - 1 elements by 1. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: 9 | [1,2,3] 10 | 11 | Output: 12 | 3 13 | 14 | Explanation: 15 | Only three moves are needed (remember each move increments two elements): 16 | 17 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 18 | ``` 19 | 20 | 21 | 22 | ## Code 23 | 24 | ```python 25 | class Solution(object): 26 | def minMoves(self, nums): 27 | """ 28 | :type nums: List[int] 29 | :rtype: int 30 | """ 31 | return sum(nums)-len(nums)*min(nums) 32 | ``` 33 | 34 | -------------------------------------------------------------------------------- /454. 4Sum II.md: -------------------------------------------------------------------------------- 1 | # 454. 4Sum II 2 | 3 | Given four lists A, B, C, D of integer values, compute how many tuples `(i, j, k, l)` there are such that `A[i] + B[j] + C[k] + D[l]` is zero. 4 | 5 | To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: 11 | A = [ 1, 2] 12 | B = [-2,-1] 13 | C = [-1, 2] 14 | D = [ 0, 2] 15 | 16 | Output: 17 | 2 18 | 19 | Explanation: 20 | The two tuples are: 21 | 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 22 | 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 23 | ``` 24 | 25 | 26 | 27 | ## Code 28 | 29 | ```python 30 | class Solution(object): 31 | def fourSumCount(self, A, B, C, D): 32 | """ 33 | :type A: List[int] 34 | :type B: List[int] 35 | :type C: List[int] 36 | :type D: List[int] 37 | :rtype: int 38 | """ 39 | map = {} 40 | res = 0 41 | for a in A: 42 | for b in B: 43 | map[a+b] = map.get(a+b,0)+1 44 | 45 | for c in C: 46 | for d in D: 47 | if -c-d in map: 48 | res += map[-c-d] 49 | return res 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /459. Repeated Substring Pattern.md: -------------------------------------------------------------------------------- 1 | # [✅] 459. Repeated Substring Pattern 2 | 3 | Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. 4 | 5 | 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: "abab" 11 | Output: True 12 | Explanation: It's the substring "ab" twice. 13 | ``` 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: "aba" 19 | Output: False 20 | ``` 21 | 22 | **Example 3:** 23 | 24 | ``` 25 | Input: "abcabcabcabc" 26 | Output: True 27 | Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) 28 | ``` 29 | 30 | ## Solution 31 | 32 | 如果长度为4的substring不满足条件,那么2也不行。同理若16不行,8也不行。 33 | 34 | 35 | 36 | ## Code 37 | 38 | ```python 39 | class Solution(object): 40 | def repeatedSubstringPattern(self, s): 41 | """ 42 | :type s: str 43 | :rtype: bool 44 | """ 45 | length = len(s) 46 | visited = set() 47 | for l in range(length/2,0,-1): 48 | if length % l != 0 or any(num%l==0 for num in visited): 49 | continue 50 | visited.add(l) 51 | 52 | pattern = s[:l] 53 | repeat = length / l 54 | for i in range(1,repeat): 55 | if s[i*l:i*l+l]!=pattern: 56 | break 57 | if i == repeat-1: 58 | return True 59 | return False 60 | ``` 61 | 62 | -------------------------------------------------------------------------------- /46. Permutations.md: -------------------------------------------------------------------------------- 1 | # 46. Permutations 2 | 3 | Given a collection of **distinct** integers, return all possible permutations. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: [1,2,3] 9 | Output: 10 | [ 11 | [1,2,3], 12 | [1,3,2], 13 | [2,1,3], 14 | [2,3,1], 15 | [3,1,2], 16 | [3,2,1] 17 | ] 18 | ``` 19 | 20 | 21 | 22 | ### Resolution: 23 | 24 | 递归解决,和之前combination的类似。 25 | 26 | ### Code: 27 | 28 | ```python 29 | def combine(candidates, target): 30 | candidates.sort() 31 | res = [] 32 | for i, c in enumerate(candidates): 33 | if c < target: 34 | for sub in combine(candidates[i:], target - c): 35 | if type(sub) == int: 36 | res.append([c] + [sub]) 37 | else: 38 | res.append([c] + sub) 39 | elif c == target: 40 | res.append([c]) 41 | return res 42 | 43 | class Solution: 44 | def combinationSum(self, candidates, target): 45 | """ 46 | :type candidates: List[int] 47 | :type target: int 48 | :rtype: List[List[int]] 49 | """ 50 | result = combine(candidates, target) 51 | return result 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /461. Hamming Distance.md: -------------------------------------------------------------------------------- 1 | # 461. Hamming Distance 2 | 3 | The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. 4 | 5 | Given two integers `x` and `y`, calculate the Hamming distance. 6 | 7 | **Note:** 8 | 0 ≤ `x`, `y` < 231. 9 | 10 | **Example:** 11 | 12 | ``` 13 | Input: x = 1, y = 4 14 | 15 | Output: 2 16 | 17 | Explanation: 18 | 1 (0 0 0 1) 19 | 4 (0 1 0 0) 20 | ↑ ↑ 21 | 22 | The above arrows point to positions where the corresponding bits are different. 23 | ``` 24 | 25 | 26 | 27 | ## Code 28 | 29 | ```python 30 | class Solution(object): 31 | def hammingDistance(self, x, y): 32 | """ 33 | :type x: int 34 | :type y: int 35 | :rtype: int 36 | """ 37 | return bin(x^y).count('1') 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /47. Permutations II.md: -------------------------------------------------------------------------------- 1 | # 47. Permutations II 2 | 3 | Given a collection of numbers that might contain duplicates, return all possible unique permutations. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: [1,1,2] 9 | Output: 10 | [ 11 | [1,1,2], 12 | [1,2,1], 13 | [2,1,1] 14 | ] 15 | ``` 16 | 17 | ### Resolution: 18 | 19 | 递归解决,加上判断重复条件即可。 20 | 21 | 22 | 23 | ### Code: 24 | 25 | ```python 26 | def per(nums): 27 | if len(nums) == 0: 28 | return [] 29 | if len(nums) == 1: 30 | return [nums] 31 | res = [] 32 | for i, c in enumerate(nums): 33 | for j in per(nums[0:i]+nums[i+1:]): 34 | if type(j) == int: 35 | if not res.__contains__([c]+[j]): 36 | res.append([c]+[j]) 37 | else: 38 | if not res.__contains__([c]+j): 39 | res.append([c]+j) 40 | return res 41 | 42 | 43 | class Solution: 44 | def permuteUnique(self, nums): 45 | """ 46 | :type nums: List[int] 47 | :rtype: List[List[int]] 48 | """ 49 | return per(nums) 50 | ``` 51 | 52 | -------------------------------------------------------------------------------- /470. Implement Rand10() Using Rand7().md: -------------------------------------------------------------------------------- 1 | # 470. Implement Rand10() Using Rand7() 2 | 3 | Given a function `rand7` which generates a uniform random integer in the range 1 to 7, write a function `rand10` which generates a uniform random integer in the range 1 to 10. 4 | 5 | Do NOT use system's `Math.random()`. 6 | 7 | 8 | 9 | 10 | 11 | **Example 1:** 12 | 13 | ``` 14 | Input: 1 15 | Output: [7] 16 | ``` 17 | 18 | **Example 2:** 19 | 20 | ``` 21 | Input: 2 22 | Output: [8,4] 23 | ``` 24 | 25 | **Example 3:** 26 | 27 | ``` 28 | Input: 3 29 | Output: [8,1,10] 30 | ``` 31 | 32 | 33 | 34 | **Note:** 35 | 36 | 1. `rand7` is predefined. 37 | 2. Each testcase has one argument: `n`, the number of times that `rand10` is called. 38 | 39 | 40 | 41 | **Follow up:** 42 | 43 | 1. What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function? 44 | 2. Could you minimize the number of calls to `rand7()`? 45 | 46 | 47 | 48 | ## Code 49 | 50 | ```python 51 | class Solution(object): 52 | def rand10(self): 53 | """ 54 | :rtype: int 55 | """ 56 | res = 40 57 | while res >= 40: 58 | res = (rand7()-1)*7 + rand7()-1 59 | return res % 10 +1 60 | ``` 61 | 62 | -------------------------------------------------------------------------------- /476. Number Complement.md: -------------------------------------------------------------------------------- 1 | # 476. Number Complement 2 | 3 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 4 | 5 | **Note:** 6 | 7 | 1. The given integer is guaranteed to fit within the range of a 32-bit signed integer. 8 | 2. You could assume no leading zero bit in the integer’s binary representation. 9 | 10 | 11 | 12 | **Example 1:** 13 | 14 | ``` 15 | Input: 5 16 | Output: 2 17 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 18 | ``` 19 | 20 | 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: 1 26 | Output: 0 27 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 28 | ``` 29 | 30 | 31 | 32 | ## Code 33 | 34 | ```python 35 | class Solution(object): 36 | def findComplement(self, num): 37 | """ 38 | :type num: int 39 | :rtype: int 40 | """ 41 | num2 = num 42 | ones = 0 43 | 44 | while num2 > 0: 45 | num2 >>= 1 46 | ones = (ones << 1) + 1 47 | # ones += 1 48 | return (num ^ ones) 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /485. Max Consecutive Ones.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhouzhiling/leetcode/69166c67b01249b464951d2d78b05db902cc3734/485. Max Consecutive Ones.md -------------------------------------------------------------------------------- /5. Longest Palindromic Substring.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 5. Longest Palindromic Substring 4 | 5 | 6 | 7 | Given a string **s**, find the longest palindromic substring in **s**. You may assume that the maximum length of **s** is 1000. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: "babad" 13 | Output: "bab" 14 | Note: "aba" is also a valid answer. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: "cbbd" 21 | Output: "bb" 22 | ``` 23 | 24 | 25 | 26 | ## Solution 27 | 28 | 同样是O(N^2)的复杂度为啥我的就超时呢orz 29 | 30 | ## Code 31 | 32 | ```python 33 | def expand(s,i,j): 34 | while i >= 0 and j < len(s) and s[i] == s[j]: 35 | i -= 1 36 | j += 1 37 | if i+1 == j-1 or i+1 == j: 38 | return [i, 1] 39 | return [i+1, j-i-1] 40 | 41 | 42 | class Solution: 43 | def longestPalindrome(self, s): 44 | """ 45 | :type s: str 46 | :rtype: str 47 | """ 48 | if len(s) < 2: 49 | return s 50 | max_st = 0 51 | max_l = 0 52 | for i in range(len(s)-1): 53 | [st1, l1] = expand(s,i,i) 54 | [st2, l2] = expand(s,i,i+1) 55 | if l2 > max_l and l2 >= l1: 56 | max_st = st2 57 | max_l = l2 58 | elif l1 > max_l and l1 >= l2: 59 | max_st = st1 60 | max_l = l1 61 | return s[max_st:max_st+max_l] 62 | ``` 63 | 64 | -------------------------------------------------------------------------------- /50. Pow(x, n).md: -------------------------------------------------------------------------------- 1 | # 50. Pow(x, n) 2 | 3 | Implement [pow(*x*, *n*)](http://www.cplusplus.com/reference/valarray/pow/), which calculates *x* raised to the power *n* (xn). 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 2.00000, 10 9 | Output: 1024.00000 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: 2.10000, 3 16 | Output: 9.26100 17 | ``` 18 | 19 | **Example 3:** 20 | 21 | ``` 22 | Input: 2.00000, -2 23 | Output: 0.25000 24 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 25 | ``` 26 | 27 | **Note:** 28 | 29 | - -100.0 < *x* < 100.0 30 | - *n* is a 32-bit signed integer, within the range [−231, 231 − 1] 31 | 32 | 33 | 34 | ## Code: 35 | 36 | ```python 37 | class Solution: 38 | def myPow(self, x, n): 39 | """ 40 | :type x: float 41 | :type n: int 42 | :rtype: float 43 | """ 44 | if x == 0 or x == 1: 45 | return x 46 | 47 | flag = 0 48 | if n < 0: 49 | flag = 1 50 | n = abs(n) 51 | left = n 52 | q = 1 53 | val = x 54 | result = 1 55 | while left > 0: 56 | if left >= q: 57 | result *= val 58 | left -= q 59 | q *= 2 60 | val *= val 61 | else: 62 | q = 1 63 | val = x 64 | 65 | if flag == 1: 66 | return 1/result 67 | else: 68 | return result 69 | ``` 70 | 71 | -------------------------------------------------------------------------------- /504. Base 7.md: -------------------------------------------------------------------------------- 1 | # 504. Base 7 2 | 3 | Given an integer, return its base 7 string representation. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 100 9 | Output: "202" 10 | ``` 11 | 12 | 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: -7 18 | Output: "-10" 19 | ``` 20 | 21 | 22 | 23 | **Note:** The input will be in range of [-1e7, 1e7]. 24 | 25 | 26 | 27 | ## Code 28 | 29 | ```python 30 | class Solution(object): 31 | def convertToBase7(self, num): 32 | """ 33 | :type num: int 34 | :rtype: str 35 | """ 36 | flag = num > 0 37 | num = abs(num) 38 | if num == 0: 39 | return "0" 40 | table = [] 41 | while num > 0: 42 | table.append(str(num % 7)) 43 | num /= 7 44 | if flag: 45 | return "".join(table[::-1]) 46 | else: 47 | return "-" + "".join(table[::-1]) 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /507. Perfect Number.md: -------------------------------------------------------------------------------- 1 | # [✅] 507. Perfect Number 2 | 3 | We define the Perfect Number is a **positive** integer that is equal to the sum of all its **positive** divisors except itself. 4 | 5 | Now, given an **integer** 6 | 7 | 8 | 9 | **Example:** 10 | 11 | ``` 12 | Input: 28 13 | Output: True 14 | Explanation: 28 = 1 + 2 + 4 + 7 + 14 15 | ``` 16 | 17 | 18 | 19 | **Note:** The input number **n** will not exceed 100,000,000. (1e8) 20 | 21 | 22 | 23 | ## Code 24 | 25 | ```python 26 | class Solution(object): 27 | def checkPerfectNumber(self, num): 28 | """ 29 | :type num: int 30 | :rtype: bool 31 | """ 32 | if num <= 3: 33 | return False 34 | cursum = 1 35 | end = int(math.sqrt(num)) 36 | for i in range(2,end+1): 37 | if num % i == 0: 38 | if i == num / i: 39 | cursum += i 40 | else: 41 | cursum += i + (num/i) 42 | return cursum == num 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /516. Longest Palindromic Subsequence.md: -------------------------------------------------------------------------------- 1 | # 516. Longest Palindromic Subsequence 2 | 3 | Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. 4 | 5 | **Example 1:** 6 | Input: 7 | 8 | ``` 9 | "bbbab" 10 | ``` 11 | 12 | Output: 13 | 14 | ``` 15 | 4 16 | ``` 17 | 18 | One possible longest palindromic subsequence is "bbbb". 19 | 20 | 21 | 22 | **Example 2:** 23 | Input: 24 | 25 | ``` 26 | "cbbd" 27 | ``` 28 | 29 | Output: 30 | 31 | ``` 32 | 2 33 | ``` 34 | 35 | One possible longest palindromic subsequence is "bb". 36 | 37 | 38 | 39 | ## Code 40 | 41 | ```python 42 | class Solution(object): 43 | def longestPalindromeSubseq(self, s): 44 | """ 45 | :type s: str 46 | :rtype: int 47 | """ 48 | length = len(s) 49 | table = [[0 for _ in range(length)] for _ in range(length)] 50 | for st in range(length-1,-1,-1): 51 | table[st][st] = 1 52 | for ed in range(st+1,length,1): 53 | if s[st] == s[ed]: 54 | table[st][ed] = 2 + table[st+1][ed-1] 55 | else: 56 | table[st][ed] = max(table[st+1][ed],table[st][ed-1]) 57 | print(table) 58 | return table[0][-1] 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /520. Detect Capital.md: -------------------------------------------------------------------------------- 1 | # 520. Detect Capital 2 | 3 | Given a word, you need to judge whether the usage of capitals in it is right or not. 4 | 5 | We define the usage of capitals in a word to be right when one of the following cases holds: 6 | 7 | 1. All letters in this word are capitals, like "USA". 8 | 2. All letters in this word are not capitals, like "leetcode". 9 | 3. Only the first letter in this word is capital, like "Google". 10 | 11 | Otherwise, we define that this word doesn't use capitals in a right way. 12 | 13 | 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: "USA" 19 | Output: True 20 | ``` 21 | 22 | 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: "FlaG" 28 | Output: False 29 | ``` 30 | 31 | 32 | 33 | **Note:** The input will be a non-empty word consisting of uppercase and lowercase latin letters. 34 | 35 | 36 | 37 | ## Code 38 | 39 | ```python 40 | class Solution(object): 41 | def detectCapitalUse(self, word): 42 | """ 43 | :type word: str 44 | :rtype: bool 45 | """ 46 | if word==word.upper() or word==word.lower(): 47 | return True 48 | return word[1:] == word[1:].lower() 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /5213. Play with Chips.md: -------------------------------------------------------------------------------- 1 | There are some chips, and the i-th chip is at position `chips[i]`. 2 | 3 | You can perform any of the two following types of moves **any number of times** (possibly zero) **on any chip**: 4 | 5 | - Move the `i`-th chip by 2 units to the left or to the right with a cost of **0**. 6 | - Move the `i`-th chip by 1 unit to the left or to the right with a cost of **1**. 7 | 8 | There can be two or more chips at the same position initially. 9 | 10 | Return the minimum cost needed to move all the chips to the same position (any position). 11 | 12 | 13 | 14 | **Example 1:** 15 | 16 | ``` 17 | Input: chips = [1,2,3] 18 | Output: 1 19 | Explanation: Second chip will be moved to positon 3 with cost 1. First chip will be moved to position 3 with cost 0. Total cost is 1. 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: chips = [2,2,2,3,3] 26 | Output: 2 27 | Explanation: Both fourth and fifth chip will be moved to position two with cost 1. Total minimum cost will be 2. 28 | ``` 29 | 30 | 31 | 32 | **Constraints:** 33 | 34 | - `1 <= chips.length <= 100` 35 | - `1 <= chips[i] <= 10^9` 36 | 37 | 38 | 39 | ## Code 40 | 41 | ```python 42 | class Solution(object): 43 | def minCostToMoveChips(self, chips): 44 | """ 45 | :type chips: List[int] 46 | :rtype: int 47 | """ 48 | count = [0, 0] 49 | # count2 = 0 50 | for pos in chips: 51 | count[pos % 2] += 1 52 | return min(count) 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /525. Contiguous Array.md: -------------------------------------------------------------------------------- 1 | # 525. Contiguous Array 2 | 3 | Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: [0,1] 9 | Output: 2 10 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 11 | ``` 12 | 13 | 14 | 15 | **Example 2:** 16 | 17 | ``` 18 | Input: [0,1,0] 19 | Output: 2 20 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 21 | ``` 22 | 23 | 24 | 25 | **Note:** The length of the given binary array will not exceed 50,000. 26 | 27 | 28 | 29 | ## Code 30 | 31 | ```python 32 | class Solution(object): 33 | def findMaxLength(self, nums): 34 | """ 35 | :type nums: List[int] 36 | :rtype: int 37 | """ 38 | length = len(nums) 39 | table = [-1 for _ in range(length*2+1)] 40 | table[length] = 0 41 | cur = 0 42 | maxsize = 0 43 | for i,num in enumerate(nums): 44 | if num == 1: 45 | cur += 1 46 | else: 47 | cur -= 1 48 | if table[length+cur] == -1: 49 | table[length+cur] = i+1 50 | else: 51 | maxsize = max(maxsize,i-table[length+cur]+1) 52 | return maxsize 53 | ``` 54 | 55 | -------------------------------------------------------------------------------- /53. Maximum Subarray.md: -------------------------------------------------------------------------------- 1 | # 53. Maximum Subarray 2 | 3 | Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: [-2,1,-3,4,-1,2,1,-5,4], 9 | Output: 6 10 | Explanation: [4,-1,2,1] has the largest sum = 6. 11 | ``` 12 | 13 | **Follow up:** 14 | 15 | If you have figured out the O(*n*) solution, try coding another solution using the divide and conquer approach, which is more subtle. 16 | 17 | ## Solution 18 | 19 | 总觉得作业里面做过一样.... 20 | 21 | end++,计算head:end的和,和当前最大值比较,和小于零的时候就扔掉。 22 | 23 | 24 | 25 | ## Code 26 | 27 | ```python 28 | class Solution: 29 | def maxSubArray(self, nums): 30 | """ 31 | :type nums: List[int] 32 | :rtype: int 33 | """ 34 | 35 | head, tail, begin, end = 0, 0, 0, 0 36 | n = len(nums) 37 | cur_sum = 0 38 | max_sum = min(nums) 39 | while end < n: 40 | cur_sum += nums[end] 41 | end += 1 42 | if cur_sum > max_sum: 43 | max_sum = cur_sum 44 | head = begin 45 | tail = end 46 | if cur_sum <= 0: 47 | cur_sum = 0 48 | begin = end 49 | 50 | # print(max_sum) 51 | return max_sum 52 | ``` 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /531. Lonely Pixel I.md: -------------------------------------------------------------------------------- 1 | # 531. Lonely Pixel I 2 | 3 | Given a picture consisting of black and white pixels, find the number of black lonely pixels. 4 | 5 | The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively. 6 | 7 | A black lonely pixel is character 'B' that located at a specific position where the same row and same column don't have any other black pixels. 8 | 9 | Example: 10 | 11 | ``` 12 | Input: 13 | [['W', 'W', 'B'], 14 | ['W', 'B', 'W'], 15 | ['B', 'W', 'W']] 16 | 17 | Output: 3 18 | Explanation: All the three 'B's are black lonely pixels. 19 | ``` 20 | 21 | 22 | 23 | Note: 24 | 25 | 1. The range of width and height of the input 2D array is [1,500]. 26 | 27 | 28 | 29 | ## Code 30 | 31 | ```python 32 | matrix = [['W', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'W']] 33 | indexs = {} 34 | height = len(matrix) 35 | width = len(matrix[0]) 36 | lonelyCount = 0 37 | for h in range(height): 38 | count = 0 39 | index = [0, 0] 40 | for w in range(width): 41 | if matrix[h][w] == 'B': 42 | count += 1 43 | index = [h, w] 44 | if count == 1: 45 | indexs[str(index)] = 1 46 | 47 | for w in range(width): 48 | count = 0 49 | index = [0, 0] 50 | for h in range(height): 51 | if matrix[h][w] == 'B': 52 | count += 1 53 | index = [h, w] 54 | if count == 1 and str(index) in indexs: 55 | lonelyCount += 1 56 | print(lonelyCount) 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /537. Complex Number Multiplication.md: -------------------------------------------------------------------------------- 1 | # 537. Complex Number Multiplication 2 | 3 | Given two strings representing two [complex numbers](https://en.wikipedia.org/wiki/Complex_number). 4 | 5 | You need to return a string representing their multiplication. Note i2 = -1 according to the definition. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: "1+1i", "1+1i" 11 | Output: "0+2i" 12 | Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. 13 | ``` 14 | 15 | 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: "1+-1i", "1+-1i" 21 | Output: "0+-2i" 22 | Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. 23 | ``` 24 | 25 | 26 | 27 | **Note:** 28 | 29 | 1. The input strings will not have extra blank. 30 | 2. The input strings will be given in the form of **a+bi**, where the integer **a** and **b** will both belong to the range of [-100, 100]. And **the output should be also in this form**. 31 | 32 | 33 | 34 | ## Code 35 | 36 | ```python 37 | class Solution(object): 38 | def complexNumberMultiply(self, a, b): 39 | """ 40 | :type a: str 41 | :type b: str 42 | :rtype: str 43 | """ 44 | idxa1 = a.index("+") 45 | idxa2 = a.index("i") 46 | idxb1 = b.index("+") 47 | idxb2 = b.index("i") 48 | xa = int(a[:idxa1]) 49 | ya = int(a[idxa1+1:idxa2]) 50 | xb = int(b[:idxb1]) 51 | yb = int(b[idxb1+1:idxb2]) 52 | 53 | resa = xa*xb - ya*yb 54 | resb = xa*yb + ya*xb 55 | return str(resa)+"+"+str(resb)+"i" 56 | ``` 57 | 58 | -------------------------------------------------------------------------------- /538. Convert BST to Greater Tree.md: -------------------------------------------------------------------------------- 1 | # 538. Convert BST to Greater Tree 2 | 3 | Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: The root of a Binary Search Tree like this: 9 | 5 10 | / \ 11 | 2 13 12 | 13 | Output: The root of a Greater Tree like this: 14 | 18 15 | / \ 16 | 20 13 17 | ``` 18 | 19 | 20 | 21 | ## Code 22 | 23 | ```python 24 | class Solution(object): 25 | def convertBST(self, root): 26 | """ 27 | :type root: TreeNode 28 | :rtype: TreeNode 29 | """ 30 | if not root: 31 | return root 32 | stack = [] 33 | node = root 34 | curval = 0 35 | while node or stack: 36 | while node: 37 | stack.append(node) 38 | node = node.right 39 | node = stack.pop() 40 | curval += node.val 41 | node.val = curval 42 | node = node.left 43 | return root 44 | ``` 45 | 46 | -------------------------------------------------------------------------------- /539. Minimum Time Difference.md: -------------------------------------------------------------------------------- 1 | # 539. Minimum Time Difference 2 | 3 | Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum **minutes** 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: ["23:59","00:00"] 9 | Output: 1 10 | ``` 11 | 12 | 13 | 14 | **Note:** 15 | 16 | 1. The number of time points in the given list is at least 2 and won't exceed 20000. 17 | 2. The input time is legal and ranges from 00:00 to 23:59. 18 | 19 | 20 | 21 | ## Code 22 | 23 | ```python 24 | class Solution(object): 25 | def findMinDifference(self, timePoints): 26 | """ 27 | :type timePoints: List[str] 28 | :rtype: int 29 | """ 30 | length = len(timePoints) 31 | time = [0 for _ in range(length)] 32 | for i,t in enumerate(timePoints): 33 | time[i] = int(t[:2])*60 + int(t[3:]) 34 | 35 | time.sort() 36 | # print(time) 37 | mindiff = float('inf') 38 | for i in range(length): 39 | if i < length-1: 40 | mindiff = min(mindiff,time[i+1]-time[i]) 41 | else: 42 | mindiff = min(mindiff,time[0]-time[i]+24*60) 43 | return mindiff 44 | ``` 45 | 46 | -------------------------------------------------------------------------------- /540. Single Element in a Sorted Array.md: -------------------------------------------------------------------------------- 1 | # 540. Single Element in a Sorted Array 2 | 3 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. 4 | 5 | 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: [1,1,2,3,3,4,4,8,8] 11 | Output: 2 12 | ``` 13 | 14 | **Example 2:** 15 | 16 | ``` 17 | Input: [3,3,7,7,10,11,11] 18 | Output: 10 19 | ``` 20 | 21 | 22 | 23 | **Note:** Your solution should run in O(log n) time and O(1) space. 24 | 25 | 26 | 27 | ## Code 28 | 29 | ```python 30 | class Solution(object): 31 | def singleNonDuplicate(self, nums): 32 | """ 33 | :type nums: List[int] 34 | :rtype: int 35 | """ 36 | length = len(nums) 37 | if length == 1: 38 | return nums[0] 39 | if nums[-2]!=nums[-1]: 40 | return nums[-1] 41 | pairs = length // 2 42 | st = 0 43 | ed = pairs-1 44 | while st < ed: 45 | sted = (st+ed)//2 46 | mid = sted*2 47 | if nums[mid] == nums[mid+1]: 48 | st = mid//2 + 1 49 | elif nums[mid] != nums[mid+1]: 50 | ed = mid//2 51 | return nums[st*2] 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /541. Reverse String II.md: -------------------------------------------------------------------------------- 1 | # 541. Reverse String II 2 | 3 | Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. 4 | 5 | 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: s = "abcdefg", k = 2 11 | Output: "bacdfeg" 12 | ``` 13 | 14 | 15 | 16 | **Restrictions:** 17 | 18 | 19 | 20 | ## Code 21 | 22 | ```python 23 | class Solution(object): 24 | def reverseStr(self, s, k): 25 | """ 26 | :type s: str 27 | :type k: int 28 | :rtype: str 29 | """ 30 | def swap(nums,i,j): 31 | nums[i], nums[j] = nums[j], nums[i] 32 | 33 | def reverse(nums,st,ed): 34 | while st < ed: 35 | swap(nums,st,ed) 36 | st += 1 37 | ed -= 1 38 | 39 | length = len(s) 40 | chrs = [ch for ch in s] 41 | st = 0 42 | while st < length: 43 | ed = min(length, st + k) 44 | chrs[st:ed] = reversed(chrs[st:ed]) 45 | st += 2*k 46 | 47 | return "".join(chrs) 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /55. Jump Game.md: -------------------------------------------------------------------------------- 1 | # 55. Jump Game 2 | 3 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | 5 | Each element in the array represents your maximum jump length at that position. 6 | 7 | Determine if you are able to reach the last index. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: [2,3,1,1,4] 13 | Output: true 14 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 15 | ``` 16 | 17 | **Example 2:** 18 | 19 | ``` 20 | Input: [3,2,1,0,4] 21 | Output: false 22 | Explanation: You will always arrive at index 3 no matter what. Its maximum 23 | jump length is 0, which makes it impossible to reach the last index. 24 | ``` 25 | 26 | 27 | 28 | ## Solution 29 | 30 | 和上一个jump game类似,增加一个判断,如果当前last_max_dist已经可以到达最后一个index的话,就返回True。 31 | 32 | 返回False的原因是还未抵达最后的index,并且无法再往前了。(last_max_dist == cur_max_dist)。 33 | 34 | 35 | 36 | ## Code 37 | 38 | ```python 39 | class Solution: 40 | def canJump(self, nums): 41 | """ 42 | :type nums: List[int] 43 | :rtype: bool 44 | """ 45 | if len(nums)<=1: 46 | return True 47 | 48 | last_max_dist = 0 49 | cur_max_dist = 0 50 | for i, c in enumerate(nums): 51 | cur_max_dist = max(cur_max_dist, i + c) 52 | if cur_max_dist >= len(nums)-1: 53 | return True 54 | if i == last_max_dist: 55 | if last_max_dist == cur_max_dist: 56 | return False 57 | last_max_dist = cur_max_dist 58 | return True 59 | ``` 60 | 61 | -------------------------------------------------------------------------------- /557. Reverse Words in a String III.md: -------------------------------------------------------------------------------- 1 | # 557. Reverse Words in a String III 2 | 3 | Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: "Let's take LeetCode contest" 9 | Output: "s'teL ekat edoCteeL tsetnoc" 10 | ``` 11 | 12 | 13 | 14 | **Note:** In the string, each word is separated by single space and there will not be any extra space in the string. 15 | 16 | 17 | 18 | ## Code 19 | 20 | ```python 21 | class Solution(object): 22 | def reverseWords(self, s): 23 | """ 24 | :type s: str 25 | :rtype: str 26 | """ 27 | words = s.split() 28 | return " ".join(word[::-1] for word in words) 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /560. Subarray Sum Equals K.md: -------------------------------------------------------------------------------- 1 | # 560. Subarray Sum Equals K 2 | 3 | Given an array of integers and an integer **k**, you need to find the total number of continuous subarrays whose sum equals to **k**. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input:nums = [1,1,1], k = 2 9 | Output: 2 10 | ``` 11 | 12 | 13 | 14 | **Note:** 15 | 16 | 1. The length of the array is in range [1, 20,000]. 17 | 2. The range of numbers in the array is [-1000, 1000] and the range of the integer **k** is [-1e7, 1e7]. 18 | 19 | 20 | 21 | ## Solution 22 | 23 | [绝了我靠](https://leetcode.com/problems/subarray-sum-equals-k/discuss/102111/Python-Simple-with-Explanation) 24 | 25 | 26 | 27 | ## Code 28 | 29 | ```python 30 | class Solution(object): 31 | def subarraySum(self, nums, k): 32 | """ 33 | :type nums: List[int] 34 | :type k: int 35 | :rtype: int 36 | """ 37 | count = {} 38 | cursum = 0 39 | res = 0 40 | count[0] = 1 41 | for num in nums: 42 | cursum += num 43 | if cursum - k in count: 44 | res += count[cursum-k] 45 | count[cursum] = count.get(cursum,0)+1 46 | return res 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /59. Spiral Matrix II.md: -------------------------------------------------------------------------------- 1 | # 59. Spiral Matrix II 2 | 3 | Given a positive integer *n*, generate a square matrix filled with elements from 1 to *n*2 in spiral order. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: 3 9 | Output: 10 | [ 11 | [ 1, 2, 3 ], 12 | [ 8, 9, 4 ], 13 | [ 7, 6, 5 ] 14 | ] 15 | ``` 16 | 17 | ## Solution 18 | 19 | 硬推公式算的。。。差点忘记等比数列求和怎么算orz 20 | 21 | ## Code 22 | 23 | ```python 24 | class Solution: 25 | def generateMatrix(self, n): 26 | """ 27 | :type n: int 28 | :rtype: List[List[int]] 29 | """ 30 | st_num = 1 31 | ite_time = (n + 1)//2 32 | result = [] 33 | if n == 0: 34 | return result 35 | for i in range(n): 36 | result.append([0 for k in range(n)]) 37 | for i in range(ite_time): 38 | st = i 39 | ed = n - i - 1 40 | if st == ed: 41 | result[st][st] = n*n 42 | else: 43 | result[st][st:ed] = range(st_num, st_num+(n-2*i-1)) 44 | for k in range(st, ed): 45 | result[k][ed] = st_num+(n-1-2*i)-st+k 46 | 47 | result[ed][ed:st:-1] = range(st_num+2*(n-2*i-1), st_num+3*(n-2*i-1)) 48 | for k in range(ed, st, -1): 49 | result[k][st] = st_num+3*(n-1-2*i)-k+ed 50 | st_num = st_num + 4*(n-2*i-1) 51 | return result 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /6. ZigZag Conversion.md: -------------------------------------------------------------------------------- 1 | ## 6. ZigZag Conversion 2 | 3 | The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 4 | 5 | ``` 6 | P A H N 7 | A P L S I I G 8 | Y I R 9 | ``` 10 | 11 | And then read line by line: `"PAHNAPLSIIGYIR"` 12 | 13 | Write the code that will take a string and make this conversion given a number of rows: 14 | 15 | ``` 16 | string convert(string s, int numRows); 17 | ``` 18 | 19 | **Example 1:** 20 | 21 | ``` 22 | Input: s = "PAYPALISHIRING", numRows = 3 23 | Output: "PAHNAPLSIIGYIR" 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: s = "PAYPALISHIRING", numRows = 4 30 | Output: "PINALSIGYAHRPI" 31 | Explanation: 32 | 33 | P I N 34 | A L S I G 35 | Y A H R 36 | P I 37 | ``` 38 | 39 | **TIPS: ** 40 | 41 | 一开始想的是用一个二维list,后来想想很麻烦(初始化和修改操作都不熟orz)。中间的空格是没用的。所以直接append就好了!机智! 42 | 43 | 44 | 45 | **CODE:** 46 | 47 | ```python 48 | class Solution: 49 | def convert(self, s, numRows): 50 | """ 51 | :type s: str 52 | :type numRows: int 53 | :rtype: str 54 | """ 55 | if numRows == 1: 56 | return s 57 | L = [''] * numRows 58 | idx, step = 0, 1 59 | for x in s: 60 | L[idx] += (x) 61 | if idx == 0: 62 | step = 1 63 | elif idx == numRows - 1: 64 | step = -1 65 | idx += step 66 | return ''.join(L) 67 | ``` 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /64. Minimum Path Sum.md: -------------------------------------------------------------------------------- 1 | # 64. Minimum Path Sum 2 | 3 | Given a *m* x *n* grid filled with non-negative numbers, find a path from top left to bottom right which *minimizes* the sum of all numbers along its path. 4 | 5 | **Note:** You can only move either down or right at any point in time. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: 11 | [ 12 | [1,3,1], 13 | [1,5,1], 14 | [4,2,1] 15 | ] 16 | Output: 7 17 | Explanation: Because the path 1→3→1→1→1 minimizes the sum. 18 | ``` 19 | 20 | 21 | 22 | ## Code 23 | 24 | ```python 25 | class Solution: 26 | def minPathSum(self, grid): 27 | """ 28 | :type grid: List[List[int]] 29 | :rtype: int 30 | """ 31 | m = len(grid) 32 | n = len(grid[0]) 33 | table = grid[:][:] 34 | for i in range(0, m): 35 | for j in range(0, n): 36 | if i==0 and j==0: 37 | table[i][j] = grid[i][j] 38 | elif i==0: 39 | table[i][j] = grid[i][j] + table[i][j-1] 40 | elif j==0: 41 | table[i][j] = grid[i][j] + table[i-1][j] 42 | else: 43 | table[i][j] = grid[i][j] + min(table[i-1][j], table[i][j-1]) 44 | 45 | return table[-1][-1] 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /680. Valid Palindrome II.md: -------------------------------------------------------------------------------- 1 | # 680. Valid Palindrome II 2 | 3 | class Solution(object): 4 | def validPalindrome(self, s): 5 | """ 6 | :type s: str 7 | :rtype: bool 8 | """ 9 | def isPali(s): 10 | return s == s[::-1] 11 | 12 | 13 | if s == s[::-1]: 14 | return True 15 | st = 0 16 | ed = len(s)-1 17 | while st < ed: 18 | if s[st] == s[ed]: 19 | st += 1 20 | ed -= 1 21 | else: 22 | return isPali(s[st:ed]) or isPali(s[st+1:ed+1]) 23 | 24 | return True 25 | 26 | 27 | ## Code 28 | 29 | ```pythons 30 | class Solution(object): 31 | def validPalindrome(self, s): 32 | """ 33 | :type s: str 34 | :rtype: bool 35 | """ 36 | def isPali(s): 37 | return s == s[::-1] 38 | 39 | if s == s[::-1]: 40 | return True 41 | st = 0 42 | ed = len(s)-1 43 | while st < ed: 44 | if s[st] == s[ed]: 45 | st += 1 46 | ed -= 1 47 | else: 48 | return isPali(s[st:ed]) or isPali(s[st+1:ed+1]) 49 | 50 | return True 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /69. Sqrt(x).md: -------------------------------------------------------------------------------- 1 | # 69. Sqrt(x) 2 | 3 | Implement `int sqrt(int x)`. 4 | 5 | Compute and return the square root of *x*, where *x* is guaranteed to be a non-negative integer. 6 | 7 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: 4 13 | Output: 2 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: 8 20 | Output: 2 21 | Explanation: The square root of 8 is 2.82842..., and since 22 | the decimal part is truncated, 2 is returned. 23 | ``` 24 | 25 | ## Code 26 | 27 | ```python 28 | class Solution: 29 | def mySqrt(self, x): 30 | """ 31 | :type x: int 32 | :rtype: int 33 | """ 34 | if x == 1 or x == 0: 35 | return x 36 | st = 1 37 | ed = x//2 38 | while st < ed: 39 | cur = (st+ed+1)//2 40 | num1 = cur*cur 41 | num2 = (cur+1)*(cur+1) 42 | if num1 <= x and num2 > x: 43 | return cur 44 | elif num1 > x: 45 | ed = cur - 1 46 | elif num1 < x: 47 | st = cur + 1 48 | return st 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /7. Reverse Integer.md: -------------------------------------------------------------------------------- 1 | ## 7. Reverse Integer 2 | 3 | Given a 32-bit signed integer, reverse digits of an integer. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 123 9 | Output: 321 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: -123 16 | Output: -321 17 | ``` 18 | 19 | **Example 3:** 20 | 21 | ``` 22 | Input: 120 23 | Output: 21 24 | ``` 25 | 26 | **Note:** 27 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 28 | 29 | **TIPS:** 30 | 31 | 逆序遍历一个string可以用``str[::-1]``来实现 32 | 33 | **Code: ** 34 | 35 | ```python 36 | class Solution: 37 | def reverse(self, x): 38 | """ 39 | :type x: int 40 | :rtype: int 41 | """ 42 | x_str = str(x) 43 | result = '' 44 | flag = 1 45 | if x_str[0] == '-': 46 | flag = -1 47 | x_str = x_str[1:] 48 | 49 | for k in x_str[::-1]: 50 | result = result + k 51 | 52 | start_idx = 0 53 | for t in range(len(result)): 54 | if result[t] != '0': 55 | start_idx = t 56 | break 57 | 58 | result = int(result[start_idx:]) * flag 59 | if result < -pow(2,31) or result > pow(2,31)-1: 60 | return 0 61 | else: 62 | return result 63 | ``` 64 | 65 | -------------------------------------------------------------------------------- /703. Kth Largest Element in a Stream.md: -------------------------------------------------------------------------------- 1 | # \703. Kth Largest Element in a Stream 2 | 3 | Design a class to find the **k**th largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. 4 | 5 | Your `KthLargest` class will have a constructor which accepts an integer `k` and an integer array `nums`, which contains initial elements from the stream. For each call to the method `KthLargest.add`, return the element representing the kth largest element in the stream. 6 | 7 | **Example:** 8 | 9 | ``` 10 | int k = 3; 11 | int[] arr = [4,5,8,2]; 12 | KthLargest kthLargest = new KthLargest(3, arr); 13 | kthLargest.add(3); // returns 4 14 | kthLargest.add(5); // returns 5 15 | kthLargest.add(10); // returns 5 16 | kthLargest.add(9); // returns 8 17 | kthLargest.add(4); // returns 8 18 | ``` 19 | 20 | **Note:** 21 | You may assume that `nums`' length ≥ `k-1` and `k` ≥ 1. 22 | 23 | 24 | 25 | ## Code 26 | 27 | ```python 28 | class KthLargest(object): 29 | 30 | def __init__(self, k, nums): 31 | """ 32 | :type k: int 33 | :type nums: List[int] 34 | """ 35 | self.k = k 36 | self.h = nums 37 | heapq.heapify(self.h) 38 | while len(self.h) > k: 39 | heapq.heappop(self.h) 40 | 41 | 42 | def add(self, val): 43 | """ 44 | :type val: int 45 | :rtype: int 46 | """ 47 | if len(self.h) < self.k: 48 | heapq.heappush(self.h, val) 49 | elif val > self.h[0]: 50 | heapq.heappushpop(self.h, val) 51 | return self.h[0] 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /77. Combinations_.md: -------------------------------------------------------------------------------- 1 | # 77. Combinations 2 | 3 | Given two integers *n* and *k*, return all possible combinations of *k* numbers out of 1 ... *n*. 4 | 5 | **Example:** 6 | 7 | ``` 8 | Input: n = 4, k = 2 9 | Output: 10 | [ 11 | [2,4], 12 | [3,4], 13 | [2,3], 14 | [1,2], 15 | [1,3], 16 | [1,4], 17 | ] 18 | ``` 19 | 20 | 21 | 22 | ## Code2-Java 23 | 24 | ```java 25 | class Solution { 26 | private void helper(int st, int ed, List path, List> res, int k) 27 | { 28 | if(k==0) 29 | { 30 | // 这里为啥不能直接res.add(path),而需要res.add(new ArrayList(path))呢? 31 | // res.add(path); 32 | res.add(new ArrayList(path)); 33 | return; 34 | } 35 | 36 | for(int i = st; i<=ed; i++) 37 | { 38 | path.add(i); 39 | helper(i+1, ed, path, res,k-1); 40 | path.remove(path.size()-1); 41 | } 42 | } 43 | public List> combine(int n, int k) { 44 | List> res = new ArrayList(); 45 | List path = new ArrayList(); 46 | int st = 1; 47 | int ed = n; 48 | helper(st, ed, path, res, k); 49 | return res; 50 | } 51 | } 52 | ``` 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /78. Subsets.md: -------------------------------------------------------------------------------- 1 | # 78. Subsets 2 | 3 | Given a set of **distinct** integers, *nums*, return all possible subsets (the power set). 4 | 5 | **Note:** The solution set must not contain duplicate subsets. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: nums = [1,2,3] 11 | Output: 12 | [ 13 | [3], 14 | [1], 15 | [2], 16 | [1,2,3], 17 | [1,3], 18 | [2,3], 19 | [1,2], 20 | [] 21 | ] 22 | ``` 23 | 24 | 25 | 26 | ## Solution 27 | 28 | 无脑递归>< 29 | 30 | 31 | 32 | ## Code 33 | 34 | ```python 35 | class Solution: 36 | def subsets(self, nums): 37 | """ 38 | :type nums: List[int] 39 | :rtype: List[List[int]] 40 | """ 41 | result = [] 42 | if len(nums) == 0: 43 | return result 44 | if len(nums) == 1: 45 | return [nums, []] 46 | 47 | c = nums[0] 48 | for ch in self.subsets(nums[1:]): 49 | # if not result.__contains__([c]+ch): 50 | result.append([c]+ch) 51 | # if not result.__contains__(ch): 52 | result.append(ch) 53 | return result 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /783. Minimum Distance Between BST Nodes.md: -------------------------------------------------------------------------------- 1 | # \783. Minimum Distance Between BST Nodes 2 | 3 | Given a Binary Search Tree (BST) with the root node `root`, return the minimum difference between the values of any two different nodes in the tree. 4 | 5 | **Example :** 6 | 7 | ``` 8 | Input: root = [4,2,6,1,3,null,null] 9 | Output: 1 10 | Explanation: 11 | Note that root is a TreeNode object, not an array. 12 | 13 | The given tree [4,2,6,1,3,null,null] is represented by the following diagram: 14 | 15 | 4 16 | / \ 17 | 2 6 18 | / \ 19 | 1 3 20 | 21 | while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2. 22 | ``` 23 | 24 | **Note:** 25 | 26 | 1. The size of the BST will be between 2 and `100`. 27 | 2. The BST is always valid, each node's value is an integer, and each node's value is different. 28 | 29 | 30 | 31 | ## Code 32 | 33 | ```python 34 | class Solution(object): 35 | def minDiffInBST(self, root): 36 | """ 37 | :type root: TreeNode 38 | :rtype: int 39 | """ 40 | stack = [] 41 | node = root 42 | pre = None 43 | mindiff = float('inf') 44 | while node or stack: 45 | while node: 46 | stack.append(node) 47 | node = node.left 48 | node = stack.pop() 49 | if pre is not None: 50 | mindiff = min(mindiff, node.val-pre) 51 | pre = node.val 52 | node = node.right 53 | return mindiff 54 | ``` 55 | 56 | -------------------------------------------------------------------------------- /82. Remove Duplicates from Sorted List II.md: -------------------------------------------------------------------------------- 1 | # 82. Remove Duplicates from Sorted List II 2 | 3 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only *distinct* numbers from the original list. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 1->2->3->3->4->4->5 9 | Output: 1->2->5 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: 1->1->1->2->3 16 | Output: 2->3 17 | ``` 18 | 19 | 20 | 21 | ## Code 22 | 23 | ```python 24 | # Definition for singly-linked list. 25 | # class ListNode: 26 | # def __init__(self, x): 27 | # self.val = x 28 | # self.next = None 29 | 30 | class Solution: 31 | def deleteDuplicates(self, head): 32 | """ 33 | :type head: ListNode 34 | :rtype: ListNode 35 | """ 36 | dummy = ListNode(0) 37 | dummy.next = head 38 | first = dummy 39 | second = dummy.next 40 | if second is not None and second.next is not None: 41 | third = second.next 42 | else: 43 | return dummy.next 44 | while third: 45 | if second.val == third.val: 46 | while third and second.val == third.val: 47 | third = third.next 48 | first.next = third 49 | second = third 50 | if third is not None: 51 | third = third.next 52 | else: 53 | first = second 54 | second = third 55 | third = third.next 56 | return dummy.next 57 | 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /83. Remove Duplicates from Sorted List.md: -------------------------------------------------------------------------------- 1 | # 83. Remove Duplicates from Sorted List 2 | 3 | Given a sorted linked list, delete all duplicates such that each element appear only *once*. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 1->1->2 9 | Output: 1->2 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: 1->1->2->3->3 16 | Output: 1->2->3 17 | ``` 18 | 19 | 20 | 21 | # Code 22 | 23 | ```python 24 | # Definition for singly-linked list. 25 | # class ListNode: 26 | # def __init__(self, x): 27 | # self.val = x 28 | # self.next = None 29 | 30 | class Solution: 31 | def deleteDuplicates(self, head): 32 | """ 33 | :type head: ListNode 34 | :rtype: ListNode 35 | """ 36 | dummy = ListNode(0) 37 | dummy.next = head 38 | if head is None or head.next is None: 39 | return dummy.next 40 | first = dummy.next 41 | second = first.next 42 | while second is not None: 43 | if second.val == first.val: 44 | while second is not None and second.val == first.val: 45 | second = second.next 46 | first.next = second 47 | 48 | if second is not None: 49 | first = second 50 | second = second.next 51 | return dummy.next 52 | ``` 53 | 54 | -------------------------------------------------------------------------------- /86. Partition List.md: -------------------------------------------------------------------------------- 1 | # 86. Partition List 2 | 3 | Given a linked list and a value *x*, partition it such that all nodes less than *x* come before nodes greater than or equal to *x*. 4 | 5 | You should preserve the original relative order of the nodes in each of the two partitions. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: head = 1->4->3->2->5->2, x = 3 11 | Output: 1->2->2->4->3->5 12 | ``` 13 | 14 | 15 | 16 | ## Solution 17 | 18 | 分成small_list和large_list逐个加进去就行。最后把small_list_tail.next = large_list.head,然后记得large_list_tail.next = None. 19 | 20 | 21 | 22 | ## Code 23 | 24 | ```python 25 | # Definition for singly-linked list. 26 | # class ListNode: 27 | # def __init__(self, x): 28 | # self.val = x 29 | # self.next = None 30 | 31 | class Solution: 32 | def partition(self, head, x): 33 | """ 34 | :type head: ListNode 35 | :type x: int 36 | :rtype: ListNode 37 | """ 38 | s_dummy = ListNode(0) 39 | l_dummy = ListNode(0) 40 | dummy = ListNode(0) 41 | dummy.next = head 42 | cur = head 43 | s_cur = s_dummy 44 | l_cur = l_dummy 45 | 46 | if head is None or head.next is None: 47 | return head 48 | while cur is not None: 49 | if cur.val < x: 50 | s_cur.next = cur 51 | s_cur = s_cur.next 52 | else: 53 | l_cur.next = cur 54 | l_cur = l_cur.next 55 | cur = cur.next 56 | 57 | s_cur.next = l_dummy.next 58 | l_cur.next = None 59 | return s_dummy.next 60 | ``` 61 | 62 | -------------------------------------------------------------------------------- /88. Merge Sorted Array.md: -------------------------------------------------------------------------------- 1 | # 88. Merge Sorted Array 2 | 3 | Given two sorted integer arrays *nums1* and *nums2*, merge *nums2* into *nums1* as one sorted array. 4 | 5 | **Note:** 6 | 7 | - The number of elements initialized in *nums1* and *nums2* are *m* and *n* respectively. 8 | - You may assume that *nums1* has enough space (size that is greater or equal to *m* + *n*) to hold additional elements from *nums2*. 9 | 10 | **Example:** 11 | 12 | ``` 13 | Input: 14 | nums1 = [1,2,3,0,0,0], m = 3 15 | nums2 = [2,5,6], n = 3 16 | 17 | Output: [1,2,2,3,5,6] 18 | ``` 19 | 20 | 21 | 22 | ## Code 23 | 24 | ```python 25 | class Solution: 26 | def merge(self, nums1, m, nums2, n): 27 | """ 28 | :type nums1: List[int] 29 | :type m: int 30 | :type nums2: List[int] 31 | :type n: int 32 | :rtype: void Do not return anything, modify nums1 in-place instead. 33 | """ 34 | head1, head2 = 0, 0 35 | while head2 < n and head1 < head2 + m: 36 | if nums1[head1] <= nums2[head2]: 37 | head1 += 1 38 | else: 39 | nums1[head1+1:m+head2+1] = nums1[head1:m+head2] 40 | nums1[head1] = nums2[head2] 41 | head2 += 1 42 | head1 += 1 43 | while head2 < n: 44 | nums1[head1] = nums2[head2] 45 | head2 += 1 46 | head1 += 1 47 | ``` 48 | 49 | -------------------------------------------------------------------------------- /89. Gray Code.md: -------------------------------------------------------------------------------- 1 | # 89. Gray Code 2 | 3 | The gray code is a binary numeral system where two successive values differ in only one bit. 4 | 5 | Given a non-negative integer *n* representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 6 | 7 | **Example 1:** 8 | 9 | ``` 10 | Input: 2 11 | Output: [0,1,3,2] 12 | Explanation: 13 | 00 - 0 14 | 01 - 1 15 | 11 - 3 16 | 10 - 2 17 | 18 | For a given n, a gray code sequence may not be uniquely defined. 19 | For example, [0,2,3,1] is also a valid gray code sequence. 20 | 21 | 00 - 0 22 | 10 - 2 23 | 11 - 3 24 | 01 - 1 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: 0 31 | Output: [0] 32 | Explanation: We define the gray code sequence to begin with 0. 33 | A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1. 34 | Therefore, for n = 0 the gray code sequence is [0]. 35 | ``` 36 | 37 | 38 | 39 | ## Solution 40 | 41 | 要学会机智地找规律 42 | 43 | 44 | 45 | ## Code 46 | 47 | ```python 48 | class Solution: 49 | def grayCode(self, n): 50 | """ 51 | :type n: int 52 | :rtype: List[int] 53 | """ 54 | result = [0] 55 | for i in range(n): 56 | result += [ x + pow(2, i) for x in reversed(result)] 57 | return result 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /896. Monotonic Array.md: -------------------------------------------------------------------------------- 1 | # 896. Monotonic Array 2 | 3 | An array is *monotonic* if it is either monotone increasing or monotone decreasing. 4 | 5 | An array `A` is monotone increasing if for all `i <= j`, `A[i] <= A[j]`. An array `A` is monotone decreasing if for all `i <= j`, `A[i] >= A[j]`. 6 | 7 | Return `true` if and only if the given array `A` is monotonic. 8 | 9 | 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: [1,2,2,3] 17 | Output: true 18 | ``` 19 | 20 | **Example 2:** 21 | 22 | ``` 23 | Input: [6,5,4,4] 24 | Output: true 25 | ``` 26 | 27 | **Example 3:** 28 | 29 | ``` 30 | Input: [1,3,2] 31 | Output: false 32 | ``` 33 | 34 | **Example 4:** 35 | 36 | ``` 37 | Input: [1,2,4,5] 38 | Output: true 39 | ``` 40 | 41 | **Example 5:** 42 | 43 | ``` 44 | Input: [1,1,1] 45 | Output: true 46 | ``` 47 | 48 | 49 | 50 | **Note:** 51 | 52 | 1. `1 <= A.length <= 50000` 53 | 2. `-100000 <= A[i] <= 100000` 54 | 55 | 56 | 57 | ## Code 58 | 59 | ```python 60 | class Solution(object): 61 | def isMonotonic(self, A): 62 | """ 63 | :type A: List[int] 64 | :rtype: bool 65 | """ 66 | flag = 0 67 | length = len(A) 68 | if length <= 2: 69 | return True 70 | for i in range(1,length): 71 | if A[i]==A[i-1]: 72 | continue 73 | elif A[i] < A[i-1]: 74 | if flag == 1: 75 | return False 76 | flag = -1 77 | else: 78 | if flag == -1: 79 | return False 80 | flag = 1 81 | return True 82 | ``` 83 | 84 | -------------------------------------------------------------------------------- /9. Palindrome Number.md: -------------------------------------------------------------------------------- 1 | # 9. Palindrome Number 2 | 3 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 121 9 | Output: true 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: -121 16 | Output: false 17 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 18 | ``` 19 | 20 | **Example 3:** 21 | 22 | ``` 23 | Input: 10 24 | Output: false 25 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 26 | ``` 27 | 28 | **Follow up:** 29 | 30 | Coud you solve it without converting the integer to a string? 31 | 32 | 33 | 34 | ## Solution: 35 | 36 | 如果可以转成string的话就两行: 37 | 38 | ```python 39 | num = str(x) 40 | return num == num[::-1] 41 | ``` 42 | 43 | 44 | 45 | 不转的话见Code。生成一个把X倒过来的y,比较两者是否相等即可。 46 | 47 | `` if x % 10 == 0: return False`` 加上这步可以很大加速。因为是0结尾的话,0没法开头。 48 | 49 | ## Code 50 | 51 | ```python 52 | class Solution: 53 | def isPalindrome(self, x): 54 | """ 55 | :type x: int 56 | :rtype: bool 57 | """ 58 | if 0 <= x <= 9: 59 | return True 60 | 61 | if x < 0 or x % 10 == 0: 62 | return False 63 | 64 | 65 | y = 0 66 | tmp = x 67 | while tmp > 0: 68 | y = y * 10 + tmp % 10 69 | tmp = tmp // 10 70 | 71 | if y == x: 72 | return True 73 | else: 74 | return False 75 | ``` 76 | 77 | -------------------------------------------------------------------------------- /90. Subsets II.md: -------------------------------------------------------------------------------- 1 | # 90. Subsets II 2 | 3 | Given a collection of integers that might contain duplicates, **nums**, return all possible subsets (the power set). 4 | 5 | **Note:** The solution set must not contain duplicate subsets. 6 | 7 | **Example:** 8 | 9 | ``` 10 | Input: [1,2,2] 11 | Output: 12 | [ 13 | [2], 14 | [1], 15 | [1,2,2], 16 | [2,2], 17 | [1,2], 18 | [] 19 | ] 20 | ``` 21 | 22 | 23 | 24 | ## Solution 25 | 26 | 和78. subsets差不多, 加了排序和判断是否已经存在的条件。 27 | 28 | 29 | 30 | ## Code 31 | 32 | ```python 33 | class Solution: 34 | def subsetsWithDup(self, nums): 35 | """ 36 | :type nums: List[int] 37 | :rtype: List[List[int]] 38 | """ 39 | nums.sort() 40 | result = [] 41 | if len(nums) == 0: 42 | return result 43 | if len(nums) == 1: 44 | return [nums, []] 45 | 46 | # for i, c in enumerate(nums): 47 | c = nums[0] 48 | for ch in self.subsetsWithDup(nums[1:]): 49 | if not result.__contains__([c]+ch): 50 | result.append([c]+ch) 51 | if not result.__contains__(ch): 52 | result.append(ch) 53 | return result 54 | 55 | ``` 56 | 57 | -------------------------------------------------------------------------------- /939. Minimum Area Rectangle.md: -------------------------------------------------------------------------------- 1 | # 939. Minimum Area Rectangle 2 | 3 | Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes. 4 | 5 | If there isn't any rectangle, return 0. 6 | 7 | 8 | 9 | **Example 1:** 10 | 11 | ``` 12 | Input: [[1,1],[1,3],[3,1],[3,3],[2,2]] 13 | Output: 4 14 | ``` 15 | 16 | **Example 2:** 17 | 18 | ``` 19 | Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]] 20 | Output: 2 21 | ``` 22 | 23 | 24 | 25 | **Note**: 26 | 27 | 1. `1 <= points.length <= 500` 28 | 2. `0 <= points[i][0] <= 40000` 29 | 3. `0 <= points[i][1] <= 40000` 30 | 4. All points are distinct. 31 | 32 | 33 | 34 | ## Code 35 | 36 | ```python 37 | class Solution(object): 38 | def minAreaRect(self, points): 39 | """ 40 | :type points: List[List[int]] 41 | :rtype: int 42 | """ 43 | map = {} 44 | 45 | for x,y in points: 46 | if x in map: 47 | map[x].append(y) 48 | else: 49 | map[x] = [y] 50 | length = len(points) 51 | minsize = float('inf') 52 | for idx1 in range(length): 53 | for idx2 in range(idx1+1,length): 54 | x1, y1 = points[idx1] 55 | x2, y2 = points[idx2] 56 | if x1==x2 or y1==y2: 57 | continue 58 | if y2 in map[x1] and y1 in map[x2]: 59 | minsize = min(minsize,abs(x1-x2)*abs(y1-y2)) 60 | return 0 if minsize==float('inf') else minsize 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /Amazon OA 2019 Find Pair With Max Appeal Sum.md: -------------------------------------------------------------------------------- 1 | # Amazon | OA 2019 | Find Pair With Max Appeal Sum 2 | 3 | Find pair with maximum Appeal value. 4 | 5 | 6 | 7 | Input: Array 8 | Output: index {i, j} ( i = j allowed) with maximum Appeal 9 | Appeal = A[i] +A[j] + abs(i-j) 10 | 11 | 12 | 13 | **Example 1:** 14 | 15 | 16 | 17 | ``` 18 | Input: [1, 3, -1] 19 | Output: [1, 1] 20 | Explanation: Appeal = A[1] + A[1] + abs(0) = 3 + 3 + 0 = 6 21 | ``` 22 | 23 | 24 | 25 | **Example 2:** 26 | 27 | 28 | 29 | ``` 30 | Input: [1, 6, 1, 1, 1, 1, 7] 31 | Output: [1, 6] 32 | Explanation 6 + 7 + abs(1 - 6) = 18 33 | ``` 34 | 35 | 36 | 37 | **Example 3:** 38 | 39 | 40 | 41 | ``` 42 | Input: [6, 2, 7, 4, 4, 1, 6] 43 | Output: [0, 6] 44 | Explanation: 6 + 6 + abs(0 - 6) = 18 45 | ``` 46 | 47 | 48 | 49 | ## Solution 50 | 51 | I think this is the easiest way 52 | A[i] +A[j] + abs(i-j) 53 | = A[i] +A[j] +(i-j) = (A[i]+i) + (A[j]-j) 54 | = A[i] +A[j] - (i-j) = (A[i]-i) + (A[j]+j) 55 | Since we are allowed to have same i=j, so just find the max value of each (A[i]-i), (A[i]+i). 56 | 57 | 58 | 59 | ## Code 60 | 61 | ```python 62 | def maxAppealPair(nums): 63 | max1 = float('-inf') 64 | max2 = float('-inf') 65 | idx1 = 0 66 | idx2 = 0 67 | for i, num in enumerate(nums): 68 | if num - i > max2: 69 | max2 = num - i 70 | idx2 = i 71 | if num + i > max1: 72 | max1 = num + i 73 | idx1 = i 74 | return [idx1, idx2] 75 | 76 | nums = [6, 2, 7, 4, 4, 1, 6] 77 | print(maxAppealPair(nums)) 78 | ``` 79 | 80 | -------------------------------------------------------------------------------- /Amazon OA 2019 Substrings with exactly K distinct chars.md: -------------------------------------------------------------------------------- 1 | # Amazon | OA 2019 | Substrings with exactly K distinct chars 2 | 3 | Given a string `s` and an int `k`, return an int representing the number of substrings (not unique) of `s` with exactly `k` distinct characters. If the given string doesn't have `k` distinct characters, return 0. 4 | https://leetcode.com/problems/subarrays-with-k-different-integers 5 | 6 | 7 | 8 | **Example 1:** 9 | 10 | 11 | 12 | ``` 13 | Input: s = "pqpqs", k = 2 14 | Output: 7 15 | Explanation: ["pq", "pqp", "pqpq", "qp", "qpq", "pq", "qs"] 16 | ``` 17 | 18 | 19 | 20 | **Example 2:** 21 | 22 | 23 | 24 | ``` 25 | Input: s = "aabab", k = 3 26 | Output: 0 27 | ``` 28 | 29 | 30 | 31 | Constraints: 32 | 33 | 34 | 35 | - The input string consists of only lowercase English letters `[a-z]` 36 | - 0 ≤ `k` ≤ 26 37 | 38 | 39 | 40 | ## Solution 41 | 42 | 要计数就没法用两个指针的方法啦。brute force就可。 43 | 44 | 以及record可以换成长度为26的list,也很快。 45 | 46 | 47 | 48 | ## Code 49 | 50 | ```python 51 | def subarrays(s, k): 52 | res = 0 53 | length = len(s) 54 | for st in range(length): 55 | count = 0 56 | record = {} 57 | for ed in range(st, length): 58 | char = s[ed] 59 | record[char] = record.get(char, 0) + 1 60 | if record[char] == 1: 61 | count += 1 62 | if count == k: 63 | res += 1 64 | elif count > k: 65 | break 66 | 67 | return res 68 | 69 | s = "aabab" 70 | k = 3 71 | print(subarrays(s, k)) 72 | ``` 73 | 74 | -------------------------------------------------------------------------------- /Amazon Deside Up or Down.md: -------------------------------------------------------------------------------- 1 | Coding: 一个数字stream,如果有增减趋势的变化就加一个UP或者DOWN,挺简单的,e.g. input 1 10 23 18 15 20,output 1 10 23 DOWN 18 15 UP 20(LZ是菜鸡本鸡,基本上我说简单就是真的简单hh) 2 | 3 | [https://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=561888&extra=page%3D4%26filter%3Dsortid%26sortid%3D311%26searchoption%5B3046%5D%5Bvalue%5D%3D5%26searchoption%5B3046%5D%5Btype%5D%3Dradio%26sortid%3D311%26orderby%3Ddateline](https://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=561888&extra=page%3D4%26filter%3Dsortid%26sortid%3D311%26searchoption[3046][value]%3D5%26searchoption[3046][type]%3Dradio%26sortid%3D311%26orderby%3Ddateline) 4 | 5 | 6 | 7 | ## Code 8 | 9 | ```python 10 | 11 | # Amazon full-time round 2 12 | # 1 10 23 DOWN 18 15 UP 20 13 | nums = [1,10,23,18,15,20] 14 | length = len(nums) 15 | if length <= 2: 16 | print(nums) 17 | else: 18 | first = 0 19 | second = 1 20 | third = 2 21 | res = nums[0:2] 22 | while third < length: 23 | if nums[first] < nums[second] and nums[second] > nums[third]: 24 | res.append('DOWN') 25 | elif nums[first] > nums[second] and nums[second] < nums[third]: 26 | res.append('UP') 27 | 28 | res.append(nums[third]) 29 | first += 1 30 | second += 1 31 | third += 1 32 | print(res) 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /Amazon Find Median from Data Stream.md: -------------------------------------------------------------------------------- 1 | # Amazon Find Median from Data Stream 2 | 3 | [Amazon](http://www.amazon.com/b?_encoding=UTF8&tag=1p3a-guanlian-20&linkCode=ur2&linkId=89c11e2c5b86155c5422f19cca1e9880&camp=1789&creative=9325&node=5) SDE intern 4 | 5 | 阿三给了道题求问正确解。网上都搜不到的题 6 | 7 | given streaming data, find the median in the top k largest elements. 8 | 9 | example: 10 | 11 | k = 3 [1] -> 1 12 | 13 | [1,2] -> 1.5 14 | 15 | [1,2,3] - > 2 16 | 17 | [1,2,3,1] -> 2 18 | 19 | [1,2,3,1,10] -> 3 20 | 21 | 22 | 23 | ## Code 24 | 25 | ```python 26 | from heapq import * 27 | class MedianFinder(object): 28 | 29 | def __init__(self): 30 | """ 31 | initialize your data structure here. 32 | """ 33 | self.maxheap = [] 34 | self.minheap = [] 35 | 36 | 37 | def addNum(self, num): 38 | """ 39 | :type num: int 40 | :rtype: None 41 | """ 42 | k = 3 43 | heappush(self.maxheap, num) 44 | heappush(self.minheap, -heappop(self.maxheap)) 45 | total_len = len(self.maxheap) + len(self.minheap) 46 | if total_len <= k and len(self.maxheap) < len(self.minheap): 47 | heappush(self.maxheap, -heappop(self.minheap)) 48 | 49 | 50 | def findMedian(self): 51 | """ 52 | :rtype: float 53 | """ 54 | k = 3 55 | length = len(self.maxheap) + len(self.minheap) 56 | true_length = min(length, k) 57 | if true_length % 2 == 0: 58 | return (self.maxheap[0] - self.minheap[0]) / 2.0 59 | else: 60 | return self.maxheap[0] 61 | ``` 62 | 63 | -------------------------------------------------------------------------------- /Amazon Word Break and Concatenated Words.md: -------------------------------------------------------------------------------- 1 | # Amazon Word Break and Concatenated Words 2 | 3 | 4 | 5 | 结合了 472. Concatenated Words 和 140. Word Break II 6 | 7 | ## Code 8 | 9 | ```python 10 | def wordBreak(words): 11 | """ 12 | :type s: str 13 | :type wordDict: List[str] 14 | :rtype: List[str] 15 | """ 16 | def helper(s, wordDict): 17 | if not s: 18 | return [] 19 | 20 | res = [] 21 | for word in wordDict: 22 | if s.startswith(word): 23 | if len(word) == len(s): 24 | res.append(word) 25 | else: 26 | res_left = helper(s[len(word):], wordDict) 27 | for item in res_left: 28 | item = word + " " + item 29 | res.append(item) 30 | return res 31 | 32 | res = [] 33 | record = {} 34 | words.sort(key=lambda x: len(x)) 35 | length = len(words) 36 | for i in range(length): 37 | curword = helper(words[i], words[:i]) 38 | if curword: 39 | for item in curword: 40 | res.append(item[:]) 41 | return res 42 | 43 | words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] 44 | print(wordBreak(words)) 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /ByteDance.md: -------------------------------------------------------------------------------- 1 | ```python 2 | #coding=utf-8 3 | # A B 4 | class TreeNode(object): 5 | def __init__(self, val): 6 | self.val = val 7 | self.left = None 8 | self.right = None 9 | 10 | def same_tree(A, B): 11 | if A is None and B is None: 12 | return True 13 | elif A is None or B is None: 14 | return False 15 | return A.val == B.val and same_tree(A.left, B.left) and same_tree(A.right, B.right) 16 | 17 | def A_subtree_of_B(A, B): 18 | if A is None and B is None: 19 | return True 20 | if A is None: 21 | return True 22 | if B is None: 23 | return False 24 | 25 | queue = [] 26 | queue.append(B) 27 | while queue: 28 | node = queue.pop(0) 29 | if same_tree(A, node): 30 | return True 31 | if node.left: 32 | queue.append(node.left) 33 | if node.right: 34 | queue.append(node.right) 35 | return False 36 | 37 | ``` 38 | 39 | 40 | 41 | ```python 42 | # n [2,3,6] 43 | # X2, +1 44 | # +1, X2, +1 45 | # X2, +1, X2, +1 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /ByteDance_Spider_Detector.md: -------------------------------------------------------------------------------- 1 | ```python 2 | #coding=utf-8 3 | class visit_history(object): 4 | def __init__(self): 5 | # key: ip 6 | # value: list[time] 7 | self.record = {} 8 | self.threshold = 1000 9 | self.time_diff = 30 10 | 11 | def find_valid_time(times, time_threshold): 12 | # binary search to find the first time 13 | length = len(times) 14 | if length == 0 or times[0] >= time_threshold: 15 | return 0 16 | st = 0 17 | ed = length-1 18 | while st < ed: 19 | mid = (st + ed) / 2 20 | if nums[mid] >= time_threshold: 21 | ed = mid 22 | else: 23 | st = mid + 1 24 | return st 25 | 26 | 27 | def server(ip): 28 | cur_time = get_time() 29 | if ip not in self.record: 30 | self.record[ip] = [cur_time] 31 | return False 32 | else: 33 | time_threshold = cur_time - self.time_diff 34 | start_index = find_valid_time(record[ip], time_threshold) 35 | record[ip] = record[ip][start_index:] 36 | record[ip].append(cur_time) 37 | length = len(record[ip]) 38 | if length > self.threshold: 39 | return True 40 | else: 41 | return False 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /Facebook Caesar Cipher Encrpytion.md: -------------------------------------------------------------------------------- 1 | # Caesar Cipher Encrpytion 2 | 3 | **Question 1:** 4 | Caesar Cipher Encrpytion 5 | You are given a list of string, group them if they are same after using Ceaser Cipher Encrpytion. 6 | Definition of "same", "abc" can right shift 1, get "bcd", here you can shift as many time as you want, the string will be considered as same. 7 | 8 | 9 | 10 | **Example:** 11 | 12 | 13 | 14 | ``` 15 | Input: ["abc", "bcd", "acd", "dfg"] 16 | Output: [["abc", "bcd"], ["acd", "dfg"]] 17 | ``` 18 | 19 | 20 | 21 | ## Code 22 | 23 | ```python 24 | # Caesar Cipher Encrpytion 25 | def CaesarEncrpytion(words): 26 | record = {} 27 | for word in words: 28 | length = len(word) 29 | keylist = [] 30 | for i in range(length): 31 | keylist.append(str(ord(word[i])-ord(word[0]))) 32 | key = "".join(keylist) 33 | if key in record: 34 | record[key].append(word) 35 | else: 36 | record[key] = [word] 37 | return record.values() 38 | 39 | words = ["abc", "bcd", "acd", "dfg"] 40 | print(CaesarEncrpytion(words)) 41 | ``` 42 | 43 | -------------------------------------------------------------------------------- /Facebook Phone Screen Redundant Paths.md: -------------------------------------------------------------------------------- 1 | # Facebook | Phone Screen | Redundant Paths 2 | 3 | **Question 1:** 4 | Given a list of directory info, return all paths which are not redundant. A redundant path is one with the root already on the list. 5 | 6 | 7 | 8 | Ex: Input: ["/a/b/c","/a/b","/d/e","/d"] 9 | Output: ["/a/b" , "/d"] 10 | 11 | 12 | 13 | Similar to: https://leetcode.com/problems/find-duplicate-file-in-system/ 14 | 15 | 16 | 17 | ## Code 18 | 19 | ```python 20 | # Facebook | Phone Screen | Redundant Paths 21 | # Facebook | Phone Screen | Redundant Paths 22 | def redundantpath(files): 23 | root = set() 24 | fileset = set(files) 25 | for file in files: 26 | idx = len(file) - file[::-1].index('/') - 1 27 | root.add(file[:idx]) 28 | 29 | res = [] 30 | for file in files: 31 | idx = len(file) - file[::-1].index('/') - 1 32 | if file[:idx] not in fileset: 33 | res.append(file) 34 | return res 35 | 36 | files = ["/a/b/c", "/a/b", "/d/e", "/d"] 37 | print(redundantpath(files)) 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /Google Interview Document.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhouzhiling/leetcode/69166c67b01249b464951d2d78b05db902cc3734/Google Interview Document.docx -------------------------------------------------------------------------------- /MemDev Find Perfect Substring.md: -------------------------------------------------------------------------------- 1 | # MemDev Find Perfect Substring 2 | 3 | ![](WeChat Image_20191027222101.jpg) 4 | 5 | ```python 6 | def find_perfect(s, k): 7 | def isPerfect(st, ed): 8 | flag = True 9 | for char in sset: 10 | occ = indexs[char][ed+1] - indexs[char][st] 11 | if occ != 0 and occ != k: 12 | flag = False 13 | break 14 | return flag 15 | 16 | sset = set(s) 17 | indexs = {} 18 | length = len(s) 19 | for char in sset: 20 | indexs[char] = [0 for _ in range(length+1)] 21 | for i, c in enumerate(s): 22 | for char in sset: 23 | indexs[char][i+1] = 1+indexs[char][i] if char == c else indexs[char][i] 24 | 25 | print(indexs) 26 | res = 0 27 | for st in range(length): 28 | for ed in range(st, length): 29 | if isPerfect(st, ed): 30 | res += 1 31 | return res 32 | 33 | s = "1221221121" 34 | print(find_perfect(s, 3)) 35 | ``` 36 | 37 | -------------------------------------------------------------------------------- /Minimum steps to reach target by a Knight.md: -------------------------------------------------------------------------------- 1 | # Minimum steps to reach target by a Knight 2 | 3 | Given a chess board with width n, calculate the minimal steps from [startX, startY] to [endX, endY]. 4 | 5 | A knight can only move like a L. 6 | 7 | 8 | 9 | ````python 10 | def minMoves(n, startX, startY, endX, endY): 11 | visited = set() 12 | queue = [] 13 | 14 | visited.add(str([startX, startY])) 15 | queue.append([startX, startY, 0]) 16 | moves = [[1,2], [1,-2], [-1, 2], [-1, -2], [2, 1], [-2, 1],[2, -1], [-2, -1]] 17 | while queue: 18 | centerX, centerY, step = queue.pop(0) 19 | if centerX==endX and centerY == endY: 20 | return step 21 | for move in moves: 22 | curX, curY = centerX + move[0], centerY + move[1] 23 | if curX >=0 and curX < n and curY >= 0 and curY < n: 24 | if str([curX, curY]) not in visited: 25 | queue.append([curX, curY, step+1]) 26 | visited.add(str([curX, curY])) 27 | 28 | return -1 29 | 30 | n = 9 31 | startX = 4 32 | startY = 4 33 | endX = 4 34 | endY = 5 35 | print(minMoves(n, startX, startY, endX, endY)) 36 | ```` 37 | 38 | -------------------------------------------------------------------------------- /Number of subarrays having sum exactly equal to k.md: -------------------------------------------------------------------------------- 1 | # Number of subarrays having sum exactly equal to k 2 | 3 | ``` 4 | Input : arr[] = {10, 2, -2, -20, 10}, 5 | k = -10 6 | Output : 3 7 | Subarrays: arr[0...3], arr[1...4], arr[3..4] 8 | have sum exactly equal to -10. 9 | 10 | Input : arr[] = {9, 4, 20, 3, 10, 5}, 11 | k = 33 12 | Output : 2 13 | Subarrays : arr[0...2], arr[2...4] have sum 14 | exactly equal to 33. 15 | ``` 16 | 17 | 18 | 19 | ## Code 20 | 21 | ```python 22 | class solution(object): 23 | def helper(self, nums, target, path): 24 | if target == 0: 25 | self.res.append(path[:]) 26 | return 27 | elif target < 0: 28 | return 29 | else: 30 | length = len(nums) 31 | for i in range(length): 32 | path.append(nums[i]) 33 | self.helper(nums[i+1:], target-nums[i], path) 34 | path.pop() 35 | 36 | def findElement(self, nums, target): 37 | self.res = [] 38 | self.helper(nums, target, []) 39 | return self.res 40 | 41 | ss = solution() 42 | # nums = [5,6,7,8,9,10,4,3,2,1] 43 | target = 33 44 | nums = [9, 4, 20, 3, 10, 5] 45 | print(ss.findElement(nums, target)) 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /Power of Three.md: -------------------------------------------------------------------------------- 1 | # Power of Three 2 | 3 | Given an integer, write a function to determine if it is a power of three. 4 | 5 | **Example 1:** 6 | 7 | ``` 8 | Input: 27 9 | Output: true 10 | ``` 11 | 12 | **Example 2:** 13 | 14 | ``` 15 | Input: 0 16 | Output: false 17 | ``` 18 | 19 | **Example 3:** 20 | 21 | ``` 22 | Input: 9 23 | Output: true 24 | ``` 25 | 26 | **Example 4:** 27 | 28 | ``` 29 | Input: 45 30 | Output: false 31 | ``` 32 | 33 | **Follow up:** 34 | Could you do it without using any loop / recursion? 35 | 36 | 37 | 38 | ## Code 39 | 40 | ```python 41 | class Solution(object): 42 | def isPowerOfThree(self, n): 43 | """ 44 | :type n: int 45 | :rtype: bool 46 | """ 47 | divisor = 3 48 | cur_divisor = 3 49 | while n >= divisor: 50 | cur_divisor *= divisor 51 | if n < cur_divisor: 52 | cur_divisor = divisor 53 | if n % cur_divisor != 0: 54 | return False 55 | n = n / cur_divisor 56 | return n == 1 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /Twittwe. OA.md: -------------------------------------------------------------------------------- 1 | ![1. partitioning array amay or to it i: to the of one N. to wing here ](file:///C:/Users/ZHILIN~1/AppData/Local/Temp/msohtmlclip1/01/clip_image001.png) 2 | 3 | ![· BuyingShOWTickets 000 ](file:///C:/Users/ZHILIN~1/AppData/Local/Temp/msohtmlclip1/01/clip_image001.png) 4 | 5 | ![3. Final Discounted price in Starting rings up its the is at j. 2.4 in W a may o' ](file:///C:/Users/ZHILIN~1/AppData/Local/Temp/msohtmlclip1/01/clip_image001.png) 6 | 7 | ![1570341775980](C:\Users\zhiling zhou\AppData\Roaming\Typora\typora-user-images\1570341775980.png) -------------------------------------------------------------------------------- /Uber Follow-up of 122. Best Time to Buy and Sell Stock II.md: -------------------------------------------------------------------------------- 1 | # [⭐] Uber Follow-up of 122. Best Time to Buy and Sell Stock II 2 | 3 | 122. Best Time to Buy and Sell Stock II 的变题。 4 | 5 | 第一題的followup: 假如改成一個2D array 每個row代表一個時間點, 每個column不同stock price。每次最多持有一支股票,求最大profit? 6 | 例如a[0][1] 就是第一天第二支stock的價格 7 | 8 | 9 | 10 | ## Solution 11 | 12 | 因为不限制购买次数,所以 13 | 14 | 15 | 16 | ## Code 17 | 18 | ```python 19 | # 122 follow up 20 | def maxProfit(prices): 21 | day_num = len(prices) 22 | stock_num = len(prices[0]) 23 | min_price = prices[0] 24 | res = 0 25 | for day in range(1, day_num): 26 | curmax = 0 27 | curidx = 0 28 | for i in range(stock_num): 29 | if prices[day][i] - min_price[i] > curmax: 30 | curmax = prices[day][i] - min_price[i] 31 | curidx = i 32 | print(curmax) 33 | res += curmax 34 | min_price = prices[day] 35 | return res 36 | 37 | prices = [[1,2,1,7],[2,2,4,6],[1,2,4,5],[4,2,4,4]] 38 | print(maxProfit(prices)) 39 | ``` 40 | 41 | -------------------------------------------------------------------------------- /Uber Segerate Odd and Even.md: -------------------------------------------------------------------------------- 1 | # Uber Segerate Odd and Even 2 | 3 | **Onsite round 1 (1 hour)** 4 | 5 | 6 | 7 | - question1: https://www.geeksforgeeks.org/segregate-even-and-odd-numbers/ 8 | - question 2: same as previous question while maintaining the same order. The interviewer expected an O(N) time and O(1) space solution. I couldn't code this. (Later I found out that it's impossible to do this. The interviewer had no idea though.) 9 | 10 | 11 | 12 | ```python 13 | 14 | # Uber segerate odd and even 15 | # Uber segerate odd and even 16 | 17 | def segerate(nums): 18 | head = 0 19 | length = len(nums) 20 | for i in range(length): 21 | if nums[i] % 2 == 0: 22 | idx = i 23 | while idx > head: 24 | nums[idx], nums[idx-1] = nums[idx-1], nums[idx] 25 | idx -= 1 26 | head += 1 27 | return nums 28 | 29 | nums = [12, 34, 45, 9, 8, 90, 3] 30 | print(segerate(nums)) 31 | ``` 32 | 33 | -------------------------------------------------------------------------------- /Uber Strange Pairs.md: -------------------------------------------------------------------------------- 1 | # Uber Strange Pairs 2 | 3 | given a list of points (x1, y1), (x2, y2), ... (xn, yn), return the biggest subset (a1, b1), (a2, b2), ... (am, bm) that meets the following condition: 4 | \1. a1 < a2 < ... < am 5 | \2. b1 > b2 > ... > bm 6 | 7 | For example: given (5, 6), (2, 8), (4, 1), (1, 9), (3, 7) return (1, 9), (2, 8), (3, 7), (5, 6) 8 | 9 | ## Solution 10 | 11 | 对初始的list进行排序之后,寻找第二列中的最大降序子列即可。 12 | 13 | 14 | 15 | ## Code 16 | 17 | ```python 18 | # UBER strange pairs sorting 19 | # UBER strange pairs sorting 20 | 21 | def sortPairs(pairs): 22 | pairs.sort() 23 | length = len(pairs) 24 | store = [[0, 0] for _ in range(length)] 25 | size = 0 26 | for i, pair in enumerate(pairs): 27 | num = pair[1] 28 | if size == 0 or num < store[size-1][0]: 29 | store[size] = [num, i] 30 | size += 1 31 | else: 32 | st = 0 33 | ed = size - 1 34 | while st < ed: 35 | mid = (st + ed + 1) // 2 36 | if store[mid][0] >= num: 37 | st = mid 38 | else: 39 | ed = mid - 1 40 | store[st] = [num, i] 41 | res = [] 42 | for i in range(size): 43 | res.append(pairs[store[i][1]]) 44 | return res 45 | 46 | pairs = [[5, 6], [5, 6], [2, 8], [4, 1], [1, 9], [3, 7]] 47 | print(sortPairs(pairs)) 48 | ``` 49 | 50 | -------------------------------------------------------------------------------- /Uber Valid Matrix.md: -------------------------------------------------------------------------------- 1 | # Valid Matrix 2 | 3 | 给一个M x N的整数矩阵,判断这个矩阵的所有元素都符合以下特点: 4 | 5 | > 所以相邻的相同数字的元素的个数等于这个元素的值 6 | 7 | 举例: 8 | 9 | > 122 10 | > 11 | > 333 12 | 13 | 这个矩阵是valid的,因为1有一个,2有两个,3有三个 14 | 15 | > 112 16 | > 17 | > 333 18 | 19 | 这个矩阵就是非法的。 20 | 21 | follow up: 如果对于特别大的矩阵该怎么处理,想象这个矩阵已经大到内存放不下了。 22 | 23 | 24 | 25 | ## Code 26 | 27 | ```python 28 | def checkValid(matrix): 29 | def dfs(i, j, value): 30 | count = 1 31 | visited[i][j] = True 32 | if i > 0 and not visited[i-1][j] and matrix[i-1][j] == value: 33 | count += dfs(i-1, j, value) 34 | if j > 0 and not visited[i][j-1] and matrix[i][j-1] == value: 35 | count += dfs(i, j-1, value) 36 | if i < height-1 and not visited[i+1][j] and matrix[i+1][j] == value: 37 | count += dfs(i+1, j, value) 38 | if j < width-1 and not visited[i][j+1] and matrix[i][j+1] == value: 39 | count += dfs(i, j+1, value) 40 | return count 41 | 42 | 43 | height = len(matrix) 44 | width = len(matrix[0]) 45 | visited = [[False for _ in range(width)] for _ in range(height)] 46 | for i in range(height): 47 | for j in range(width): 48 | if not visited[i][j]: 49 | value = matrix[i][j] 50 | count = dfs(i, j, value) 51 | if count != value: 52 | return False 53 | return True 54 | 55 | matrix = [[1,3,2],[3,3,3]] 56 | print(checkValid(matrix)) 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /WeChat Image_20191027222101.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhouzhiling/leetcode/69166c67b01249b464951d2d78b05db902cc3734/WeChat Image_20191027222101.jpg -------------------------------------------------------------------------------- /[Google]ChocolateSweetness.md: -------------------------------------------------------------------------------- 1 | # [Google]ChocolateSweetness 2 | 3 | Given an array `chocolate` of `n` non-negative integers, where the values are sweetness levels of the chocolate. You are also given a value `k` which denotes the number of friends you will share this chocolate with. Your friends are greedy so they will always take the highest sweetness chunk. Find out what is the maximum sweetness level you could get. 4 | 5 | 6 | 7 | tltr: Split the array into `k` non-empty continuous subarrays. Write an algorithm to maximize **the minimum** sum among these `k` subarrays. 8 | 9 | 10 | 11 | ## Solution 12 | 13 | 和410. Split Array Largest Sum类似的做法。 14 | 15 | 16 | 17 | ## Code 18 | 19 | ```python 20 | def chocolateSweetness(A, K): 21 | def possible(x): 22 | k, temp = 0, 0 23 | for a in A: 24 | temp += a 25 | if temp >= x: 26 | k, temp = k + 1, 0 27 | return k >= K 28 | 29 | l, h = min(A), sum(A) 30 | while l < h: 31 | m = (l + h + 1) // 2 32 | if possible(m): 33 | l = m 34 | else: 35 | h = m - 1 36 | return l 37 | 38 | 39 | # A = [6, 3, 2, 8, 7, 5] 40 | K = 2 41 | A = [25,25,2,2] 42 | print(chocolateSweetness(A, K)) 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /[Google]Local Max.md: -------------------------------------------------------------------------------- 1 | # Local Max 2 | 3 | Find Local ‍‌‌‍‌‌‍‍‍‌‌‍‌‌‍‍‍‌‌Maximum from a given array.A value is Local Maximum if it is greater than its adjacent values.e.g. [1, 2, 3, 1, 4, 1] -> [3, 4] 4 | 5 | **Follow-up:** 6 | 7 | Lets take this a step further. Instead of returning an array of numbers (the local maximal), recursively find local max. 8 | 9 | 10 | 11 | ## Code 12 | 13 | ```python 14 | class Solution(object): 15 | def fizzBuzz(self, n): 16 | """ 17 | :type n: int 18 | :rtype: List[str] 19 | """ 20 | nums = [1,6,4,10,5,9,3] 21 | length = len(nums) 22 | preidx = -1 23 | output = [] 24 | res = [] 25 | for i in range(1,length-1): 26 | if preidx!=i-1 and nums[i] > nums[i+1]: 27 | res.append(nums[i]) 28 | preidx = i 29 | preidx = -1 30 | output.append(res[:]) 31 | # cur = [] 32 | while len(res)>0: 33 | cur = [] 34 | lgth = len(res) 35 | for i in range(1,lgth-1): 36 | if preidx!=i-1 and res[i]>res[i+1]: 37 | cur.append(res[i]) 38 | preidx = i 39 | output.append(cur[:]) 40 | res = cur 41 | return output 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /[Quora]concatenationsSum.md: -------------------------------------------------------------------------------- 1 | Given an array of positive integers `a`, your task is to calculate the sum of every possible `a[i] ∘ a[j]`, where `a[i] ∘ a[j]` is the concatenation of the string representations of `a[i]` and `a[j]` respectively. 2 | 3 | Example 4 | 5 | - For `a = [10, 2]`, the output should be `concatenationsSum(a) = 1344`. 6 | 7 | - `a[0] ∘ a[0] = 10 ∘ 10 = 1010`, 8 | - `a[0] ∘ a[1] = 10 ∘ 2 = 102`, 9 | - `a[1] ∘ a[0] = 2 ∘ 10 = 210`, 10 | - `a[1] ∘ a[1] = 2 ∘ 2 = 22`. 11 | 12 | So the sum is equal to `1010 + 102 + 210 + 22 = 1344`. 13 | 14 | - For `a = [8]`, the output should be `concatenationsSum(a) = 88`. 15 | 16 | There is only one number in `a`, and `a[0] ∘ a[0] = 8 ∘ 8 = 88`, so the answer is `88`. 17 | 18 | Input/Output 19 | 20 | - **[execution time limit] 4 seconds (py)** 21 | 22 | - **[input] array.integer a** 23 | 24 | A non-empty array of positive integers. 25 | 26 | *Guaranteed constraints:* 27 | `1 ≤ a.length ≤ 105`, 28 | `1 ≤ a[i] ≤ 106`. 29 | 30 | - **[output] integer64** 31 | 32 | - The sum of all `a[i] ∘ a[j]`s. It's guaranteed that the answer is less than `253`. 33 | 34 | 35 | 36 | ## Code 37 | 38 | ```python 39 | def concatenationsSum(a): 40 | 41 | def calculate_digit(num): 42 | digit = 0 43 | # divisor = 10 44 | while num > 0: 45 | num = num / 10 46 | digit += 1 47 | return digit 48 | 49 | output = 0 50 | length = len(a) 51 | tensum = 0 52 | for num in a: 53 | tensum += pow(10,calculate_digit(num)) 54 | tensum += length 55 | 56 | return tensum * sum(a) 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /google电面.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhouzhiling/leetcode/69166c67b01249b464951d2d78b05db902cc3734/google电面.md -------------------------------------------------------------------------------- /java_3150103638_hw1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Zhouzhiling/leetcode/69166c67b01249b464951d2d78b05db902cc3734/java_3150103638_hw1.pdf --------------------------------------------------------------------------------