├── .gitignore ├── GenerateCodeTable$1.class ├── GenerateCodeTable.java ├── Java ├── 1. Two Sum.java ├── 10. Regular Expression Matching.java ├── 100. Same Tree.java ├── 1004. Max Consecutive Ones III.java ├── 1007. Minimum Domino Rotations For Equal Row.java ├── 1008. Construct Binary Search Tree from Preorder Traversal.java ├── 101. Symmetric Tree.java ├── 102. Binary Tree Level Order Traversal.java ├── 1021. Remove Outermost Parentheses.java ├── 1026. Maximum Difference Between Node and Ancestor.java ├── 103. Binary Tree Zigzag Level Order Traversal.java ├── 1033. Moving Stones Until Consecutive.java ├── 104. Maximum Depth of Binary Tree.java ├── 1040. Moving Stones Until Consecutive II.java ├── 1041. Robot Bounded In Circle.java ├── 1043. Partition Array for Maximum Sum.java ├── 1048. Longest String Chain.java ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.java ├── 1053. Previous Permutation With One Swap.java ├── 1057. Campus Bikes.java ├── 1060. Missing Element in Sorted Array.java ├── 1091. Shortest Path in Binary Matrix.java ├── 1094. Car Pooling.java ├── 110. Balanced Binary Tree.java ├── 1106. Parsing A Boolean Expression.java ├── 1108. Defanging an IP Address.java ├── 111. Minimum Depth of Binary Tree.java ├── 1110. Delete Nodes And Return Forest.java ├── 1117. Building H2O.java ├── 112. Path Sum.java ├── 1123. Lowest Common Ancestor of Deepest Leaves.java ├── 114. Flatten Binary Tree to Linked List.java ├── 1146. Snapshot Array.java ├── 1153. String Transforms Into Another String.java ├── 1161. Maximum Level Sum of a Binary Tree.java ├── 1170. Compare Strings by Frequency of the Smallest Character.java ├── 118. Pascal's Triangle.java ├── 119. Pascal's Triangle II.java ├── 1197. Minimum Knight Moves.java ├── 12. Integer to Roman.java ├── 1203. Sort Items by Groups Respecting Dependencies.java ├── 121. Best Time to Buy and Sell Stock.java ├── 1213. Intersection of Three Sorted Arrays.java ├── 1216. Valid Palindrome III.java ├── 1219. Path with Maximum Gold.java ├── 122. Best Time to Buy and Sell Stock II.java ├── 124. Binary Tree Maximum Path Sum.java ├── 1249. Minimum Remove to Make Valid Parentheses.java ├── 125. Valid Palindrome.java ├── 1267. Count Servers that Communicate.java ├── 13. Roman to Integer.java ├── 1306. Jump Game III.java ├── 131. Palindrome Partitioning.java ├── 133. Clone Graph.java ├── 134. Gas Station.java ├── 136. Single Number.java ├── 138. Copy List with Random Pointer.java ├── 139. Word Break.java ├── 14. Longest Common Prefix.java ├── 140. Word Break II.java ├── 141. Linked List Cycle.java ├── 142. Linked List Cycle II.java ├── 144. Binary Tree Preorder Traversal.java ├── 145. Binary Tree Postorder Traversal.java ├── 146. LRU Cache.java ├── 149. Max Points on a Line.java ├── 15. 3Sum.java ├── 151. Reverse Words in a String.java ├── 152. Maximum Product Subarray.java ├── 156. Binary Tree Upside Down.java ├── 157. Read N Characters Given Read4.java ├── 158. Read N Characters Given Read4 II - Call multiple times.java ├── 159. Longest Substring with At Most Two Distinct Characters.java ├── 160. Intersection of Two Linked Lists.java ├── 168. Excel Sheet Column Title.java ├── 169. Majority Element.java ├── 170. Two Sum III - Data structure design.java ├── 173. Binary Search Tree Iterator.java ├── 189. Rotate Array.java ├── 19. Remove Nth Node From End of List.java ├── 198. House Robber.java ├── 199. Binary Tree Right Side View.java ├── 2. Add Two Numbers.java ├── 20. Valid Parentheses.java ├── 200. Number of Islands.java ├── 202. Happy Number.java ├── 203. Remove Linked List Elements.java ├── 204. Count Primes.java ├── 205. Isomorphic Strings.java ├── 206. Reverse Linked List.java ├── 207. Course Schedule.java ├── 208. Implement Trie (Prefix Tree).java ├── 21. Merge Two Sorted Lists.java ├── 210. Course Schedule II.java ├── 211. Add and Search Word - Data structure design.java ├── 215. Kth Largest Element in an Array.java ├── 217. Contains Duplicate.java ├── 218. The Skyline Problem.java ├── 219. Contains Duplicate II.java ├── 22. Generate Parentheses.java ├── 221. Maximal Square.java ├── 222. Count Complete Tree Nodes.java ├── 229. Majority Element II.java ├── 23. Merge k Sorted Lists.java ├── 234. Palindrome Linked List.java ├── 235. Lowest Common Ancestor of a Binary Search Tree.java ├── 236. Lowest Common Ancestor of a Binary Tree.java ├── 237. Delete Node in a Linked List.java ├── 238. Product of Array Except Self.java ├── 239. Sliding Window Maximum.java ├── 242. Valid Anagram.java ├── 243. Shortest Word Distance.java ├── 244. Shortest Word Distance II.java ├── 245. Shortest Word Distance III.java ├── 246. Strobogrammatic Number.java ├── 252. Meeting Rooms.java ├── 253. Meeting Rooms II.java ├── 254. Factor Combinations.java ├── 256. Paint House.java ├── 257. Binary Tree Paths.java ├── 259. 3Sum Smaller.java ├── 26.Remove Duplicates from Sorted Array.java ├── 261. Graph Valid Tree.java ├── 265. Paint House II.java ├── 266. Palindrome Permutation.java ├── 269. Alien Dictionary.java ├── 270. Closest Binary Search Tree Value.java ├── 272. Closest Binary Search Tree Value II.java ├── 273. Integer to English Words.java ├── 274.H-Index.java ├── 275. H-Index II.java ├── 277. Find the Celebrity.java ├── 278. First Bad Version.java ├── 28. Implement strStr().java ├── 283. Move Zeroes.java ├── 287. Find the Duplicate Number.java ├── 293. Flip Game.java ├── 295. Find Median from Data Stream.java ├── 297. Serialize and Deserialize Binary Tree.java ├── 299. Bulls and Cows.java ├── 301. Remove Invalid Parentheses.java ├── 303. Range Sum Query - Immutable.java ├── 304. Range Sum Query 2D - Immutable.java ├── 305. Number of Islands II.java ├── 307. Range Sum Query - Mutable.java ├── 308. Range Sum Query 2D - Mutable.java ├── 31. Next Permutation.java ├── 311. Sparse Matrix Multiplication.java ├── 314. Binary Tree Vertical Order Traversal.java ├── 315. Count of Smaller Numbers After Self.java ├── 319. Bulb Switcher.java ├── 322. Coin Change.java ├── 327. Count of Range Sum.java ├── 33. Search in Rotated Sorted Array.java ├── 332. Reconstruct Itinerary.java ├── 339. Nested List Weight Sum.java ├── 34. Find First and Last Position of Element in Sorted Array.java ├── 340. Longest Substring with At Most K Distinct Characters.java ├── 341. Flatten Nested List Iterator.java ├── 345. Reverse Vowels of a String.java ├── 346. Moving Average from Data Stream.java ├── 347. Top K Frequent Elements.java ├── 349. Intersection of Two Arrays.java ├── 350. Intersection of Two Arrays II.java ├── 359. Logger Rate Limiter.java ├── 36. Valid Sudoku.java ├── 360. Sort Transformed Array.java ├── 361. Bomb Enemy.java ├── 364. Nested List Weight Sum II.java ├── 366. Find Leaves of Binary Tree.java ├── 367. Valid Perfect Square.java ├── 369. Plus One Linked List.java ├── 373. Find K Pairs with Smallest Sums.java ├── 380. Insert Delete GetRandom O(1).java ├── 383. Ransom Note.java ├── 387. First Unique Character in a String.java ├── 39. Combination Sum.java ├── 398. Random Pick Index.java ├── 399. Evaluate Division.java ├── 40. Combination Sum II.java ├── 402. Remove K Digits.java ├── 405. Convert a Number to Hexadecimal.java ├── 408. Valid Word Abbreviation.java ├── 41. First Missing Positive.java ├── 410. Split Array Largest Sum.java ├── 414. Third Maximum Number.java ├── 415. Add Strings.java ├── 416. Partition Equal Subset Sum.java ├── 42. Trapping Rain Water.java ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List.java ├── 427. Construct Quad Tree.java ├── 429. N-ary Tree Level Order Traversal.java ├── 43. Multiply Strings.java ├── 430. Flatten a Multilevel Doubly Linked List.java ├── 432. All One Data Structure.java ├── 438. Find All Anagrams in a String.java ├── 443. String Compression.java ├── 448. Find All Numbers Disappeared in an Array.java ├── 449. Serialize and Deserialize BST.java ├── 46. Permutations.java ├── 463. Island Perimeter.java ├── 47. Permutations II.java ├── 485. Max Consecutive Ones.java ├── 49. Group Anagrams.java ├── 493. Reverse Pairs.java ├── 496. Next Greater Element I.java ├── 4Sum.java ├── 5. Longest Palindromic Substring.java ├── 509. Fibonacci Number.java ├── 51. N-Queens.java ├── 515. Find Largest Value in Each Tree Row.java ├── 516. Longest Palindromic Subsequence.java ├── 518. Coin Change 2.java ├── 52. N-Queens II.java ├── 523. Continuous Subarray Sum.java ├── 53. Maximum Subarray.java ├── 543. Diameter of Binary Tree.java ├── 55. Jump Game.java ├── 557. Reverse Words in a String III.java ├── 56. Merge Intervals.java ├── 560. Subarray Sum Equals K.java ├── 561. Array Partition I.java ├── 567. Permutation in String.java ├── 57. Insert Interval.java ├── 58. Length of Last Word.java ├── 605. Can Place Flowers.java ├── 611. Valid Triangle Number.java ├── 62. Unique Path.java ├── 621. Task Scheduler.java ├── 63. Unique Paths II.java ├── 632. Smallest Range Covering Elements from K Lists.java ├── 636. Exclusive Time of Functions.java ├── 639. Decode Ways II.java ├── 64. Minimum Path Sum.java ├── 65. Valid Number.java ├── 665. Non-decreasing Array.java ├── 67. Add Binary.java ├── 671. Second Minimum Node In a Binary Tree.java ├── 674. Longest Continuous Increasing Subsequence.java ├── 68. Text Justification.java ├── 680. Valid Palindrome II.java ├── 686. Repeated String Match.java ├── 689. Maximum Sum of 3 Non-Overlapping Subarrays.java ├── 69. Sqrt(x).java ├── 692. Top K Frequent Words.java ├── 694. Number of Distinct Islands.java ├── 698. Partition to K Equal Sum Subsets.java ├── 7. Reverse Integer.java ├── 70. Climbing Stairs.java ├── 71. Simplify Path.java ├── 715. Range Module.java ├── 716. Max Stack.java ├── 717. 1-bit and 2-bit Characters.java ├── 72. Edit Distance.java ├── 720. Longest Word in Dictionary.java ├── 721. Accounts Merge.java ├── 724. Find Pivot Index.java ├── 727. Minimum Window Subsequence.java ├── 739. Daily Temperatures.java ├── 741. Cherry Pickup.java ├── 743. Network Delay Time.java ├── 745. Prefix and Suffix Search.java ├── 747. Largest Number At Least Twice of Others.java ├── 76. Minimum Window Substring.java ├── 760. Find Anagram Mappings.java ├── 766. Toeplitz Matrix.java ├── 767. Reorganize String.java ├── 771. Jewels and Stones.java ├── 78. Subsets.java ├── 785. Is Graph Bipartite.java ├── 788. Rotated Digits.java ├── 796. Rotate String.java ├── 8. String to Integer (atoi).java ├── 80.Remove Duplicates from Sorted Array II.java ├── 824. Goat Latin.java ├── 83. Remove Duplicates from Sorted List.java ├── 843. Guess the Word.java ├── 844. Backspace String Compare.java ├── 849. Maximize Distance to Closest Person.java ├── 850. Rectangle Area II.java ├── 852. Peak Index in a Mountain Array.java ├── 855. Exam Room.java ├── 875. Koko Eating Bananas.java ├── 876. Middle of Linked List.java ├── 88. Merge Sorted Array.java ├── 88. Search in Rotated Sorted Array II.java ├── 893. Groups of Special-Equivalent Strings.java ├── 896. Monotonic Array.java ├── 9. Palindrome Number.java ├── 91. Decode Ways.java ├── 921. Minimum Add to Make Parentheses Valid.java ├── 938. Range Sum of BST.java ├── 94. Binary Tree Inorder Traversal.java ├── 953. Verifying an Alien Dictionary.java ├── 973. K Closest Points to Origin.java ├── 977. Squares of a Sorted Array.java ├── 98. Validate Binary Search Tree.java ├── 981. Time Based Key-Value Store.java ├── 986. Interval List Intersections.java ├── 987. Vertical Order Traversal of a Binary Tree.java ├── Add Digits.java ├── Add Two Numbers II.java ├── Backpack II.java ├── Backpack III.java ├── Backpack V.java ├── Backpack VI.java ├── Backpack.java ├── Backspace String Compare.java ├── Basic Calculator.java ├── Best Time to Buy and Sell Stock III.java ├── Best Time to Buy and Sell Stock IV.java ├── Best Time to Buy and Sell Stock with Cooldown.java ├── Best Time to Buy and Sell Stock with Transaction Fee.java ├── Binary Gap.java ├── Binary Representation.java ├── Binary Tree Level Order Traversal II.java ├── Binary Tree Longest Consecutive Sequence II.java ├── Binary Tree Longest Consecutive Sequence.java ├── Binary Tree Maximum Path Sum II.java ├── Brick Wall.java ├── Bricks Falling When Hit.java ├── Burst Balloons.java ├── Bus Routes.java ├── Classical Binary Search.java ├── Closest Number in Sorted Array.java ├── Coins in a Line II.java ├── Coins in a Line III.java ├── Coins in a Line.java ├── ColorGrid.java ├── Combination Sum III.java ├── Combination Sum IV.java ├── Combinations.java ├── Compare Version Numbers.java ├── Complete Binary Tree.java ├── Connecting Graph II.java ├── Connecting Graph III.java ├── Connecting Graph.java ├── Construct Binary Tree from Inorder and Postorder Traversal.java ├── Container With Most Water.java ├── Contains Duplicate III.java ├── Contiguous Array.java ├── Convert Binary Search Tree to Sorted Doubly Linked List (extra space).java ├── Convert Expression to Polish Notation.java ├── Convert Expression to Reverse Polish Notation.java ├── Convert Integer A to Integer B.java ├── Convert Sorted Array to Binary Search Tree.java ├── Convert Sorted List to Binary Search Tree.java ├── Copy Books.java ├── Cosine Similarity.java ├── Count 1 in Binary.java ├── Count and Say.java ├── Count of Smaller Number before itself.java ├── Count of Smaller Number.java ├── Counting Bits.java ├── Cracking the Safe.java ├── Decode String.java ├── Design Search Autocomplete System.java ├── Distinct Subsequences.java ├── Encode and Decode Strings.java ├── Encode and Decode TinyURL.java ├── Evaluate Reverse Polish Notation.java ├── Excel Sheet Column Number.java ├── Expression Add Operators.java ├── Expression Evaluation.java ├── Expression Tree Build.java ├── Fast Power.java ├── Find Minimum in Rotated Sorted Array II.java ├── Find Minimum in Rotated Sorted Array.java ├── Find Peak Element II.java ├── Find Peak Element.java ├── Find the Connected Component in the Undirected Graph.java ├── Find the Weak Connected Component in the Directed Graph.java ├── Flatten 2D Vector.java ├── Flip Game II.java ├── Flood Fill.java ├── Fraction to Recurring Decimal.java ├── Friends Of Appropriate Ages.java ├── Frog Jump.java ├── Game of Life.java ├── Gray Code.java ├── Group Shifted Strings.java ├── Guess Number Higher or Lower.java ├── Hamming Distance.java ├── HashWithArray.java ├── HashWithCustomizedClass(LinkedList).java ├── Heaters.java ├── House Robber II.java ├── House Robber III.java ├── Implement Queue using Stacks.java ├── Implement Stack using Queues.java ├── Implement Stack.java ├── IndexMatch.java ├── Inorder Successor in BST.java ├── Insert Node in a Binary Search Tree .java ├── Insertion Sort List.java ├── Interleaving Positive and Negative Numbers.java ├── Interleaving String.java ├── Interval Minimum Number.java ├── Interval Sum II.java ├── Interval Sum.java ├── Invert Binary Tree.java ├── Jump Game II.java ├── K Edit Distance.java ├── K Empty Slots.java ├── Kth Largest Element in an Array.java ├── Kth Smallest Element in a BST.java ├── Kth Smallest Element in a Sorted Matrix.java ├── Kth Smallest Sum In Two Sorted Arrays.java ├── Largest Number.java ├── Largest Rectangle in Histogram.java ├── Last Position of Target.java ├── Letter Combinations of a Phone Number.java ├── Line Reflection.java ├── Linked List Cycle II.java ├── Longest Common Subsequence.java ├── Longest Common Substring.java ├── Longest Consecutive Sequence.java ├── Longest Increasing Continuous subsequence II.java ├── Longest Increasing Continuous subsequence.java ├── Longest Increasing Path in a Matrix.java ├── Longest Increasing Subsequence.java ├── Longest Substring Without Repeating Characters.java ├── Longest Univalue Path.java ├── Longest Valid Parentheses.java ├── Majority Number II.java ├── Majority Number III.java ├── Matrix Zigzag Traversal.java ├── Max Area of Island.java ├── Max Sum of Rectangle No Larger Than K.java ├── Maximal Rectangle.java ├── Maximum Average Subarray I.java ├── Maximum Average Subarray II.java ├── Maximum Binary Tree.java ├── Maximum Size Subarray Sum Equals k.java ├── Maximum Subarray II.java ├── Maximum Subarray III.java ├── Maximum Vacation Days.java ├── Maximum XOR of Two Numbers in an Array.java ├── Median of two Sorted Arrays.java ├── Merge Two Binary Trees.java ├── Min Stack.java ├── Minimum Absolute Difference in BST.java ├── Minimum Height Trees.java ├── Minimum Size Subarray Sum.java ├── Minimum Subarray.java ├── Minimum Swaps To Make Sequences Increasing.java ├── Missing Number.java ├── Missing Ranges.java ├── My Calendar I.java ├── Next Closest Time.java ├── Nim Game.java ├── Number Of Corner Rectangles.java ├── Number of Airplane in the sky.java ├── Number of Connected Components in an Undirected Graph.java ├── Number of Digit One.java ├── Number of Longest Increasing Subsequence.java ├── O(1) Check Power of 2.java ├── One Edit Distance.java ├── Ones and Zeroes.java ├── Orderly Queue.java ├── Paint Fence.java ├── Palindrome Pairs.java ├── Palindrome Partitioning II.java ├── Palindrome Permutation II.java ├── Palindromic Substrings.java ├── Partition Array by Odd and Even.java ├── Partition Array.java ├── Partition List.java ├── Path Sum II.java ├── Path Sum III.java ├── Path Sum IV.java ├── Peeking Iterator.java ├── Perfect Rectangle.java ├── Perfect Squares.java ├── Permutation Index.java ├── Permutation Sequence.java ├── Plus One.java ├── Populating Next Right Pointers in Each Node II.java ├── Populating Next Right Pointers in Each Node.java ├── Pow(x, n).java ├── Power of Three.java ├── Power of Two.java ├── Predict the Winner.java ├── Queue Reconstruction by Height.java ├── QuickSort.java ├── Rearrange String k Distance Apart.java ├── Recover Binary Search Tree.java ├── Redundant Connection II.java ├── Redundant Connection.java ├── Rehashing.java ├── Remove Duplicate Letters.java ├── Remove Duplicates from Sorted List II.java ├── Remove Duplicates from Unsorted List.java ├── Remove Node in Binary Search Tree.java ├── Reorder List.java ├── Reshape the Matrix.java ├── Restore IP Addresses.java ├── Reverse Linked List II .java ├── Reverse String.java ├── Reverse Words in a String II.java ├── Robot Room Cleaner.java ├── Rotate Image.java ├── Rotate List.java ├── Russian Doll Envelopes.java ├── Scramble String.java ├── Search Insert Position.java ├── Search Range in Binary Search Tree .java ├── Search a 2D Matrix II.java ├── Search a 2D Matrix.java ├── Search for a Range.java ├── Segment Tree Modify.java ├── Segment Tree Query II.java ├── Shortest Distance from All Buildings.java ├── Shortest Palindrome.java ├── Shuffle an Array.java ├── Single Number II.java ├── Single Number III.java ├── Singleton.java ├── Sliding Puzzle.java ├── Sliding Window Median.java ├── Smallest Subtree with all the Deepest Nodes.java ├── Sort Colors II.java ├── Sort Colors.java ├── Sort Letters by Case.java ├── Sort List.java ├── Space Replacement.java ├── Spiral Matrix.java ├── Stone Game.java ├── String Permutation.java ├── Strobogrammatic Number II.java ├── Subarray Sum Closest.java ├── Subarray Sum II.java ├── Submatrix Sum.java ├── Subsets II.java ├── Subtree of Another Tree.java ├── Subtree.java ├── Sum of Two Integers.java ├── Summary Ranges.java ├── Surrounded Regions.java ├── Swap Bits.java ├── Swap Nodes in Pairs.java ├── Target Sum.java ├── The Maze II.java ├── The Maze III.java ├── The Maze.java ├── The Smallest Difference.java ├── The Spiral Matrix II.java ├── Total Hamming Distance.java ├── Total Occurrence of Target.java ├── Trailing Zeros.java ├── Trapping Rain Water II.java ├── Triangle Count.java ├── Triangles.java ├── Trim a Binary Search Tree.java ├── Tweaked Identical Binary Tree.java ├── Two Lists Sum.java ├── Two Strings Are Anagrams.java ├── Two Sum II - Input array is sorted.java ├── Two Sum IV - Input is a BST.java ├── Ugly Number II.java ├── Ugly Number.java ├── Unique Binary Search Tree II.java ├── Unique Binary Search Tree.java ├── Unique Word Abbreviation.java ├── Update Bits.java ├── Walls and Gates.java ├── Wiggle Sort.java ├── Wildcard Matching.java ├── Wood Cut.java ├── Word Ladder II.java ├── Word Ladder.java ├── Word Pattern.java ├── Word Search II.java ├── Word Search.java ├── Word Squares.java ├── Zigzag Iterator.java ├── [HackerRank]. Change to Anagram.java ├── [lint]. 2 Sum II.java ├── [lint]. 3 Sum Closest.java ├── [lint]. Anagrams.java ├── [lint]. Compare Strings.java ├── [lint]. HashHeap.java ├── [lint]. Heapify.java ├── [lint]. Longest Words.java ├── [lint]. Lowest Common Ancestor II.java ├── [lint]. Merge k Sorted Arrays.java ├── [lint]. Nth to Last Node in List.java ├── [lint]. Product of Array Exclude Itself.java ├── [lint]. Recover Rotated Sorted Array.java ├── [lint]. Segment Tree Build II.java ├── [lint]. Segment Tree Build.java ├── [lint]. Segment Tree Query.java ├── [lint]. Subarray Sum.java ├── [lint]. Unique Characters.java ├── [tool] Quick Select - Median.java ├── [tool]. Hash Function.java ├── [tool]. MergeSort.java ├── [tool]. Topological Sorting.java ├── [tool]. UnionFind.java └── k Sum.java ├── KnowledgeHash.md ├── LevelReviewPage.md ├── Others ├── CheckClock.java ├── HackerrankNote.md ├── Insert a node into a sorted doubly linked list.java ├── Matching Same Text Again & Again.java ├── MorseCode.java ├── README.md ├── RemoveNodeFromLinkedList.java ├── Solution$TreeNode.class ├── Solution.class ├── Solution.java ├── Sort Anagram.java ├── TopTenURL.java ├── Tree-Huffman Decoding.java ├── old records │ ├── LeetCode-Merged │ │ ├── GenerateCodeTable.class │ │ ├── GenerateCodeTable.java │ │ ├── Java │ │ │ ├── 3Sum Smaller.java │ │ │ ├── 3Sum.java │ │ │ ├── Alien Dictionary.java │ │ │ ├── Binary Search Tree Iterator.java │ │ │ ├── Binary Tree Inorder Traversal.java │ │ │ ├── Binary Tree Level Order Traversal.java │ │ │ ├── Binary Tree Longest Consecutive Sequence.java │ │ │ ├── Binary Tree Paths.java │ │ │ ├── Binary Tree Right Side View.java │ │ │ ├── Building Outline.java │ │ │ ├── Burst Balloons.java │ │ │ ├── Closest Binary Search Tree Value.java │ │ │ ├── Count Primes.java │ │ │ ├── Course Schedule II.java │ │ │ ├── Course Schedule.java │ │ │ ├── Encode and Decode Strings.java │ │ │ ├── Excel Sheet Column Number.java │ │ │ ├── ExcelSheetColumnNumber .java │ │ │ ├── Find Peak Element.java │ │ │ ├── First Bad Version.java │ │ │ ├── Flatten 2D Vector.java │ │ │ ├── Flattern 2D Vector.java │ │ │ ├── Flip Game II.java │ │ │ ├── Flip Game.java │ │ │ ├── Fraction to Recurring Decimal.java │ │ │ ├── Game of Life.java │ │ │ ├── Generate Parentheses.java │ │ │ ├── Graph Valid Tree.java │ │ │ ├── Gray Code.java │ │ │ ├── Group Anagrams.java │ │ │ ├── H-Index II.java │ │ │ ├── H-Index.java │ │ │ ├── Implement Trie (Prefix Tree).java │ │ │ ├── Implement strStr().java │ │ │ ├── Insert Interval.java │ │ │ ├── Integer to English Words.java │ │ │ ├── Intersection of Two Linked Lists.java │ │ │ ├── Jump Game.java │ │ │ ├── Kth Smallest Element in a BST.java │ │ │ ├── LRU Cache.java │ │ │ ├── Letter Combinations of a Phone Number.java │ │ │ ├── Longest Palindromic Substring.java │ │ │ ├── Lowest Common Ancestor of a Binary Search Tree.java │ │ │ ├── MaximumSubarray.java │ │ │ ├── Median of Two Sorted Arrays.java │ │ │ ├── Meeting Rooms II.java │ │ │ ├── Meeting Rooms.java │ │ │ ├── Merge Intervals.java │ │ │ ├── Merge Two Sorted Lists.java │ │ │ ├── Merge k Sorted Lists.java │ │ │ ├── Min Stack.java │ │ │ ├── Minimum Height Trees.java │ │ │ ├── Missing Ranges.java │ │ │ ├── Multiply Strings.java │ │ │ ├── Number of Islands.java │ │ │ ├── One Edit Distance.java │ │ │ ├── Paint Fence.java │ │ │ ├── Palindrome Permutation.java │ │ │ ├── Peeking Iterator.java │ │ │ ├── Perfect Squares.java │ │ │ ├── Plus One.java │ │ │ ├── Restore IP Addresses.java │ │ │ ├── Reverse Linked List.java │ │ │ ├── Reverse Words in a String II.java │ │ │ ├── Rotate Image.java │ │ │ ├── Search a 2D Matrix II.java │ │ │ ├── Search a 2D Matrix.java │ │ │ ├── String to Integer.java │ │ │ ├── Strobogrammatic Number II.java │ │ │ ├── Strobogrammatic Number.java │ │ │ ├── Summary Ranges.java │ │ │ ├── Surrounded Regions.java │ │ │ ├── Symmetric Binar Tree.java │ │ │ ├── Trapping Rain Water.java │ │ │ ├── Two Sum II - Input array is sorted.java │ │ │ ├── Two Sum.java │ │ │ ├── Ugly Number II.java │ │ │ ├── Ugly Number.java │ │ │ ├── Unique Word Abbreviation.java │ │ │ ├── Valid Anagram.java │ │ │ ├── Valid Parentheses.java │ │ │ ├── Validate Binary Search Tree.java │ │ │ ├── Wiggle Sort.java │ │ │ ├── Word Pattern.java │ │ │ ├── Zigzag Iterator.java │ │ │ └── reverseInteger.java │ │ ├── README.md │ │ └── WordPress.txt │ └── LintCode-Backup │ │ ├── 2 Sum.java │ │ ├── 3 Sum Closest.java │ │ ├── 3 Sum.java │ │ ├── 4 Sum.java │ │ ├── A+B.java │ │ ├── Add Binary.java │ │ ├── Add Two Numbers II.java │ │ ├── Add Two Numbers.java │ │ ├── Add and Search Word.java │ │ ├── Anagrams.java │ │ ├── Backpack II.java │ │ ├── Backpack.java │ │ ├── Balanced Binary Tree.java │ │ ├── Best Time to Buy and Sell Stock I.java │ │ ├── Best Time to Buy and Sell Stock II.java │ │ ├── Best Time to Buy and Sell Stock III .java │ │ ├── Best Time to Buy and Sell Stock IV.java │ │ ├── Binary Representation.java │ │ ├── Binary Search Tree Iterator.java │ │ ├── Binary Tree Inorder Traversal.java │ │ ├── Binary Tree Level Order Traversal II.java │ │ ├── Binary Tree Level Order Traversal.java │ │ ├── Binary Tree Maximum Path Sum II.java │ │ ├── Binary Tree Maximum Path Sum.java │ │ ├── Binary Tree Path Sum.java │ │ ├── Binary Tree Paths.java │ │ ├── Binary Tree Postorder Traversal.java │ │ ├── Binary Tree Preorder Traversal.java │ │ ├── Binary Tree Zigzag Level Order Traversal.java │ │ ├── Building Outline.java │ │ ├── Classical Binary Search.java │ │ ├── Climbing Stairs.java │ │ ├── Clone Graph.java │ │ ├── Closest Number in Sorted Array.java │ │ ├── Coins in a Line.java │ │ ├── Combination Sum II.java │ │ ├── Combination Sum.java │ │ ├── Combinations.java │ │ ├── Compare Strings.java │ │ ├── Complete Binary Tree.java │ │ ├── Construct Binary Tree from Inorder and Postorder Traversal.java │ │ ├── Construct Binary Tree from Inorder and Preorder Traversal.java │ │ ├── Container With Most Water.java │ │ ├── Convert Binary Search Tree to Doubly Linked List.java │ │ ├── Convert Expression to Polish Notation.java │ │ ├── Convert Expression to Reverse Polish Notation.java │ │ ├── Convert Integer A to Integer B.java │ │ ├── Convert Sorted Array to Binary Search Tree With Minimal Height.java │ │ ├── Convert Sorted List to Binary Search Tree.java │ │ ├── Copy List with Random Pointer.java │ │ ├── Cosine Similarity.java │ │ ├── Count 1 in Binary.java │ │ ├── Count and Say.java │ │ ├── Count of Smaller Number before itself.java │ │ ├── Count of Smaller Number.java │ │ ├── Data Stream Median.java │ │ ├── Delete Digits.java │ │ ├── Delete Node in the Middle of Singly Linked List.java │ │ ├── Distinct Subsequences.java │ │ ├── Easy Reverse Linked List.java │ │ ├── Edit Distance.java │ │ ├── Expression Evaluation.java │ │ ├── Expression Tree Build.java │ │ ├── Fast Power.java │ │ ├── Fibonacci.java │ │ ├── Find Minimum in Rotated Sorted Array II.java │ │ ├── Find Minimum in Rotated Sorted Array.java │ │ ├── Find Peak Element II.java │ │ ├── Find Peak Element.java │ │ ├── Find the Connected Component in the Undirected Graph.java │ │ ├── Find the Weak Connected Component in the Directed Graph.java │ │ ├── First Bad Version.java │ │ ├── First Missing Positive.java │ │ ├── Flatten Binary Tree to Linked List.java │ │ ├── Gas Station.java │ │ ├── Generate Parentheses.java │ │ ├── Graph Valid Tree.java │ │ ├── Happy Number.java │ │ ├── Hash Function.java │ │ ├── HashWithArray.java │ │ ├── Heapify.java │ │ ├── House Robber.java │ │ ├── Identical Binary Tree.java │ │ ├── Implement Queue by Two Stacks.java │ │ ├── Implement Stack by Two Queues.java │ │ ├── Implement Stack.java │ │ ├── Implement Trie.java │ │ ├── Insert Interval.java │ │ ├── Insert Node in a Binary Search Tree .java │ │ ├── Insertion Sort List.java │ │ ├── Interleaving Positive and Negative Numbers.java │ │ ├── Interleaving String.java │ │ ├── Intersection of Two Linked Lists.java │ │ ├── Interval Minimum Number.java │ │ ├── Interval Sum II.java │ │ ├── Interval Sum.java │ │ ├── Invert Binary Tree.java │ │ ├── Jump Game II.java │ │ ├── Jump Game.java │ │ ├── Kth Largest Element.java │ │ ├── Kth Smallest Sum In Two Sorted Arrays.java │ │ ├── Largest Number.java │ │ ├── Largest Rectangle in Histogram.java │ │ ├── Last Position of Target.java │ │ ├── Length of Last Word.java │ │ ├── Letter Combinations of a Phone Number.java │ │ ├── Linked List Cycle II.java │ │ ├── Linked List Cycle.java │ │ ├── Longest Common Prefix.java │ │ ├── Longest Common Subsequence.java │ │ ├── Longest Common Substring.java │ │ ├── Longest Consecutive Sequence.java │ │ ├── Longest Increasing Continuous subsequence II.java │ │ ├── Longest Increasing Continuous subsequence.java │ │ ├── Longest Increasing Subsequence.java │ │ ├── Longest Palindromic Substring.java │ │ ├── Longest Substring Without Repeating Characters.java │ │ ├── Longest Substring with At Most K Distinct Characters.java │ │ ├── Longest Words.java │ │ ├── Lowest Common Ancestor II.java │ │ ├── Lowest Common Ancestor.java │ │ ├── Majority Number II.java │ │ ├── Majority Number III.java │ │ ├── Majority Number.java │ │ ├── Matrix Zigzag Traversal.java │ │ ├── Max Tree.java │ │ ├── Maximal Square.java │ │ ├── Maximum Depth of Binary Tree.java │ │ ├── Maximum Product Subarray.java │ │ ├── Maximum Subarray III.java │ │ ├── MaximumSubarray.java │ │ ├── MaximumSubarrayII.java │ │ ├── Median of two Sorted Arrays.java │ │ ├── Median.java │ │ ├── Merge Intervals.java │ │ ├── Merge Sorted Array II.java │ │ ├── Merge Sorted Array.java │ │ ├── Merge Two Sorted List.java │ │ ├── Merge k Sorted Arrays.java │ │ ├── Merge k Sorted Lists.java │ │ ├── Middle of Linked List.java │ │ ├── Min Stack.java │ │ ├── Minimum Path Sum.java │ │ ├── Minimum Size Subarray Sum.java │ │ ├── Minimum Subarray.java │ │ ├── Minimum Window Substring.java │ │ ├── MinimumDepthOfBinaryTree.java │ │ ├── NQueens.java │ │ ├── NQueensII.java │ │ ├── Next Permutation.java │ │ ├── Nim Game.java │ │ ├── Nth to Last Node in List.java │ │ ├── Number Triangles.java │ │ ├── Number of Airplane in the sky.java │ │ ├── Number of Islands II.java │ │ ├── Number of Islands.java │ │ ├── O(1) Check Power of 2.java │ │ ├── Palindrome Linked List.java │ │ ├── Palindrome Partitioning II.java │ │ ├── Palindrome Partitioning.java │ │ ├── Partition Array by Odd and Even.java │ │ ├── Partition Array.java │ │ ├── Partition List.java │ │ ├── Permutation Index.java │ │ ├── Permutations II.java │ │ ├── Permutations.java │ │ ├── Plus One.java │ │ ├── Pow(x,n).java │ │ ├── Product of Array Exclude Itself.java │ │ ├── QuickSort.java │ │ ├── Recover Rotated Sorted Array.java │ │ ├── Rehashing.java │ │ ├── Remove Duplicates from Sorted Array.java │ │ ├── Remove Duplicates from Sorted List II.java │ │ ├── Remove Duplicates from Sorted List.java │ │ ├── Remove Duplicates from Unsorted List.java │ │ ├── Remove Linked List Elements.java │ │ ├── Remove Node in Binary Search Tree.java │ │ ├── Remove Nth Node From End of List.java │ │ ├── Reorder List.java │ │ ├── Reverse Integer.java │ │ ├── Reverse Linked List II .java │ │ ├── Reverse Linked List.java │ │ ├── Reverse Words in a String.java │ │ ├── Rotate Image.java │ │ ├── Rotate List.java │ │ ├── Rotate String.java │ │ ├── Search Insert Position.java │ │ ├── Search Range in Binary Search Tree .java │ │ ├── Search Rotated in Sorted Array II.java │ │ ├── Search Rotated in Sorted Array.java │ │ ├── Search a 2D Matrix II.java │ │ ├── Search a 2D Matrix.java │ │ ├── Search for a Range.java │ │ ├── Segment Tree Build II.java │ │ ├── Segment Tree Build.java │ │ ├── Segment Tree Modify.java │ │ ├── Segment Tree Query II.java │ │ ├── Segment Tree Query.java │ │ ├── Serilization and Deserialization Of Binary Tree.java │ │ ├── Single Number II.java │ │ ├── Single Number III.java │ │ ├── Single Number.java │ │ ├── Singleton.java │ │ ├── Sliding Window Maximum.java │ │ ├── Sliding Window Median.java │ │ ├── Sort Color.java │ │ ├── Sort Colors II.java │ │ ├── Sort Letters by Case.java │ │ ├── Sort List.java │ │ ├── Space Replacement.java │ │ ├── Sqrt(x).java │ │ ├── Stone Game.java │ │ ├── StrStr.java │ │ ├── String to Integer(atoi).java │ │ ├── Subarray Sum Closest.java │ │ ├── Subarray Sum.java │ │ ├── Subset.java │ │ ├── Subsets II.java │ │ ├── Subtree.java │ │ ├── Swap Nodes in Pairs.java │ │ ├── Symmetric Binary Tree.java │ │ ├── The Smallest Difference.java │ │ ├── Top K Frequent Words.java │ │ ├── Topological Sorting.java │ │ ├── Total Occurrence of Target.java │ │ ├── Trailing Zeros.java │ │ ├── Trapping Rain Water II.java │ │ ├── Trapping Rain Water.java │ │ ├── Triangle Count.java │ │ ├── Tweaked Identical Binary Tree.java │ │ ├── Two Lists Sum.java │ │ ├── Two Strings Are Anagrams.java │ │ ├── Two Sum II.java │ │ ├── Ugly Number.java │ │ ├── Unique Binary Search Tree II.java │ │ ├── Unique Binary Search Tree.java │ │ ├── Unique Characters.java │ │ ├── Unique Path.java │ │ ├── Unique Paths II.java │ │ ├── Update Bits.java │ │ ├── Valid Palindrome.java │ │ ├── Valid Parentheses.java │ │ ├── Valid Sudoku.java │ │ ├── Validate Binary Search Tree.java │ │ ├── Wood Cut.java │ │ ├── Word Break.java │ │ ├── Word Ladder II.java │ │ ├── Word Ladder.java │ │ ├── Word Search II.java │ │ └── Word Search.java └── 亚麻 │ ├── FindFirstDuplicate.java │ └── Slot Machine.java ├── README.md ├── ReviewPage.md ├── Solution.java ├── SystemDesign.md ├── TagREADME.md ├── TagReviewPage.md ├── WordPress.txt ├── fails.md ├── knowledgeHash.json └── review ├── Adjacency Matrix.md ├── Analysis.md ├── Array.md ├── BFS.md ├── BIT.md ├── BST.md ├── Backpack DP.md ├── Backpack.md ├── Backtracking.md ├── Basic Implementation.md ├── Binary Indexed Tree.md ├── Binary Search on Value.md ├── Binary Search.md ├── Binary Tree.md ├── Bit Manipulation.md ├── Bitwise DP.md ├── Brainteaser.md ├── Bucket Sort.md ├── Combination.md ├── Coordinate DP.md ├── Cycle Detection.md ├── DFS.md ├── DP.md ├── Deque.md ├── Design.md ├── Divide and Conquer.md ├── Double Recursive.md ├── Double Sequence DP.md ├── Doubly Linked List.md ├── Edge Case.md ├── Enumeration.md ├── Expression Tree.md ├── Game Theory.md ├── Garph.md ├── Geometry.md ├── Graph.md ├── Greedy.md ├── Hash Table.md ├── HashHeap.md ├── Heap.md ├── Interval DP.md ├── Interval.md ├── KMP.md ├── Linked List.md ├── LinkedHashMap.md ├── Lint.md ├── List.md ├── Lock.md ├── Math.md ├── Matrix DFS.md ├── MaxHeap.md ├── Memoization.md ├── Merge Sort.md ├── MinHeap.md ├── MiniMax.md ├── Minimum Binary Tree.md ├── Monotonous Stack.md ├── Moore Voting.md ├── NestedInteger.md ├── PQ.md ├── Partition DP.md ├── Partition.md ├── Permutation.md ├── PreProduct.md ├── PreSum.md ├── PriorityQueue.md ├── Pruning.md ├── Queue.md ├── Quick Select.md ├── Quick Sort.md ├── Recursion.md ├── Reservior Sampling.md ├── Rotation.md ├── Segment Tree.md ├── Semaphore.md ├── Sequence DFS.md ├── Sequence DP.md ├── Sliding Window.md ├── Slow Fast Pointer.md ├── Sort.md ├── Stack.md ├── Status DP.md ├── String.md ├── Subarray.md ├── Sweep Line.md ├── Thread.md ├── Topological Sort.md ├── Tree DP.md ├── Tree.md ├── TreeMap.md ├── TreeSet.md ├── Trie.md ├── Two Pointers.md ├── Two Stacks.md ├── Union Find.md └── level ├── Easy.md ├── Hard.md ├── Medium.md ├── NA.md └── Review.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | GenerateCodeTable.class 3 | GenerateCodeTable$TableRow.class 4 | gh-md-toc 5 | Solution.class 6 | -------------------------------------------------------------------------------- /GenerateCodeTable$1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awangdev/leet-code/11cb3779bca977c66374f749adc6e41fede36b79/GenerateCodeTable$1.class -------------------------------------------------------------------------------- /Java/104. Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: DFS, Tree 3 | 4 | 给一个binary tree, 找最深depth 5 | 6 | #### DFS 7 | - 这里要走过所有的node, 所以dfs非常合适 8 | - Divide and conquer. 9 | - 维持一个最大值: Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 10 | - 注意check root == null 11 | 12 | #### Note 13 | - BFS is doable as well, but a bit more code to write: tracks largest level we reach 14 | 15 | ``` 16 | /* 17 | Given a binary tree, find its maximum depth. 18 | 19 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 20 | 21 | Note: A leaf is a node with no children. 22 | 23 | Example: 24 | 25 | Given binary tree [3,9,20,null,null,15,7], 26 | 27 | 3 28 | / \ 29 | 9 20 30 | / \ 31 | 15 7 32 | return its depth = 3. 33 | 34 | */ 35 | 36 | /* 37 | Thinking process: 38 | check if root is null, return 0 if so. 39 | Divide and return integer as the depth 40 | Conquer: find the max and return depth + 1. 41 | */ 42 | 43 | /** 44 | * Definition for a binary tree node. 45 | * public class TreeNode { 46 | * int val; 47 | * TreeNode left; 48 | * TreeNode right; 49 | * TreeNode(int x) { val = x; } 50 | * } 51 | */ 52 | public class Solution { 53 | public int maxDepth(TreeNode root) { 54 | if (root == null) { 55 | return 0; 56 | } 57 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 58 | } 59 | } 60 | 61 | ``` -------------------------------------------------------------------------------- /Java/1108. Defanging an IP Address.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: String, Basic Implementation 3 | 4 | ``` 5 | 6 | /** 7 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 8 | 9 | A defanged IP address replaces every period "." with "[.]". 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: address = "1.1.1.1" 16 | Output: "1[.]1[.]1[.]1" 17 | Example 2: 18 | 19 | Input: address = "255.100.50.0" 20 | Output: "255[.]100[.]50[.]0" 21 | */ 22 | class Solution { 23 | public String defangIPaddr(String address) { 24 | StringBuffer sb = new StringBuffer(); 25 | for (char c : address.toCharArray()) { 26 | if (c == '.') { 27 | sb.append("[.]"); 28 | } else { 29 | sb.append(c); 30 | } 31 | } 32 | return sb.toString(); 33 | } 34 | } 35 | ``` -------------------------------------------------------------------------------- /Java/112. Path Sum.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Tree, DFS 3 | 4 | 给一个inputSum, 然后dfs, 找到是否有一条path, 得出的path sum 跟 inputSum 一样. 5 | 6 | #### DFS 7 | - 确定好结尾条件: `is leaf` && `val == sum`. 8 | - 每一层减掉node.val, 然后dfs. 9 | - 写一写: `root == null => false` 对parent nodes的影响. 这里发现没影响, 所以可以简化成用1个functionDFS. 10 | 11 | 12 | ``` 13 | /* 14 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 15 | 16 | Note: A leaf is a node with no children. 17 | 18 | Example: 19 | 20 | Given the below binary tree and sum = 22, 21 | 22 | 5 23 | / \ 24 | 4 8 25 | / / \ 26 | 11 13 4 27 | / \ \ 28 | 7 2 1 29 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 30 | */ 31 | 32 | /** 33 | * Definition for a binary tree node. 34 | * public class TreeNode { 35 | * int val; 36 | * TreeNode left; 37 | * TreeNode right; 38 | * TreeNode(int x) { val = x; } 39 | * } 40 | */ 41 | /* 42 | Thoughts: 43 | DFS on the function itself, keep subtracting the root.val. 44 | when root == null && sum == 0, return true; 45 | */ 46 | 47 | class Solution { 48 | public boolean hasPathSum(TreeNode root, int sum) { 49 | if (root == null) return false; 50 | if (root.left == null && root.right == null && sum == root.val) return true; 51 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 52 | } 53 | } 54 | 55 | 56 | ``` -------------------------------------------------------------------------------- /Java/118. Pascal's Triangle.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, List, Basic Implementation 3 | time: O(n^2) based on pascal triangle size 4 | space: O(n^2) 5 | 6 | ``` 7 | /* 8 | Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 9 | 10 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 11 | 12 | Example: 13 | 14 | Input: 5 15 | Output: 16 | [ 17 | [1], 18 | [1,1], 19 | [1,2,1], 20 | [1,3,3,1], 21 | [1,4,6,4,1] 22 | ] 23 | */ 24 | 25 | class Solution { 26 | public List> generate(int numRows) { 27 | List> result = new ArrayList<>(); 28 | if (numRows == 0) return result; 29 | if (numRows >= 1) result.add(Arrays.asList(1)); 30 | if (numRows >= 2) result.add(Arrays.asList(1, 1)); 31 | 32 | for (int row = 2; row < numRows; row++) { 33 | List list = new ArrayList<>(Arrays.asList(1, 1)); 34 | List lastRow = result.get(row - 1); 35 | int end = row - 1; 36 | for (int i = 1; i <= end; i++) { 37 | list.add(i, lastRow.get(i) + lastRow.get(i - 1)); 38 | } 39 | result.add(list); 40 | } 41 | return result; 42 | } 43 | } 44 | ``` -------------------------------------------------------------------------------- /Java/119. Pascal's Triangle II.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, Basic Implementation 3 | time: O(k^2), pascal triangle size 4 | space: O(k^2) 5 | 6 | 简单处理 list. code is very similar to Pascal triangle I. 7 | 8 | - 注意 `list = Arrays.asList(x, y, z ...)` 给fixed-size list, 不能直接 list.add(). 9 | - Use `new ArrayList<>(Arrays.asList(...))` to wrap it up. 10 | 11 | 12 | ``` 13 | 14 | 15 | /* 16 | Given an index k, return the kth row of the Pascal's triangle. 17 | 18 | For example, given k = 3, 19 | Return [1,3,3,1]. 20 | 21 | Note: 22 | Could you optimize your algorithm to use only O(k) extra space? 23 | 24 | Hide Tags Array 25 | Hide Similar Problems (E) Pascal's Triangle 26 | 27 | */ 28 | 29 | 30 | /* 31 | 1 32 | 1 1 33 | 1 2 1 34 | 1 3 3 1 35 | */ 36 | 37 | //list store 0 1 0. Iteratve over k, each time createa a new list. 38 | //Add 1 on two size before calculating each row 39 | class Solution { 40 | public List getRow(int rowIndex) { 41 | List result = new ArrayList<>(); 42 | if (rowIndex == 0) result.add(1); 43 | if (rowIndex >= 1) result.add(1); 44 | 45 | for (int row = 1; row <= rowIndex; row++) { 46 | List list = new ArrayList<>(Arrays.asList(1, 1)); 47 | List lastRow = result; 48 | int end = row - 1; 49 | for (int i = 1; i <= end; i++) { 50 | list.add(i, lastRow.get(i) + lastRow.get(i - 1)); 51 | } 52 | result = list; 53 | } 54 | return result; 55 | } 56 | } 57 | ``` -------------------------------------------------------------------------------- /Java/136. Single Number.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Hash Table, Bit Manipulation 3 | 4 | Bit XOR: 当两个bit不同时,return 1. 5 | 题目正要消光所有重复出现的数儿留下出现一次的那个. 6 | 7 | ``` 8 | /* 9 | Given a non-empty array of integers, every element appears twice except for one. Find that single one. 10 | 11 | Note: 12 | 13 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 14 | 15 | Example 1: 16 | 17 | Input: [2,2,1] 18 | Output: 1 19 | Example 2: 20 | 21 | Input: [4,1,2,1,2] 22 | Output: 4 23 | 24 | 25 | Thinking process: 26 | One-pass and constant extra space. 27 | since all numbers appears twice, consider them as in bits format. Two identical number XOR will be zero. 28 | If we XOR everything double-numbers together, it will be zero. 29 | At the end, we use o XOR our target number, the result is actually the target number. 30 | Very smart trick to use bits. 31 | In order to compare from index 0 to the end, we need to extract index 0 first as result before for loop. And start for loop at i = 1. 32 | */ 33 | 34 | class Solution { 35 | public int singleNumber(int[] nums) { 36 | if (nums == null || nums.length == 0) return 0; 37 | int result = 0; 38 | for (int i : nums) { 39 | result = result ^ i; 40 | } 41 | return result; 42 | } 43 | } 44 | 45 | 46 | 47 | ``` -------------------------------------------------------------------------------- /Java/168. Excel Sheet Column Title.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Math 3 | time: O(n) 4 | space: O(1) 5 | 6 | #### 基本换算 7 | - 26位, 像10位一样去思考 8 | - 从末尾开始, mod %26 可以拿到 末尾数字 remain = n % 26 9 | - 特殊: remain = 0 的时候, 也就是说n是26的倍数, 末尾应该是 'Z' 10 | - 记录'Z'了之后, n-- 11 | 12 | 13 | ``` 14 | /* 15 | Given a positive integer, return its corresponding column title 16 | as appear in an Excel sheet. 17 | 18 | For example: 19 | 20 | 1 -> A 21 | 2 -> B 22 | 3 -> C 23 | ... 24 | 26 -> Z 25 | 27 -> AA 26 | 28 -> AB 27 | */ 28 | 29 | /* 30 | Thoughts: 31 | 26 bits => num / 26 = 1 => 'A' on that digit 32 | */ 33 | class Solution { 34 | public String convertToTitle(int n) { 35 | if (n <= 0) { 36 | return null; 37 | } 38 | 39 | StringBuilder sb = new StringBuilder(); 40 | while (n > 0) { 41 | int remain = n % 26; 42 | n = n / 26; 43 | if (remain == 0) { 44 | sb.append("Z"); 45 | n--; 46 | } else { 47 | sb.append((char)('A' + remain - 1)); 48 | } 49 | } 50 | return sb.reverse().toString(); 51 | } 52 | } 53 | ``` -------------------------------------------------------------------------------- /Java/189. Rotate Array.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, Rotation 3 | 4 | #### Rotate array in place 5 | - rotate all 6 | - rotate 2 sides: < k or >= 7 | 8 | 9 | #### Rotate by buffer the k array 10 | 11 | ``` 12 | /* 13 | Given an array, rotate the array to the right by k steps, where k is non-negative. 14 | 15 | Example 1: 16 | 17 | Input: [1,2,3,4,5,6,7] and k = 3 18 | Output: [5,6,7,1,2,3,4] 19 | Explanation: 20 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 21 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 22 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 23 | Example 2: 24 | 25 | Input: [-1,-100,3,99] and k = 2 26 | Output: [3,99,-1,-100] 27 | Explanation: 28 | rotate 1 steps to the right: [99,-1,-100,3] 29 | rotate 2 steps to the right: [3,99,-1,-100] 30 | Note: 31 | 32 | Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 33 | Could you do it in-place with O(1) extra space? 34 | 35 | */ 36 | 37 | /* 38 | 1. rotate all 39 | 1. rotate 2 sides: < k or >= k 40 | */ 41 | class Solution { 42 | public void rotate(int[] nums, int k) { 43 | int n = nums.length; 44 | k = k % n; 45 | if (k == 0) return; 46 | // rotate all 47 | rotateByRange(nums, 0, n - 1); 48 | // rotate side 49 | rotateByRange(nums, 0, k - 1); 50 | rotateByRange(nums, k, n - 1); 51 | } 52 | 53 | private void rotateByRange(int[] nums, int x, int y) { 54 | while (x >= 0 && x < y) { 55 | int temp = nums[x]; 56 | nums[x] = nums[y]; 57 | nums[y] = temp; 58 | x++; 59 | y--; 60 | } 61 | } 62 | } 63 | ``` -------------------------------------------------------------------------------- /Java/19. Remove Nth Node From End of List.java: -------------------------------------------------------------------------------- 1 | M 2 | tags: Linked List, Two Pointers 3 | time: O(n) 4 | space: O(1) 5 | 6 | #### Two Pointer 7 | - 1 end pointer to define the window based n steps 8 | - 1 pre pointer to track the node before the targeting node 9 | - when end reaches null, remove nth node: link pre and head.next 10 | 11 | ``` 12 | /* 13 | Given a linked list, remove the nth node from the end of list and return its head. 14 | 15 | Note 16 | The minimum number of nodes in list is n. 17 | 18 | Example 19 | Given linked list: 1->2->3->4->5->null, and n = 2. 20 | After removing the second node from the end, the linked list becomes 1->2->3->5->null. 21 | Challenge 22 | O(n) time 23 | 24 | Tags Expand 25 | Two Pointers Linked List 26 | 27 | 28 | */ 29 | /** 30 | * Definition for singly-linked list. 31 | * public class ListNode { 32 | * int val; 33 | * ListNode next; 34 | * ListNode(int x) { val = x; } 35 | * } 36 | */ 37 | /* 38 | Thoughts: 39 | Find starting piont of the window, and keep moving forward, until candidate reach end. 40 | */ 41 | class Solution { 42 | public ListNode removeNthFromEnd(ListNode head, int n) { 43 | ListNode dummy = new ListNode(-1), pre = new ListNode(0); 44 | pre.next = head; 45 | dummy = pre; 46 | 47 | // Establish window 48 | ListNode end = head; // end node 49 | while (n--> 0 && end != null) end = end.next; 50 | 51 | // move window 52 | while (end != null) { 53 | end = end.next; 54 | pre = pre.next; 55 | head = head.next; 56 | } 57 | // remove nth node 58 | pre.next = head.next; 59 | return dummy.next; 60 | } 61 | } 62 | 63 | ``` -------------------------------------------------------------------------------- /Java/20. Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: String, Stack 3 | time: O(n) 4 | space: O(n) 5 | 6 | #### Stack 7 | - 剥皮过程。解铃还须系铃人 8 | - 左边的外皮'{['在stack底部 9 | - 右边的外皮应该和stack顶上的左外皮一一对应 10 | 11 | ``` 12 | /* 13 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 14 | 15 | Example 16 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 17 | 18 | Tags Expand 19 | Stack 20 | */ 21 | 22 | class Solution { 23 | public boolean isValid(String s) { 24 | if (s == null) return true; 25 | if (s.length() % 2 != 0) return false; 26 | 27 | Stack stack = new Stack<>(); 28 | for (char c : s.toCharArray()) { 29 | if (stack.isEmpty() || (c == '(' || c == '{' || c == '[')) stack.push(c); 30 | else if (validate(stack.peek(), c)) stack.pop(); 31 | else return false; 32 | } 33 | return stack.isEmpty(); 34 | } 35 | 36 | private boolean validate(char a, char b) { 37 | if (a == '(') return b == ')'; 38 | if (a == '{') return b == '}'; 39 | if (a == '[') return b == ']'; 40 | return false; 41 | } 42 | } 43 | 44 | 45 | ``` -------------------------------------------------------------------------------- /Java/202. Happy Number.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Hash Table, Math 3 | time: O(m), m iterations 4 | space: O(m), m number in set 5 | 6 | Basic Implementation of the requirements. 7 | 8 | 用HashSet存查看过的数值。若重复,return false. 9 | 10 | ``` 11 | /* 12 | Write an algorithm to determine if a number is happy. 13 | 14 | A happy number is a number defined by the following process: 15 | Starting with any positive integer, replace the number by the sum of the squares of its digits, 16 | and repeat the process until the number equals 1 (where it will stay), 17 | or it loops endlessly in a cycle which does not include 1. 18 | Those numbers for which this process ends in 1 are happy numbers. 19 | 20 | Example 21 | 19 is a happy number 22 | 23 | 1^2 + 9^2 = 82 24 | 8^2 + 2^2 = 68 25 | 6^2 + 8^2 = 100 26 | 1^2 + 0^2 + 0^2 = 1 27 | Tags Expand 28 | Hash Table Mathematics 29 | */ 30 | /* 31 | User HashMap/HashSet to record the calculated number 32 | */ 33 | class Solution { 34 | public boolean isHappy(int n) { 35 | Set set = new HashSet<>(); 36 | long sum = n; 37 | set.add(sum); 38 | 39 | while(sum != 1) { 40 | sum = process(sum); // 1 + 81 = 82 41 | if(!set.add(sum)) return false; // 82, 68, 100, 1 42 | } 43 | return true; 44 | } 45 | 46 | private long process(long n) { 47 | long sum = 0; 48 | while (n != 0) { 49 | long mod = n % 10; 50 | sum += mod * mod; 51 | n /= 10; 52 | } 53 | return sum; 54 | } 55 | } 56 | 57 | ``` -------------------------------------------------------------------------------- /Java/203. Remove Linked List Elements.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Linked List 3 | 4 | 从linked list 里面去掉所有的 target 5 | 6 | #### Basics 7 | - 如果match: node.next = head.next; 8 | - 如果不match, node 和 head 一起移动 9 | 10 | ``` 11 | /* 12 | Remove all elements from a linked list of integers that have value val. 13 | 14 | Have you met this question in a real interview? Yes 15 | Example 16 | Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5 17 | 18 | Tags Expand 19 | Linked List 20 | */ 21 | 22 | /* 23 | Thoughts: 24 | While loop through. Maintain a parent, so it can be used to skip current node. 25 | */ 26 | 27 | class Solution { 28 | public ListNode removeElements(ListNode head, int val) { 29 | if (head == null) { 30 | return head; 31 | } 32 | ListNode dummy = new ListNode(-1); 33 | dummy.next = head; 34 | ListNode node = dummy; 35 | while (head != null) { 36 | if (head.val == val) { 37 | node.next = head.next; 38 | } else { 39 | node = node.next; 40 | } 41 | head = head.next; 42 | } 43 | 44 | return dummy.next; 45 | } 46 | } 47 | 48 | ``` -------------------------------------------------------------------------------- /Java/205. Isomorphic Strings.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Hash Table 3 | time: O(n) 4 | space: O(n) 5 | 6 | #### HashMap 7 | - check 2 failture cases: 8 | - same key, value not matching 9 | - two key maps to same value 10 | 11 | ``` 12 | /* 13 | Given two strings s and t, determine if they are isomorphic. 14 | 15 | Two strings are isomorphic if the characters in s can be replaced to get t. 16 | 17 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 18 | 19 | For example, 20 | Given "egg", "add", return true. 21 | 22 | Given "foo", "bar", return false. 23 | 24 | Given "paper", "title", return true. 25 | 26 | Note: 27 | You may assume both s and t have the same length. 28 | 29 | Hide Company Tags LinkedIn 30 | Hide Tags Hash Table 31 | Hide Similar Problems (E) Word Pattern 32 | 33 | */ 34 | 35 | class Solution { 36 | public boolean isIsomorphic(String s, String t) { 37 | if (s == null || t == null || s.length() != t.length()) return false; 38 | Map map = new HashMap<>(); 39 | 40 | for (int i = 0; i < s.length(); i++) { 41 | char charS = s.charAt(i), charT = t.charAt(i); 42 | if (map.containsKey(charS)) { 43 | if (map.get(charS) != charT) return false; // same key, value not matching 44 | } else { 45 | if (map.containsValue(charT)) return false; // two key maps to same value 46 | map.put(charS, charT); 47 | } 48 | } 49 | 50 | return true; 51 | } 52 | } 53 | 54 | ``` 55 | -------------------------------------------------------------------------------- /Java/21. Merge Two Sorted Lists.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Linked List 3 | time: O(n) 4 | space: O(1) 5 | 6 | 如题 7 | 8 | #### Basics 9 | - 小的放前。每次比head大小 10 | - while过后,把没完的list一口气接上。 11 | - 一开始建一个node用来跑路, 每次都存node.next = xxx。存一个dummy。用来return dummy.next. 12 | 13 | ``` 14 | /* 15 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 16 | 17 | Example 18 | Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null 19 | 20 | Tags Expand 21 | Linked List 22 | 23 | Thinking process: 24 | 1. Merge sorted list, compare before add to node.next 25 | 2. when any of l1 or l2 is null, break out. 26 | 3. add the non-null list at the end of node. 27 | 4. return dummy.next. 28 | 29 | */ 30 | /** 31 | * Definition for singly-linked list. 32 | * public class ListNode { 33 | * int val; 34 | * ListNode next; 35 | * ListNode(int x) { val = x; } 36 | * } 37 | */ 38 | class Solution { 39 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 40 | ListNode head = new ListNode(0); 41 | ListNode node = head; 42 | 43 | while (l1 != null && l2 != null) { 44 | if (l1.val <= l2.val) { 45 | node.next = l1; 46 | l1 = l1.next; 47 | } else { 48 | node.next = l2; 49 | l2 = l2.next; 50 | } 51 | node = node.next; 52 | } 53 | 54 | if (l1 != null) node.next = l1;; 55 | if (l2 != null) node.next = l2; 56 | return head.next; 57 | } 58 | } 59 | 60 | ``` -------------------------------------------------------------------------------- /Java/217. Contains Duplicate.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, Hash Table 3 | time: O(n) 4 | space: O(1) 5 | 6 | 7 | 无序数组, 找是否有重复element, return true/false. 8 | 9 | #### HashSet 10 | - No brain: HashSet. 11 | - Time O(n), Space O(n) 12 | 13 | #### Sort, Binary Search 14 | - Arrays.sort(x): Time O(nLogN), Space O(1) 15 | - 排序后, 重复数会排在一起, 然后 binary search 16 | 17 | ``` 18 | /* 19 | Given an array of integers, find if the array contains any duplicates. 20 | Your function should return true if any value appears at least twice in the array, 21 | and it should return false if every element is distinct. 22 | */ 23 | 24 | /* 25 | Use a hashSet. Cost: extra space. 26 | */ 27 | class Solution { 28 | public boolean containsDuplicate(int[] nums) { 29 | if (nums == null || nums.length == 0) { 30 | return false; 31 | } 32 | HashSet set = new HashSet<>(); 33 | for (int num : nums) { 34 | if (set.contains(num)) { 35 | return true; 36 | } 37 | set.add(num); 38 | } 39 | return false; 40 | } 41 | } 42 | 43 | /* 44 | Sorry array, nLog(n) 45 | */ 46 | class Solution { 47 | public boolean containsDuplicate(int[] nums) { 48 | if (nums == null || nums.length == 0) { 49 | return false; 50 | } 51 | Arrays.sort(nums); 52 | for (int i = 0; i < nums.length - 1; i++) { 53 | if (nums[i] == nums[i + 1]) { 54 | return true; 55 | } 56 | } 57 | return false; 58 | } 59 | } 60 | ``` -------------------------------------------------------------------------------- /Java/237. Delete Node in a Linked List.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Linked List 3 | 4 | Given Singlely linked list, 删除一个任意node (不能是head node) 5 | 6 | #### Basic 7 | - update node.val 8 | - Link curr.next to curr.next.next 9 | 10 | ``` 11 | /* 12 | LeetCode 13 | Write a function to delete a node (except the tail) 14 | in a singly linked list, given only access to that node. 15 | 16 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and 17 | you are given the third node with value 3, 18 | the linked list should become 1 -> 2 -> 4 after calling your function. 19 | */ 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * public class ListNode { 24 | * int val; 25 | * ListNode next; 26 | * ListNode(int x) { val = x; } 27 | * } 28 | */ 29 | class Solution { 30 | public void deleteNode(ListNode node) { 31 | if (node == null || node.next == null) { 32 | return; 33 | } 34 | node.val = node.next.val; 35 | node.next = node.next.next; 36 | } 37 | } 38 | 39 | ``` -------------------------------------------------------------------------------- /Java/28. Implement strStr().java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Two Pointers, String 3 | 4 | 给两个string A, B, 找一个 B 在 A 种的起始位置. 5 | 6 | #### Two Pointer 7 | - 找到B在A中的起始位置, 然后看一下从这个点开始的substring是否等于B就可以了 8 | - 还挺多坑的, 这些可以帮助优化: 9 | - 1. 当B是“”的时候,也就是能在A的其实位置找到B....index = 0. 10 | - 2. edge condition: 如果 haystack.length() < needle.length() 的话, 必须错, return -1 11 | - 3. 如果在某个index, A后面剩下的长度, 比B的长度短, 也是误解, return -1 12 | 13 | ``` 14 | /* 15 | Implement strStr(). 16 | 17 | Returns the index of the first occurrence of needle in haystack, 18 | or -1 if needle is not part of haystack. 19 | 20 | Hide Company Tags Facebook 21 | Hide Tags Two Pointers String 22 | Hide Similar Problems (H) Shortest Palindrome 23 | 24 | Clarification 25 | Do I need to implement KMP Algorithm in an interview? 26 | 27 | - Not necessary. When this problem occurs in an interview, 28 | the interviewer just want to test your basic implementation ability. 29 | 30 | */ 31 | 32 | class Solution { 33 | public int strStr(String haystack, String needle) { 34 | if (needle == null || needle.length() == 0) { 35 | return 0; 36 | } 37 | if (needle.length() > haystack.length()) { 38 | return -1; 39 | } 40 | int n = haystack.length(); 41 | int m = needle.length(); 42 | for (int i = 0; i < n; i++) { // n(n) 43 | if (n - i < m) { 44 | return -1; 45 | } 46 | if (haystack.charAt(i) != needle.charAt(0)) { 47 | continue; 48 | } 49 | 50 | if (haystack.substring(i, i + m).equals(needle)) { // O(m) 51 | return i; 52 | } 53 | } 54 | return -1; 55 | } 56 | } 57 | 58 | ``` -------------------------------------------------------------------------------- /Java/283. Move Zeroes.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, Two Pointers 3 | time: O(n) 4 | space: O(1) 5 | 6 | Move non-zero elements to front of array; preseve order. 7 | 8 | #### Two Pointers 9 | - Outside pointer that moves in certain condition. 10 | - Save appropirate elements 11 | 12 | ``` 13 | /* 14 | Given an array nums, write a function to move all 0's to the end of it 15 | while maintaining the relative order of the non-zero elements. 16 | 17 | Example: 18 | 19 | Input: [0,1,0,3,12] 20 | Output: [1,3,12,0,0] 21 | Note: 22 | 23 | You must do this in-place without making a copy of the array. 24 | Minimize the total number of operations. 25 | */ 26 | /* 27 | Pick non-zero and assign to front. Use a pointer to track 28 | - Use pointer to move all elements to non-zero index. 29 | - set remaining list -> 0 30 | */ 31 | class Solution { 32 | public void moveZeroes(int[] nums) { 33 | if (nums == null) return; 34 | int index = 0, n = nums.length; 35 | for (int i = 0; i < n; i++) { 36 | if (nums[i] != 0) nums[index++] = nums[i]; 37 | } 38 | for (int i = index; i < n; i++) { 39 | nums[i] = 0; 40 | } 41 | } 42 | } 43 | ``` -------------------------------------------------------------------------------- /Java/303. Range Sum Query - Immutable.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: DP, PreSum 3 | time: O(1) query, O(n) setup 4 | space: O(n) 5 | 6 | 给一串数字, 求sumRange. 7 | 8 | #### PreSum 9 | - pre sum 的definition 10 | - preSum也是dp[]一种最简易的形式把. 11 | - dp[i], preSum[i]: 前(i-1)个元素的和. 12 | 13 | ``` 14 | /** 15 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 16 | 17 | Example: 18 | Given nums = [-2, 0, 3, -5, 2, -1] 19 | 20 | sumRange(0, 2) -> 1 21 | sumRange(2, 5) -> -1 22 | sumRange(0, 5) -> -3 23 | Note: 24 | You may assume that the array does not change. 25 | There are many calls to sumRange function. 26 | 27 | */ 28 | 29 | class NumArray { 30 | int[] preSum = null; 31 | public NumArray(int[] nums) { 32 | if (nums == null || nums.length == 0) return; 33 | int n = nums.length; 34 | preSum = new int[n]; 35 | preSum[0] = nums[0]; 36 | for(int i = 1; i < n; i++) preSum[i] = preSum[i - 1] + nums[i]; 37 | } 38 | 39 | public int sumRange(int i, int j) { 40 | if (i == 0) return preSum[j]; 41 | return preSum[j] - preSum[i - 1]; 42 | } 43 | } 44 | 45 | /** 46 | * Your NumArray object will be instantiated and called as such: 47 | * NumArray obj = new NumArray(nums); 48 | * int param_1 = obj.sumRange(i,j); 49 | */ 50 | ``` -------------------------------------------------------------------------------- /Java/319. Bulb Switcher.java: -------------------------------------------------------------------------------- 1 | M 2 | tags: Math, Brainteaser 3 | time: O(1) 4 | space: O(1) 5 | 6 | #### Brainteaser 7 | - https://leetcode.com/problems/bulb-switcher/discuss/77104/Math-solution.. 8 | 9 | #### Brutle: 10 | - if just impl, it take O(n^2): 11 | - repating: some pos are toggled mutiple times: if we know total times, easy to determin each pos. 12 | - loop over [2, n], count times on each index 13 | 14 | ``` 15 | 16 | /* 17 | 18 | There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds. 19 | 20 | Example: 21 | 22 | Input: 3 23 | Output: 1 24 | Explanation: 25 | At first, the three bulbs are [off, off, off]. 26 | After first round, the three bulbs are [on, on, on]. 27 | After second round, the three bulbs are [on, off, on]. 28 | After third round, the three bulbs are [on, off, off]. 29 | 30 | So you should return 1, because there is only one bulb is on. 31 | */ 32 | 33 | /* 34 | Brain teaser 35 | */ 36 | class Solution { 37 | public int bulbSwitch(int n) { 38 | return (int)Math.sqrt(n); 39 | } 40 | } 41 | ``` -------------------------------------------------------------------------------- /Java/346. Moving Average from Data Stream.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Design, Queue, Sliding Window 3 | time: O(1) for `next()` 4 | space: O(size) for fixed storage 5 | 6 | 给一个interface, design一个structure, 能够计算moving window average. 7 | 8 | #### Queue 9 | - 读懂题目, 注意average 和 window 的处理. 10 | - 简单的queue.size() comparison 11 | - Note: if we it is calculate moving-window-product, better to use deque :) 12 | - Sliding window? 13 | - It has the spirit of slinding window: 1) maintain a range; 2) check range size `if (queue.size() > size)` 14 | - Though, the solution must use a data structure to store data; it is not the traditional sliding window type of `left/right` pointer problem 15 | 16 | ``` 17 | /** 18 | Given a stream of integers and a window size, 19 | calculate the moving average of all integers in the sliding window. 20 | 21 | For example, 22 | MovingAverage m = new MovingAverage(3); 23 | m.next(1) = 1 24 | m.next(10) = (1 + 10) / 2 25 | m.next(3) = (1 + 10 + 3) / 3 26 | m.next(5) = (10 + 3 + 5) / 3 27 | */ 28 | 29 | class MovingAverage { 30 | double sum; 31 | int size; 32 | Queue queue; 33 | 34 | /** Initialize your data structure here. */ 35 | public MovingAverage(int size) { 36 | this.sum = 0.0; 37 | this.size = size; 38 | this.queue = new LinkedList<>(); 39 | } 40 | 41 | public double next(int val) { 42 | sum += val; 43 | queue.offer(val); 44 | if (queue.size() > size) sum -= queue.poll(); 45 | return sum / queue.size(); 46 | } 47 | } 48 | 49 | /** 50 | * Your MovingAverage object will be instantiated and called as such: 51 | * MovingAverage obj = new MovingAverage(size); 52 | * double param_1 = obj.next(val); 53 | */ 54 | ``` -------------------------------------------------------------------------------- /Java/367. Valid Perfect Square.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Math, Binary Search 3 | time: O(logN) 4 | space: O(1) 5 | 6 | #### Binary找sqrt 7 | - binary search template: mid+1, mid-1, `start <= end` 8 | - define index as long. 9 | 10 | ``` 11 | /* 12 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 13 | 14 | Note: Do not use any built-in library function such as sqrt. 15 | 16 | Example 1: 17 | 18 | Input: 16 19 | Returns: True 20 | Example 2: 21 | 22 | Input: 14 23 | Returns: False 24 | */ 25 | 26 | /* 27 | Thoughts: 28 | Find a number x that x * x == num. x = [0 ~ num] 29 | Binary search [0 ~ num] 30 | */ 31 | /* 32 | - Find a number n, that n*n == num 33 | - Make it faster, use binary search 34 | - End state: (n-1)^2 < num, and n^2 > num 35 | */ 36 | class Solution { 37 | public boolean isPerfectSquare(int num) { 38 | long start = 0, end = num; 39 | while (start <= end) { 40 | long mid = start + (end - start) / 2; 41 | long sqrt = mid * mid; 42 | if (sqrt == num) return true; 43 | else if (sqrt < num) start = mid + 1; 44 | else end = mid - 1; 45 | } 46 | return false; 47 | } 48 | } 49 | ``` -------------------------------------------------------------------------------- /Java/383. Ransom Note.java: -------------------------------------------------------------------------------- 1 | E 2 | 1558026139 3 | tags:String, Basic Implementation 4 | 5 | count chars in int[256] 6 | 7 | ``` 8 | /* 9 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 10 | 11 | Each letter in the magazine string can only be used once in your ransom note. 12 | 13 | Note: 14 | You may assume that both strings contain only lowercase letters. 15 | 16 | canConstruct("a", "b") -> false 17 | canConstruct("aa", "ab") -> false 18 | canConstruct("aa", "aab") -> true 19 | */ 20 | 21 | /* 22 | count ransom note letter occurrence, and count magazine letters 23 | compare occurrence 24 | edge: null ransom -> true; null or shorter magazine, false 25 | */ 26 | class Solution { 27 | public boolean canConstruct(String ransomNote, String magazine) { 28 | if (ransomNote == null) return true; 29 | if (magazine == null || magazine.length() < ransomNote.length()) return false; 30 | 31 | int[] count = new int[256]; 32 | for (char c : magazine.toCharArray()) { 33 | count[c]++; 34 | } 35 | 36 | for (char c : ransomNote.toCharArray()) { 37 | count[c]--; 38 | if (count[c] < 0) { 39 | return false; 40 | } 41 | } 42 | 43 | return true; 44 | } 45 | } 46 | 47 | ``` -------------------------------------------------------------------------------- /Java/410. Split Array Largest Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. 3 | 4 | Note: 5 | If n is the length of array, assume the following constraints are satisfied: 6 | 7 | 1 ≤ n ≤ 1000 8 | 1 ≤ m ≤ min(50, n) 9 | Examples: 10 | 11 | Input: 12 | nums = [7,2,5,10,8] 13 | m = 2 14 | 15 | Output: 16 | 18 17 | 18 | Explanation: 19 | There are four ways to split nums into two subarrays. 20 | The best way is to split it into [7,2,5] and [10,8], 21 | where the largest sum among the two subarrays is only 18. 22 | */ -------------------------------------------------------------------------------- /Java/414. Third Maximum Number.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, PriorityQueue 3 | 4 | #### pq 5 | - 注意special case: `when less than 3 items, return maximum` 6 | - PQ是natural order: remain peek() will be the 3rd maximum 7 | 8 | 9 | ``` 10 | /* 11 | 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). 12 | 13 | Example 1: 14 | Input: [3, 2, 1] 15 | 16 | Output: 1 17 | 18 | Explanation: The third maximum is 1. 19 | Example 2: 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 | Example 3: 26 | Input: [2, 2, 3, 1] 27 | 28 | Output: 1 29 | 30 | Explanation: Note that the third maximum here means the third maximum distinct number. 31 | Both numbers with value 2 are both considered as second maximum. 32 | */ 33 | 34 | class Solution { 35 | public int thirdMax(int[] nums) { 36 | PriorityQueue pq = new PriorityQueue<>(); 37 | for (int num : nums) { 38 | if (!pq.contains(num)) { 39 | pq.offer(num); 40 | if (pq.size() > 3) pq.poll(); 41 | } 42 | } 43 | // if no third maximum, return max 44 | if (pq.size() < 3) { 45 | while (pq.size() > 1) pq.poll(); 46 | } 47 | return pq.peek(); 48 | } 49 | } 50 | ``` -------------------------------------------------------------------------------- /Java/485. Max Consecutive Ones.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, Basic Implementation 3 | time: O(n) 4 | space: O(1) 5 | 6 | - preserve max 7 | - 清零count 8 | 9 | ``` 10 | /* 11 | Given a binary array, find the maximum number of consecutive 1s in this array. 12 | 13 | Example 1: 14 | Input: [1,1,0,1,1,1] 15 | Output: 3 16 | Explanation: The first two digits or the last three digits are consecutive 1s. 17 | The maximum number of consecutive 1s is 3. 18 | Note: 19 | 20 | The input array will only contain 0 and 1. 21 | The length of input array is a positive integer and will not exceed 10,000 22 | */ 23 | 24 | /* 25 | Thoughts: 26 | Maintain a min outsize, loop through all numbers. 27 | 28 | */ 29 | 30 | class Solution { 31 | public int findMaxConsecutiveOnes(int[] nums) { 32 | if (nums == null || nums.length == 0) { 33 | return 0; 34 | } 35 | int maxCount = 0; 36 | int count = 0; 37 | for (int i = 0; i < nums.length; i++) { 38 | if (nums[i] == 0) { 39 | maxCount = Math.max(count, maxCount); 40 | count = 0; 41 | } else { 42 | count++; 43 | } 44 | } 45 | return Math.max(count, maxCount); 46 | } 47 | } 48 | 49 | ``` -------------------------------------------------------------------------------- /Java/557. Reverse Words in a String III.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: String 3 | 4 | 给一个String, 里面的Word被single space split开来, 目的是reverse里面所有的Word, 但preserve Word 和 space order. 5 | 6 | #### Reverse function 7 | - Reverse Words in a String II 的降级版, 去掉第一个overall reverse就好了 8 | 9 | ``` 10 | /* 11 | Given a string, you need to reverse the order of characters 12 | in each word within a sentence while still preserving whitespace and initial word order. 13 | 14 | Example 1: 15 | Input: "Let's take LeetCode contest" 16 | Output: "s'teL ekat edoCteeL tsetnoc" 17 | Note: In the string, each word is separated by single space and there will not be any extra space in the string. 18 | 19 | 20 | */ 21 | 22 | class Solution { 23 | public String reverseWords(String s) { 24 | if (s == null || s.length() <= 1) { 25 | return s; 26 | } 27 | char[] str = s.toCharArray(); 28 | int start = 0; 29 | for (int i = 0; i < str.length; i++) { 30 | if (str[i] == ' ') { 31 | reverse(str, start, i - 1); 32 | start = i + 1; 33 | } else if (i == str.length - 1) { 34 | reverse(str, start, i); 35 | } 36 | }//end for 37 | 38 | return String.valueOf(str); 39 | } 40 | 41 | public void reverse(char[] s, int start, int end) { 42 | while (start < end) { 43 | char temp = s[start]; 44 | s[start] = s[end]; 45 | s[end] = temp; 46 | start++; 47 | end--; 48 | } 49 | } 50 | } 51 | ``` -------------------------------------------------------------------------------- /Java/605. Can Place Flowers.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, Greedy 3 | time: O(n) 4 | space: O(1) 5 | 6 | #### Array 7 | - just check flowerbed[i-1] & flowerbed[i+1] and count 8 | 9 | ``` 10 | /* 11 | Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die. 12 | 13 | Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule. 14 | 15 | Example 1: 16 | Input: flowerbed = [1,0,0,0,1], n = 1 17 | Output: True 18 | Example 2: 19 | Input: flowerbed = [1,0,0,0,1], n = 2 20 | Output: False 21 | Note: 22 | The input array won't violate no-adjacent-flowers rule. 23 | The input array size is in the range of [1, 20000]. 24 | n is a non-negative integer which won't exceed the input array size. 25 | */ 26 | 27 | /* 28 | Greedy,just check flowerbed[i-1] and move on 29 | */ 30 | class Solution { 31 | public boolean canPlaceFlowers(int[] flowerbed, int n) { 32 | if (flowerbed.length == 0 || n <= 0) return true; 33 | int m = flowerbed.length; 34 | for (int i = 0; i < m; i++) { 35 | if (flowerbed[i] == 1) continue; 36 | int lastVal = i == 0 ? 0 : flowerbed[i-1]; 37 | int nextval = i == m-1? 0: flowerbed[i+1]; 38 | if (lastVal == 0 && nextval == 0) { 39 | flowerbed[i] = 1; 40 | n--; 41 | } 42 | if (n <= 0) return true; 43 | } 44 | 45 | return false; 46 | } 47 | } 48 | ``` -------------------------------------------------------------------------------- /Java/67. Add Binary.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Math, String, Two Pointers 3 | 4 | #### Two Pointers 5 | - 注意加法结果的位置. 6 | - Use two pointers i, j to track the 2 strings 7 | - Add when i and j are applicable. While (i >= 0 || j >= 0) 8 | - `StringBuffer.insert(0, x);` 9 | - handle carry 10 | 11 | #### reverse 12 | - Reverse string -> Convert to Integer List, add up -> Convert back to string 13 | - pointer 从前向后, 所以只需要 1个pointer. 14 | - 操作复杂, 如上, 证明可以解决. 没必要reverse. 15 | 16 | #### Incorrect: convert to Integer 17 | 把binary换成数字作加法. 如果input很大,那么很可能int,long都hold不住。不保险。 18 | 19 | ``` 20 | /* 21 | Given two binary strings, return their sum (also a binary string). 22 | 23 | The input strings are both non-empty and contains only characters 1 or 0. 24 | 25 | Example 1: 26 | 27 | Input: a = "11", b = "1" 28 | Output: "100" 29 | Example 2: 30 | 31 | Input: a = "1010", b = "1011" 32 | Output: "10101" 33 | */ 34 | public class Solution { 35 | public String addBinary(String a, String b) { 36 | StringBuilder sb = new StringBuilder(); 37 | int i = a.length() - 1, j = b.length() -1, carry = 0; 38 | while (i >= 0 || j >= 0) { 39 | int sum = carry; 40 | if (i >= 0) sum += a.charAt(i--) - '0'; 41 | if (j >= 0) sum += b.charAt(j--) - '0'; 42 | sb.insert(0, sum % 2); 43 | carry = sum / 2; 44 | } 45 | if (carry != 0) sb.insert(0, carry); 46 | return sb.toString(); 47 | } 48 | } 49 | 50 | /* 51 | Thoughts: 52 | Can't just convert to int because of Integer.MAX_VALUE limitation. 53 | Convert to char, and add up all chars 54 | */ 55 | 56 | 57 | 58 | ``` 59 | -------------------------------------------------------------------------------- /Java/771. Jewels and Stones.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Hash Table 3 | time: O(n) 4 | space: O(n) 5 | 6 | - 给J 和 S两个string. J里的character是unique 的珠宝, S 里面的character包含珠宝和石头. 找S里面有多少珠宝 7 | - Basic HashSet 8 | 9 | ``` 10 | /* 11 | You're given strings J representing the types of stones that are jewels, 12 | and S representing the stones you have. Each character in S is a type of stone you have. 13 | You want to know how many of the stones you have are also jewels. 14 | 15 | The letters in J are guaranteed distinct, and all characters in J and S are letters. 16 | Letters are case sensitive, so "a" is considered a different type of stone from "A". 17 | 18 | Example 1: 19 | 20 | Input: J = "aA", S = "aAAbbbb" 21 | Output: 3 22 | Example 2: 23 | 24 | Input: J = "z", S = "ZZ" 25 | Output: 0 26 | Note: 27 | 28 | S and J will consist of letters and have length at most 50. 29 | The characters in J are distinct. 30 | */ 31 | 32 | /* 33 | Thoughts: 34 | Have jewels in set. Iterate over S to check existance and count. 35 | O(m + n), m = J.length(), n = S.length() 36 | */ 37 | class Solution { 38 | public int numJewelsInStones(String J, String S) { 39 | if (J == null || J.length() == 0 || S == null || S.length() == 0) { 40 | return 0; 41 | } 42 | int m = J.length(); 43 | Set set = new HashSet<>(); 44 | int count = 0; 45 | for (char c : J.toCharArray()) { 46 | set.add(c); 47 | } 48 | for (char c : S.toCharArray()) { 49 | count += set.contains(c) ? 1 : 0; 50 | } 51 | return count; 52 | } 53 | } 54 | ``` -------------------------------------------------------------------------------- /Java/852. Peak Index in a Mountain Array.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Binary Search 3 | time: O(logn) 4 | space: O(1) 5 | 6 | #### Binary Search 7 | - binary search to find A[i-1] < A[i] < A[i+1] 8 | - if [mid-1] < [mid+1], on left slope, start = mid 9 | - if [mid-1] > [mid+1], on right slope, end = mid 10 | - init: start == 1, end = n - 2; 11 | 12 | ``` 13 | /** 14 | Let's call an array A a mountain if the following properties hold: 15 | 16 | A.length >= 3 17 | There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 18 | Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. 19 | 20 | Example 1: 21 | 22 | Input: [0,1,0] 23 | Output: 1 24 | Example 2: 25 | 26 | Input: [0,2,1,0] 27 | Output: 1 28 | Note: 29 | 30 | 3 <= A.length <= 10000 31 | 0 <= A[i] <= 10^6 32 | A is a mountain, as defined above. 33 | */ 34 | 35 | /* 36 | - binary search to find A[i-1] < A[i] < A[i+1] 37 | - init: start == 1, end = n - 2; 38 | - if [mid-1] < [mid+1], on left slope, start = mid 39 | - if [mid-1] > [mid+1], on right slope, end = mid 40 | */ 41 | class Solution { 42 | public int peakIndexInMountainArray(int[] A) { 43 | int start = 1, end = A.length - 2; 44 | int mid = start + (end - start)/2; 45 | while (start + 1 < end) { 46 | mid = start + (end - start)/2; 47 | if (A[mid-1] < A[mid] && A[mid] > A[mid+1]) return mid; 48 | else if (A[mid-1] < A[mid+1]) start = mid; 49 | else if (A[mid-1] > A[mid+1]) end = mid; 50 | } 51 | return A[start] < A[end] ? end : start; 52 | } 53 | } 54 | 55 | ``` -------------------------------------------------------------------------------- /Java/896. Monotonic Array.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array 3 | 4 | basic implementation 5 | 6 | ``` 7 | 8 | /** 9 | An array is monotonic if it is either monotone increasing or monotone decreasing. 10 | 11 | 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]. 12 | 13 | Return true if and only if the given array A is monotonic. 14 | 15 | 16 | 17 | Example 1: 18 | 19 | Input: [1,2,2,3] 20 | Output: true 21 | Example 2: 22 | 23 | Input: [6,5,4,4] 24 | Output: true 25 | Example 3: 26 | 27 | Input: [1,3,2] 28 | Output: false 29 | Example 4: 30 | 31 | Input: [1,2,4,5] 32 | Output: true 33 | Example 5: 34 | 35 | Input: [1,1,1] 36 | Output: true 37 | 38 | 39 | Note: 40 | 41 | 1 <= A.length <= 50000 42 | -100000 <= A[i] <= 100000 43 | */ 44 | 45 | 46 | class Solution { 47 | public boolean isMonotonic(int[] A) { 48 | return verify(A, true) || verify(A, false); 49 | } 50 | 51 | private boolean validate(int a, int b, boolean incline) { 52 | if (incline) return a <= b; 53 | return a >= b; 54 | } 55 | 56 | private boolean verify(int[] A, boolean incline) { 57 | for (int i = 0; i < A.length - 1; i++) { 58 | if (!validate(A[i], A[i + 1], incline)) { 59 | return false; 60 | } 61 | } 62 | return true; 63 | } 64 | } 65 | ``` -------------------------------------------------------------------------------- /Java/9. Palindrome Number.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Math 3 | 4 | #### Reverse half of the number 5 | - build reversed integer 直到midpoint, where x <= reverse 6 | - 如果input双数: x == reverse 7 | - 如果input单数 (而且x>reverse): x == reverse/10 8 | 9 | #### Consider palindrome 10 | - optionA: compare digit by digit 11 | - optionB: reverse half of the string/int, and compare with other half. 12 | 13 | 14 | 15 | 16 | ``` 17 | 18 | /* 19 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 20 | 21 | Example 1: 22 | 23 | Input: 121 24 | Output: true 25 | Example 2: 26 | 27 | Input: -121 28 | Output: false 29 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 30 | Example 3: 31 | 32 | Input: 10 33 | Output: false 34 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 35 | Follow up: 36 | 37 | Coud you solve it without converting the integer to a string? 38 | */ 39 | 40 | // Build reverse until mid point 41 | class Solution { 42 | public boolean isPalindrome(int x) { 43 | if (x < 0 || (x != 0 && x % 10 == 0)) return false; 44 | int reverse = 0; 45 | while (x > reverse){ 46 | reverse = reverse * 10 + x % 10; 47 | x = x/10; 48 | } 49 | return (x == reverse || x == reverse / 10); 50 | } 51 | } 52 | ``` -------------------------------------------------------------------------------- /Java/977. Squares of a Sorted Array.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Array, Two Pointers 3 | time: O(n) 4 | space: O(n) 5 | 6 | #### Two Pointers 7 | - negative index i, positive index j 8 | 9 | ``` 10 | 11 | /* 12 | Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. 13 | 14 | Example 1: 15 | 16 | Input: [-4,-1,0,3,10] 17 | Output: [0,1,9,16,100] 18 | Example 2: 19 | 20 | Input: [-7,-3,2,3,11] 21 | Output: [4,9,9,49,121] 22 | 23 | 24 | Note: 25 | 26 | 1 <= A.length <= 10000 27 | -10000 <= A[i] <= 10000 28 | A is sorted in non-decreasing order. 29 | */ 30 | 31 | class Solution { 32 | public int[] sortedSquares(int[] A) { 33 | if (A == null || A.length == 0) return A; 34 | int n = A.length; 35 | int i = findPos(A), j = i + 1; 36 | int index = 0; 37 | int[] result = new int[n]; 38 | 39 | while (i >= 0 || j < n) { 40 | int squareI = i < 0 ? Integer.MAX_VALUE : A[i] * A[i]; 41 | int squareJ = j >= n ? Integer.MAX_VALUE : A[j] * A[j]; 42 | if (squareI < squareJ) { 43 | result[index++] = squareI; 44 | i--; 45 | } else { 46 | result[index++] = squareJ; 47 | j++; 48 | } 49 | } 50 | return result; 51 | } 52 | 53 | public int findPos(int[] A) { 54 | for (int i = 0; i < A.length; i++) { 55 | if (A[i] >= 0) return i - 1; 56 | } 57 | return 0; 58 | } 59 | } 60 | ``` 61 | -------------------------------------------------------------------------------- /Java/Add Digits.java: -------------------------------------------------------------------------------- 1 | E 2 | 1519709532 3 | tags: Math 4 | 5 | 方法1: 普通做法就是按照题意, double-while loop把数字加起来. 第一层循环是O(n), 然后第二层循环就少很多数位, overall O(n) 6 | 7 | 方法2: 找数学规律, 每过9个数字, 取mod就会开始重复, 所以给所有数字取mod 就可以间接找到答案. O(1) 8 | 9 | ``` 10 | /* 11 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 12 | 13 | For example: 14 | 15 | Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 16 | 17 | Follow up: 18 | Could you do it without any loop/recursion in O(1) runtime? 19 | */ 20 | 21 | /* 22 | Thoughts: 23 | Keep adding until result < 10 24 | Double-while loop: start with a num, calculate result, then num = result. 25 | */ 26 | class Solution { 27 | public int addDigits(int num) { 28 | if (num < 10) { 29 | return num; 30 | } 31 | while (num > 9) { 32 | int temp = 0; 33 | while (num != 0) { 34 | temp += num % 10; 35 | num = num / 10; 36 | } 37 | num = temp; 38 | } 39 | return num; 40 | } 41 | } 42 | 43 | class Solution { 44 | public int addDigits(int num) { 45 | return (num - 1) % 9 + 1; 46 | } 47 | } 48 | ``` -------------------------------------------------------------------------------- /Java/Classical Binary Search.java: -------------------------------------------------------------------------------- 1 | E 2 | 1521694570 3 | tags: Binary Search 4 | 5 | #### Binary Search Template 6 | - while: start + 1 < end 7 | - mid = start + (end - start) / 2; 8 | - 根据mid作比较 9 | - 末尾double check start, end. 10 | 11 | 12 | ``` 13 | /* 14 | Find any position of a target number in a sorted array. 15 | Return -1 if target does not exist. 16 | 17 | Example 18 | Given [1, 2, 2, 4, 5, 5]. 19 | 20 | For target = 2, return 1 or 2. 21 | 22 | For target = 5, return 4 or 5. 23 | 24 | For target = 6, return -1. 25 | 26 | Challenge 27 | O(logn) time 28 | 29 | Tags Expand 30 | Binary Search 31 | */ 32 | 33 | /* 34 | Thoughts: classic 35 | start,mid,end 36 | */ 37 | public class Solution { 38 | public int findPosition(int[] nums, int target) { 39 | if (nums == null || nums.length == 0) { 40 | return -1; 41 | } 42 | int start = 0; 43 | int end = nums.length - 1; 44 | while (start + 1 < end) { 45 | int mid = start + ((end - start) >> 1); 46 | if (nums[mid] == target) { 47 | return mid; 48 | } else if (nums[mid] < target) { 49 | start = mid; 50 | } else { 51 | end = mid; 52 | } 53 | } 54 | 55 | if (nums[start] == target) { 56 | return start; 57 | } 58 | if (nums[end] == target) { 59 | return end; 60 | } 61 | return -1; 62 | } 63 | } 64 | 65 | ``` 66 | -------------------------------------------------------------------------------- /Java/Convert Integer A to Integer B.java: -------------------------------------------------------------------------------- 1 | E 2 | 1522132721 3 | tags: Bit Manipulation 4 | 5 | 把Integer A 转换成 Integer B 需要改变多少bits? 6 | 7 | #### Bit Manipulation 8 | - a^b 显示出bit format里面有不同binary code的数位. 9 | - 每次 (a^b)>>i 移动i位之后, 再 & 1时其实是指留下这一位的数字. 10 | - count 11 | - 其实用到了 ^ 找不同的bit, >> 移位, &1 mask 12 | 13 | ``` 14 | /* 15 | LintCode 16 | Determine the number of bits required to convert integer A to integer B 17 | 18 | Example 19 | Given n = 31, m = 14,return 2 20 | 21 | (31)10=(11111)2 22 | 23 | (14)10=(01110)2 24 | 25 | Tags Expand 26 | Cracking The Coding Interview Bit Manipulation Binary Representation 27 | 28 | Thinking process: 29 | Assume the integer is 32 bit. 30 | XOR a and b, shift by 1 bit everytime -> want to check the XORed value at index 0 : just & 1 will do. 31 | Count the above calculated result: how many bit difference do a and b have. 32 | */ 33 | 34 | class Solution { 35 | /** 36 | *@param a, b: Two integer 37 | *return: An integer 38 | */ 39 | public static int bitSwapRequired(int a, int b) { 40 | int count = 0; 41 | for (int i = 0; i < 32; i++) { 42 | count += (a ^ b) >> i & 1; 43 | } 44 | return count; 45 | } 46 | }; 47 | 48 | 49 | 50 | ``` -------------------------------------------------------------------------------- /Java/Count 1 in Binary.java: -------------------------------------------------------------------------------- 1 | E 2 | 1522133098 3 | tags: Bit Manipulation 4 | 5 | count 一个 32-bit number binary format 里面有多少1 6 | 7 | #### Bit Manipulation 8 | - shift >> i 9 | - apply mask & 1 10 | 11 | #### Convert to string O(n) space 12 | 可以把integer -> string -> char array. 13 | 14 | ``` 15 | /* 16 | LintCode 17 | Count how many 1 in binary representation of a 32-bit integer. 18 | 19 | Example 20 | Given 32, return 1 21 | 22 | Given 5, return 2 23 | 24 | Given 1023, return 9 25 | 26 | Challenge 27 | If the integer is n bits with m 1 bits. Can you do it in O(m) time? 28 | 29 | Tags Expand 30 | Binary Bit Manipulation 31 | 32 | Thoughts: 33 | 1. break string into char[] 34 | 2. convert char[] into integer using Character.getNumericValue() 35 | 36 | */ 37 | /* 38 | Thoughts: 39 | Shift the 32 bit integer and apply mask 1 40 | */ 41 | public class Solution { 42 | public int countOnes(int num) { 43 | int count = 0; 44 | for (int i = 1; i <= 32; i++) { 45 | count += num >> i & 1; 46 | } 47 | return count; 48 | } 49 | }; 50 | 51 | 52 | 53 | public class Solution { 54 | /** 55 | * @param num: an integer 56 | * @return: an integer, the number of ones in num 57 | */ 58 | public int countOnes(int num) { 59 | if (num < 0) { 60 | return 0; 61 | } 62 | String bits = Integer.toBinaryString(num); 63 | char[] bitArray = bits.toCharArray(); 64 | int sum = 0; 65 | for (int i = 0; i < bitArray.length; i++) { 66 | sum += Character.getNumericValue(bitArray[i]); 67 | } 68 | return sum; 69 | } 70 | }; 71 | 72 | ``` -------------------------------------------------------------------------------- /Java/Encode and Decode TinyURL.java: -------------------------------------------------------------------------------- 1 | M 2 | 1516430518 3 | tags: Hash Table, Math 4 | 5 | 其实想到了切入点, 是个可难可简单的题目. 这里的encode就是想办法把url存起来, 然后给个 key. 6 | 那么具体怎么做这个key, 简单就可以用一个map, 然后counting. 复杂一点就可以做random letter/number组成key. 7 | 8 | ``` 9 | /* 10 | TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. 11 | 12 | Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. 13 | */ 14 | 15 | /* 16 | Use a hashmap to store. Come up with a method to store keys. 17 | Most easies way, use size of the map as keys 18 | */ 19 | public class Codec { 20 | final String PREFIX = "http://tinyurl.com/"; 21 | final Map map = new HashMap<>(); 22 | // Encodes a URL to a shortened URL. 23 | public String encode(String longUrl) { 24 | final String key = PREFIX + (map.size() + 1); 25 | map.put(key, longUrl); 26 | return key; 27 | } 28 | 29 | // Decodes a shortened URL to its original URL. 30 | public String decode(String shortUrl) { 31 | return map.get(shortUrl); 32 | } 33 | } 34 | 35 | // Your Codec object will be instantiated and called as such: 36 | // Codec codec = new Codec(); 37 | // codec.decode(codec.encode(url)); 38 | ``` -------------------------------------------------------------------------------- /Java/Excel Sheet Column Number.java: -------------------------------------------------------------------------------- 1 | E 2 | 1524455965 3 | tags: Math 4 | 5 | #### Math 6 | - 26位的运算, 根据10位运算去思考 7 | - 'A' - 'A' = 0. 所以 char - 'A' + 1 = 题目里的对应数位 8 | - 或者: 26位运算和10位一样:num += 每位的digit * Math.pow(26, 数位号) 9 | 10 | 11 | ``` 12 | /* 13 | Given a column title as appear in an Excel sheet, 14 | return its corresponding column number. 15 | 16 | For example: 17 | 18 | A -> 1 19 | B -> 2 20 | C -> 3 21 | ... 22 | Z -> 26 23 | AA -> 27 24 | AB -> 28 25 | */ 26 | 27 | /* 28 | Thoughts: 29 | - 26-bits. 30 | - Char array, head char is at most significant index. 31 | - char - 'a' + 1 = number 32 | 33 | */ 34 | class Solution { 35 | public int titleToNumber(String s) { 36 | if (s == null || s.length() == 0) { 37 | return 0; 38 | } 39 | int count = 0; 40 | for (char c : s.toCharArray()) { 41 | int digit = c - 'A' + 1; 42 | count = count * 26 + digit; 43 | } 44 | return count; 45 | } 46 | } 47 | 48 | //3.4.2016 recap 49 | //digit * pow(26, digit position) 50 | public class Solution { 51 | public int titleToNumber(String s) { 52 | if (s == null || s.length() == 0) { 53 | return 0; 54 | } 55 | int num = 0; 56 | for (int i = s.length() - 1; i >= 0; i--) { 57 | int digit = s.charAt(i) - 'A' + 1; 58 | num += digit * Math.pow(26, s.length() - i - 1); 59 | } 60 | return num; 61 | } 62 | } 63 | 64 | ``` -------------------------------------------------------------------------------- /Java/Fast Power.java: -------------------------------------------------------------------------------- 1 | M 2 | 1527969371 3 | tags: DFS, Divide and Conquer 4 | 5 | 如题: Calculate the a^n % b where a, b and n are all 32bit integers. 6 | 7 | #### Divide and Conquer 8 | - a^n可以被拆解成(a*a*a*a....*a), 是乘机形式,而%是可以把每一项都mod一下的。所以就拆开来take mod. 9 | - 这里用个二分的方法,recursively二分下去,直到n/2为0或者1,然后分别对待. 10 | - 注意1: 二分后要conquer,乘积可能大于Integer.MAX_VALUE, 所以用个long. 11 | - 注意2: 要处理n%2==1的情况,二分时候自动省掉了一份 a,要乘一下。 12 | 13 | 14 | ``` 15 | /* 16 | Calculate the a^n % b where a, b and n are all 32bit integers. 17 | 18 | Example 19 | For 2^31 % 3 = 2 20 | 21 | For 100^1000 % 1000 = 0 22 | 23 | Challenge 24 | O(logn) 25 | 26 | Tags Expand 27 | Divide and Conquer 28 | 29 | 30 | */ 31 | 32 | /* 33 | Thoughts: 34 | Learn online: 35 | (a * b) % p = (a % p * b % p) % p 36 | Than mean: a ^ n can be divided into a^(n/2) * a^(n/2), that can be used for recursion: divde and conqure. 37 | 38 | Note: when n is odd number, it cannot be evenly divided into n/2 and n/2. This case needs special treatment: n = n/2 + n/2 + 1; 39 | */ 40 | class Solution { 41 | public int fastPower(int a, int b, int n) { 42 | if (n == 0) { 43 | return 1 % b; 44 | } 45 | if (n == 1) { 46 | return a % b; 47 | } 48 | 49 | long recurPow = fastPower(a, b, n / 2); 50 | recurPow = (recurPow * recurPow) % b; 51 | 52 | if (n % 2 == 1) { 53 | recurPow = recurPow * a % b; 54 | } 55 | 56 | return (int)recurPow; 57 | } 58 | }; 59 | 60 | ``` -------------------------------------------------------------------------------- /Java/Hamming Distance.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | bit: XOR, &, shift>> 4 | 5 | ``` 6 | /* 7 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 8 | 9 | Given two integers x and y, calculate the Hamming distance. 10 | 11 | Note: 12 | 0 ≤ x, y < 231. 13 | 14 | Example: 15 | 16 | Input: x = 1, y = 4 17 | 18 | Output: 2 19 | 20 | Explanation: 21 | 1 (0 0 0 1) 22 | 4 (0 1 0 0) 23 | ↑ ↑ 24 | 25 | The above arrows point to positions where the corresponding bits are different. 26 | */ 27 | 28 | /* 29 | Thoughts: 30 | ^XOR: gives out all the different bits. 31 | Count the 1's by shiftting right and & 1 32 | */ 33 | class Solution { 34 | public int hammingDistance(int x, int y) { 35 | int xor = x ^ y; 36 | int count = 0; 37 | while (xor != 0) { 38 | count += xor & 1; 39 | xor = xor >> 1; 40 | } 41 | return count; 42 | } 43 | } 44 | ``` -------------------------------------------------------------------------------- /Java/HashWithArray.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | 4 | ``` 5 | /* 6 | Self Test: 7 | Implement HashTable with just array and integer. 8 | 9 | Thoughts: 10 | A simple approach is to % size of the array, if the key exist, move 1 slot over. 11 | 12 | A bug will be: when exceeds the size of array, there will be no avialable space, 13 | and it'll run into error. 14 | 15 | Inspired here :http://www.algolist.net/Data_structures/Hash_table/Simple_example 16 | 1. create a entry class. 17 | 2. hash the key, and put Entry into that hased index. 18 | */ 19 | 20 | Class Entry{ 21 | int key; 22 | int value; 23 | public Entry(int key, int value) { 24 | this.key = key; 25 | this.value = value; 26 | } 27 | 28 | public getKey(){ 29 | return this.key; 30 | } 31 | 32 | public getValue() { 33 | return this.value; 34 | } 35 | } 36 | 37 | Class HashMap { 38 | int[] table; 39 | int SIZE = 128; 40 | public HashMap(){ 41 | table = new int[SIZE]; 42 | for (int i = 0; i < SIZE; i++) { 43 | table[i] = null; 44 | } 45 | } 46 | 47 | public void put(int key, int value){ 48 | int hash = key % SIZE; 49 | while (table[hash] != null && table[hash].getKey() != key) { 50 | hash = (hash + 1) % SIZE; 51 | } 52 | table[key] = new Entry(key, value); 53 | } 54 | 55 | public int get(int key) { 56 | int hash = key % SIZE; 57 | while (table[hash] != null && table[hash].getKey() != key) { 58 | hash = (hash + 1) % SIZE; 59 | } 60 | if (table[hash] == null) { 61 | return -1; 62 | } 63 | return table[hash].getValue(); 64 | } 65 | } 66 | 67 | 68 | 69 | ``` -------------------------------------------------------------------------------- /Java/Implement Stack.java: -------------------------------------------------------------------------------- 1 | E 2 | 1525667761 3 | tags: Stack 4 | 5 | 随便用一个data structure, implement stack. 6 | 7 | #### Stack, 先入, 后出 8 | - ArrayList: return/remove ArrayList的末尾项。 9 | - 2 Queues 10 | 11 | ``` 12 | /* 13 | LintCode 14 | 15 | Implement Stack 16 | 17 | Implement a stack. You can use any data structure inside a stack except stack itself to implement it. 18 | 19 | 20 | Example 21 | push(1) 22 | pop() 23 | push(2) 24 | top() // return 2 25 | pop() 26 | isEmpty() // return true 27 | push(3) 28 | isEmpty() // return false 29 | Tags Expand 30 | Array Stack 31 | */ 32 | 33 | /* 34 | Thoughts: 35 | use arraylist and a index tracker - leng 36 | push: add to end 37 | pop: remove end 38 | top: get end. 39 | isEmpty: return length 40 | */ 41 | 42 | class Stack { 43 | private ArrayList list = new ArrayList(); 44 | // Push a new item into the stack 45 | public void push(int x) { 46 | list.add(x); 47 | } 48 | 49 | // Pop the top of the stack 50 | public void pop() { 51 | if (list.size() > 0) { 52 | list.remove(list.size() - 1); 53 | } 54 | } 55 | 56 | // Return the top of the stack 57 | public int top() { 58 | if (list.size() > 0) { 59 | return list.get(list.size() - 1); 60 | } 61 | return -1; 62 | } 63 | 64 | // Check the stack is empty or not. 65 | public boolean isEmpty() { 66 | return list.size() == 0; 67 | } 68 | } 69 | ``` -------------------------------------------------------------------------------- /Java/IndexMatch.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | 有序, 假设有这样的数字:target. 4 | target 左边的数字,一定不比index大,target右边的数字,一定比index大。 5 | 这样可以binary search.O(logn) 6 | 7 | ``` 8 | /* 9 | 来自网上uber面经:给一个有序数组(不含重复),返回任意一个数字,这个数字的值和它的数组下标相等 10 | 11 | 可能的follow up: 12 | 1. 如果含有重复数字怎么办? 13 | 如果有序,也没问题,还是binary search 14 | 15 | 2. 另一种follow up:找这样数字的边界. 16 | 如果存在,那么和index match的一定在一块. 17 | 找到任何一个candiate, 找边界,也可以binary search,只是match的condition不同罢了。 18 | 19 | */ 20 | //Binary search. 21 | import java.io.*; 22 | import java.util.*; 23 | class Solution { 24 | 25 | public int indexMatch(int[] nums) { 26 | if (nums == null || nums.length == 0) { 27 | return -1; 28 | } 29 | 30 | int start = 0; 31 | int end = nums.length - 1; 32 | while (start + 1 < end) { 33 | int mid = start + (end - start)/2; 34 | if (nums[mid] == mid) { 35 | return mid; 36 | } else if (nums[mid] < mid) { 37 | start = mid; 38 | } else {//nums[mid] > mid 39 | end = mid; 40 | } 41 | } 42 | 43 | return -1; 44 | } 45 | 46 | public static void main(String[] args) { 47 | System.out.println("START"); 48 | int[] input = {-1, 0, 1, 3, 5, 8, 9};//return 3 49 | Solution sol = new Solution(); 50 | int rst = sol.indexMatch(input); 51 | System.out.println(rst); 52 | } 53 | } 54 | ``` -------------------------------------------------------------------------------- /Java/Last Position of Target.java: -------------------------------------------------------------------------------- 1 | E 2 | 1525238120 3 | tags: Binary Search 4 | 5 | 给一个sorted integer array, 找target出现的最后的index. array 里有重复数字 6 | 7 | 有重复,不是末尾点,继续binary search 8 | 9 | ``` 10 | 11 | /* 12 | Find the last position of a target number in a sorted array. 13 | Return -1 if target does not exist. 14 | 15 | Example 16 | Given [1, 2, 2, 4, 5, 5]. 17 | 18 | For target = 2, return 2. 19 | 20 | For target = 5, return 5. 21 | 22 | For target = 6, return -1. 23 | 24 | Tags Expand 25 | Binary Search 26 | */ 27 | 28 | /* 29 | Thoughts: 30 | Regular binary search for it. 31 | found condition: A[mid] == target && A[mid + 1] != target 32 | 33 | */ 34 | public class Solution { 35 | /** 36 | * @param A an integer array sorted in ascending order 37 | * @param target an integer 38 | * @return an integer 39 | */ 40 | public int lastPosition(int[] A, int target) { 41 | if (A == null || A.length == 0) { 42 | return -1; 43 | } 44 | int start = 0; 45 | int end = A.length - 1; 46 | int mid; 47 | 48 | while(start + 1 < end) { 49 | mid = start + (end - start)/2; 50 | if (A[mid] == target) { 51 | if (mid + 1 < A.length && A[mid + 1] == target) { 52 | start = mid; 53 | } else { 54 | return mid; 55 | } 56 | } else if (A[mid] < target) { 57 | start = mid; 58 | } else { 59 | end = mid; 60 | } 61 | } 62 | 63 | if (A[end] == target) { 64 | return end; 65 | } else if (A[start] == target) { 66 | return start; 67 | } 68 | 69 | return -1; 70 | } 71 | } 72 | 73 | ``` -------------------------------------------------------------------------------- /Java/Maximum Average Subarray I.java: -------------------------------------------------------------------------------- 1 | E 2 | 1517552169 3 | tags: Array, Subarray 4 | time: O(n) 5 | space: O(1) 6 | 7 | 简单的求sum of fixed window k, 同时求max avg, 结尾求余数就好. 8 | 9 | ``` 10 | /* 11 | Given an array consisting of n integers, find the contiguous subarray of given length k 12 | that has the maximum average value. And you need to output the maximum average value. 13 | 14 | Example 1: 15 | Input: [1,12,-5,-6,50,3], k = 4 16 | Output: 12.75 17 | Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 18 | Note: 19 | 1 <= k <= n <= 30,000. 20 | Elements of the given array will be in the range [-10,000, 10,000]. 21 | */ 22 | 23 | /* 24 | Thoughts: 25 | Given a k as range, find the max sum. 26 | Brutle: use the box, calculate sum one index at a time, and find the max. 27 | No need to add 4 numbers all the time, just minus the leading one and add the new one. 28 | 29 | Note: use double to catch the sum. 30 | */ 31 | class Solution { 32 | public double findMaxAverage(int[] nums, int k) { 33 | if (nums == null || nums.length == 0) { 34 | return 0; 35 | } 36 | double sum = 0; 37 | // init the sum of k items 38 | for (int i = 0; i < k; i++) { 39 | sum += nums[i]; 40 | } 41 | 42 | // calculate 43 | double max = sum; 44 | for (int i = k; i < nums.length; i++) { 45 | max = Math.max(sum, max); 46 | sum = sum - nums[i - k] + nums[i]; 47 | } 48 | max = Math.max(sum, max); 49 | return max / k; 50 | } 51 | } 52 | ``` -------------------------------------------------------------------------------- /Java/Maximum Subarray III.java: -------------------------------------------------------------------------------- 1 | R 2 | 3 | ``` 4 | /* 5 | 6 | Given an array of integers and a number k, 7 | find k non-overlapping subarrays which have the largest sum. 8 | 9 | The number in each subarray should be contiguous. 10 | 11 | Return the largest sum. 12 | 13 | 14 | Example 15 | Given [-1,4,-2,3,-2,3], k=2, return 8 16 | 17 | Note 18 | The subarray should contain at least one number 19 | 20 | Tags Expand 21 | LintCode Copyright Dynamic Programming Subarray Array 22 | */ 23 | 24 | // Should be partition DP 25 | /** 26 | dp[i][j]: max sum for first i items, divided into j parts 27 | dp[n + 1][k + 1] 28 | dp[0][0] = 0; 29 | 30 | dp[i][j] = Math.max(dp[x][j - 1] + maxSubArray(x+1,i)), x = 1 ~ n 31 | http://www.cnblogs.com/lishiblog/p/4183917.html 32 | */ 33 | public class Solution { 34 | public int maxSubArray(int[] nums, int k) { 35 | if (nums == null || nums.length == 0) { 36 | return 0; 37 | } 38 | int n = nums.length; 39 | int[][] dp = new int[n + 1][k + 1]; 40 | // dp[i][0] = 0; 41 | 42 | for (int j = 1; j <= k; j++) { 43 | for (int i = j; i <= n; i++) { // ??? why i = j 44 | dp[i][j] = Integer.MIN_VALUE; 45 | 46 | int endMax = 0; 47 | int max = Integer.MIN_VALUE; 48 | for (int x = i - 1; x >= j - 1; x--) { // ??? why x = i-1, x >= j -1? 49 | endMax = Math.max(nums[x], nums[x] + endMax); 50 | max = Math.max(max, endMax); 51 | dp[i][j] = dp[i][j] < dp[x][j - 1] + max ? dp[x][j - 1] + max : dp[i][j]; 52 | } 53 | } 54 | } 55 | return dp[n][k]; 56 | } 57 | } 58 | 59 | ``` -------------------------------------------------------------------------------- /Java/Number of Digit One.java: -------------------------------------------------------------------------------- 1 | H 2 | 1529474471 3 | tags: Math 4 | 5 | Pure math problem, not quite representative 6 | 7 | Explanation 8 | https://leetcode.com/problems/number-of-digit-one/discuss/64381/4+-lines-O(log-n)-C++JavaPython 9 | 10 | ``` 11 | /* 12 | 13 | Given an integer n, count the total number of digit 1 appearing in all 14 | non-negative integers less than or equal to n. 15 | 16 | Example: 17 | 18 | Input: 13 19 | Output: 6 20 | Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 21 | 22 | */ 23 | 24 | class Solution { 25 | public int countDigitOne(int n) { 26 | int count = 0; 27 | for (long i = 1; i <= n; i *= 10) { 28 | count += (n / i + 8) / 10 * i; 29 | if (n / i % 10 == 1) { 30 | count += n % i + 1; 31 | } 32 | } 33 | return count; 34 | } 35 | } 36 | ``` -------------------------------------------------------------------------------- /Java/O(1) Check Power of 2.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Bit Manipulation 3 | 4 | ``` 5 | 6 | /* 7 | Using O(1) time to check whether an integer n is a power of 2. 8 | Example 9 | For n=4, return true 10 | 11 | For n=5, return false 12 | 13 | Challenge 14 | O(1) time 15 | 16 | Tags Expand 17 | Binary 18 | 19 | Thinking process: 20 | Any integer that's power of 2, follows one pattern. They are all: 1000000000....000 format. 21 | so (n - 1) becomes: 01111111111...111. 22 | If bit-and them togeter, it will be 0. 23 | 24 | */ 25 | 26 | class Solution { 27 | /* 28 | * @param n: An integer 29 | * @return: True or false 30 | */ 31 | public boolean checkPowerOf2(int n) { 32 | if (n <= 0) { 33 | return false; 34 | } 35 | return (n & (n - 1)) == 0; 36 | } 37 | }; 38 | 39 | 40 | 41 | ``` -------------------------------------------------------------------------------- /Java/Power of Two.java: -------------------------------------------------------------------------------- 1 | E 2 | 1516343302 3 | tags: Math, Bit Manipulation 4 | 5 | 跟powerOfThree一样: 可以loop, check mod; 也可以用binary search找合适的数字. 6 | 7 | ``` 8 | /* 9 | Given an integer, write a function to determine if it is a power of two. 10 | */ 11 | 12 | /* 13 | Similar to powerOfThree. Two ways: 1 divide and check mode; 2. binary search 14 | */ 15 | class Solution { 16 | public boolean isPowerOfTwo(int n) { 17 | if (n <= 0) { 18 | return false; 19 | } 20 | while (n != 1) { 21 | if (n % 2 != 0 || n / 2 == 0) { 22 | return false; 23 | } 24 | n/=2; 25 | } 26 | return true; 27 | } 28 | } 29 | ``` -------------------------------------------------------------------------------- /Java/Reverse String.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Two Pointers, String 3 | 4 | Similar to Reverse Integer. 5 | 可以用StringBuffer, 也可以two pointer reverse head/tail 6 | 7 | ``` 8 | /* 9 | Write a function that reverses a string. The input string is given as an array of characters char[]. 10 | 11 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 12 | 13 | You may assume all the characters consist of printable ascii characters. 14 | */ 15 | 16 | /* 17 | Thoughts: 18 | Obvious: new StringBuilder().reverse(). 19 | Or, turn into charArray and reverse 20 | */ 21 | class Solution { 22 | public void reverseString(char[] s) { 23 | if (s == null || s.length <= 1) { 24 | return; 25 | } 26 | 27 | int n = s.length; 28 | for (int i = 0; i < n / 2; i++) { 29 | char temp = s[i]; 30 | s[i] = s[n - i - 1]; 31 | s[n - i - 1] = temp; 32 | } 33 | } 34 | } 35 | ``` -------------------------------------------------------------------------------- /Java/Rotate Image.java: -------------------------------------------------------------------------------- 1 | M 2 | tags: Array, Enumeration 3 | 4 | #### 找公式规律 5 | - 找到个转角度的规律公式: r = c; c = (w - r) 6 | - 用temp variable, swap in place. 7 | 8 | ``` 9 | /* 10 | You are given an n x n 2D matrix representing an image. 11 | Rotate the image by 90 degrees (clockwise). 12 | 13 | Have you met this question in a real interview? Yes 14 | Example 15 | Given a matrix 16 | 17 | [ 18 | [1,2], 19 | [3,4] 20 | ] 21 | rotate it by 90 degrees (clockwise), return 22 | 23 | [ 24 | [3,1], 25 | [4,2] 26 | ] 27 | Challenge 28 | Do it in-place. 29 | 30 | Tags Expand 31 | Cracking The Coding Interview Matrix 32 | */ 33 | 34 | 35 | //in matrix, to find next position: r = c; c = (w - r). Work on the equation => oldR = w - c, oldC = r 36 | //In pace: do loop, change 4 at once. do a quater of the matrix 37 | public class Solution { 38 | public void rotate(int[][] matrix) { 39 | if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 40 | return; 41 | } 42 | int width = matrix.length; 43 | for (int i = 0; i < width/2; i++) { 44 | for (int j = 0; j < Math.ceil(width/2.0); j++) { 45 | int temp = matrix[i][j]; 46 | matrix[i][j] = matrix[width - 1 - j][i]; 47 | matrix[width - 1 - j][i] = matrix[width - 1 - i][width - 1 - j]; 48 | matrix[width - 1 - i][width - 1 - j] = matrix[j][width - 1 - i]; 49 | matrix[j][width - 1 - i] = temp; 50 | } 51 | } 52 | } 53 | } 54 | ``` -------------------------------------------------------------------------------- /Java/Shortest Distance from All Buildings.java: -------------------------------------------------------------------------------- 1 | H 2 | 1533539906 3 | tags: BFS 4 | 5 | 给Walls and Gates很像, 不同的是, 这道题要选一个 coordinate, having shortest sum distance to all buildings (marked as 1). 6 | 7 | #### BFS 8 | - BFS 可以 mark shortest distance from bulding -> any possible spot. 9 | - Try each building (marked as 1) -> BFS cover all 0. 10 | - time: O(n^2) * # of building; use new visited[][] to mark visited for each building. 11 | - O(n^2) find smallest point/aggregation value. 12 | - 注意, 这道题我们update grid[][] sum up with shortest path value from building. 13 | - 最后找个min value 就好了, 甚至不用return coordinate. 14 | - 分析过, 还没有写. 15 | 16 | ``` 17 | 18 | /* 19 | You want to build a house on an empty land which reaches all buildings 20 | in the shortest amount of distance. You can only move up, down, left and right. 21 | You are given a 2D grid of values 0, 1 or 2, where: 22 | 23 | Each 0 marks an empty land which you can pass by freely. 24 | Each 1 marks a building which you cannot pass through. 25 | Each 2 marks an obstacle which you cannot pass through. 26 | Example: 27 | 28 | Input: [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] 29 | 30 | 1 - 0 - 2 - 0 - 1 31 | | | | | | 32 | 0 - 0 - 0 - 0 - 0 33 | | | | | | 34 | 0 - 0 - 1 - 0 - 0 35 | 36 | Output: 7 37 | 38 | Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2), 39 | the point (1,2) is an ideal empty land to build a house, as the total 40 | travel distance of 3+3+1=7 is minimal. So return 7. 41 | Note: 42 | There will be at least one building. 43 | If it is not possible to build such house according to the above rules, return -1. 44 | 45 | */ 46 | ``` -------------------------------------------------------------------------------- /Java/Singleton.java: -------------------------------------------------------------------------------- 1 | E 2 | 1525415182 3 | tags: Design 4 | 5 | 让一个class 是 singleton 6 | 7 | ``` 8 | /* 9 | Singleton is a most widely used design pattern. 10 | If a class has and only has one instance at every moment, 11 | we call this design as singleton. 12 | 13 | For example, for class Mouse (not a animal mouse), we should design it in singleton. 14 | 15 | You job is to implement a getInstance method for given class, 16 | return the same instance of this class every time you call this method. 17 | 18 | 19 | Example 20 | In Java: 21 | 22 | A a = A.getInstance(); 23 | A b = A.getInstance(); 24 | a should equal to b. 25 | 26 | Challenge 27 | If we call getInstance concurrently, can you make sure your code could run correctly? 28 | 29 | Tags Expand 30 | LintCode Copyright OO Design 31 | 32 | */ 33 | 34 | class Solution { 35 | public static Solution instance = null; 36 | public static Solution getInstance() { 37 | if (instance == null) { 38 | instance = new Solution(); 39 | } 40 | return instance; 41 | } 42 | }; 43 | 44 | // Thread safe: 45 | class Solution { 46 | public static Solution solution = null; 47 | /** 48 | * @return: The same instance of this class every time 49 | */ 50 | public static Solution getInstance() { 51 | if (solution == null) { 52 | synchronized (Solution.class) { 53 | // Double check 54 | if (solution == null) { 55 | solution = new Solution(); 56 | } 57 | } 58 | } 59 | return solution; 60 | } 61 | }; 62 | 63 | ``` -------------------------------------------------------------------------------- /Java/String Permutation.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | 把#of occurrences 存进HashMap, 第一个string 做加法,第二个string做减法。最后看是否有不等于0的作判断。 4 | 5 | ``` 6 | public class Solution { 7 | /* 8 | * @param A: a string 9 | * @param B: a string 10 | * @return: a boolean 11 | */ 12 | public boolean Permutation(String A, String B) { 13 | if (A == null || B == null || A.length() != B.length()) { 14 | return false; 15 | } 16 | final Map strMap = new HashMap<>(); 17 | for (int i = 0; i < A.length(); i++) { 18 | final char charA = A.charAt(i); 19 | final char charB = B.charAt(i); 20 | if (!strMap.containsKey(charA)) { 21 | strMap.put(charA, 0); 22 | } 23 | strMap.put(charA, strMap.get(charA) + 1); 24 | if (!strMap.containsKey(charB)) { 25 | strMap.put(charB, 0); 26 | } 27 | strMap.put(charB, strMap.get(charB) - 1); 28 | } 29 | for (Map.Entry entry : strMap.entrySet()) { 30 | if (entry.getValue() != 0) { 31 | return false; 32 | } 33 | } 34 | return true; 35 | } 36 | } 37 | 38 | ``` 39 | -------------------------------------------------------------------------------- /Java/Subarray Sum II.java: -------------------------------------------------------------------------------- 1 | H 2 | tags: Two Pointers, Array, Binary Search 3 | 4 | ``` 5 | /* 6 | Given an integer array, find a subarray where the sum of numbers is in a given interval. 7 | Your code should return the number of possible answers. (The element in the array should be positive) 8 | 9 | Example 10 | Given [1,2,3,4] and interval = [1,3], return 4. The possible answers are: 11 | 12 | [0, 0] 13 | [0, 1] 14 | [1, 1] 15 | [2, 2] 16 | */ 17 | 18 | /* 19 | Thoughts: 20 | Brutle O(n2) with preSum can do. Do better: O(nlogn) 21 | - presum 22 | - iterate over start point, which will be the 'must have' index in result 23 | - find the largest end point, where preSum[end] - preSum[start - 1] <= max. Binary Search since the presum will be increasing 24 | - count += end - start + 1 25 | - move on to next start 26 | - Overall it should be O(nlogn) 27 | - should write the binary search as a separate function 28 | */ 29 | ``` -------------------------------------------------------------------------------- /Java/Summary Ranges.java: -------------------------------------------------------------------------------- 1 | M 2 | 1528247314 3 | tags: Array 4 | 5 | 给一串sorted list, 中间有缺数字, return 所有数字的range string (example 看题目) 6 | 7 | #### Basic implementation 8 | - 用一个list as the buffer to store candidates 9 | - when: 1. end of nums; 2. not continuous integer => convert list to result 10 | 11 | ``` 12 | /* 13 | Given a sorted integer array without duplicates, return the summary of its ranges. 14 | 15 | For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 16 | 17 | Tags: Array 18 | Similar Problems: (M) Missing Ranges 19 | 20 | 21 | */ 22 | /* 23 | Thoughts: basic implementation, use a arraylist to catch candidates. 24 | Detect condition, and return results. 25 | */ 26 | public class Solution { 27 | public List summaryRanges(int[] nums) { 28 | List rst = new ArrayList<>(); 29 | if (nums == null || nums.length == 0) { 30 | return rst; 31 | } 32 | List list = new ArrayList<>(); 33 | for (int i = 0; i < nums.length; i++) { 34 | list.add(nums[i]); 35 | if (i + 1 == nums.length || nums[i] + 1 != nums[i + 1]) { 36 | if (list.size() == 1) { 37 | rst.add(list.get(0) + ""); 38 | } else { 39 | rst.add(list.get(0) + "->" + list.get(list.size() - 1)); 40 | } 41 | list = new ArrayList(); 42 | } 43 | } 44 | return rst; 45 | } 46 | } 47 | 48 | //O(n) 49 | ``` -------------------------------------------------------------------------------- /Java/Swap Bits.java: -------------------------------------------------------------------------------- 1 | E 2 | 1517982439 3 | tags: Bit Manipulation 4 | 5 | 简单, 但是很多知识点: 6 | 1. Hex 0xaaaaaaaa 是1010101....1010; 0x55555555 是01010101....0101 7 | 2. 可以用这两个hex取单数和负数. 如果需要取其他的pattern, 也可以做. 8 | 3. x很可能是negative number, 所以right-shift 要用logic shift, >>> 避免leading负数补位. 9 | 10 | ``` 11 | /* 12 | Write a program to swap odd and even bits in an integer with as few instructions as possible 13 | (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). 14 | */ 15 | 16 | /* 17 | Thoughts: 18 | index '0' is even, so starting from even bits. 19 | Goal: 20 | Shift even bits << 1, shift odd bits >> 1. 21 | We need to extract all of the odd bits and all of the even bits. 22 | 23 | Trick: 24 | 0xaaaaaaaa represents: 10101010101....1010 25 | Because 0xA: is number 10, and has binary of 1010. 26 | 27 | Similarly: 28 | 0x55555555 represents: 01010101010....0101 29 | Because 0x5: is number 5, and has binary of 0101 30 | 31 | Therefore: 32 | Get even bits: x & 0x55555555 33 | Get odd bits: x & 0xaaaaaaaa 34 | 35 | End: 36 | Perform the shift and add up the two numbers together. 37 | 38 | Note: right-shift has to use the logic-shift >>> to resolve the negative number issue. 39 | */ 40 | public class Solution { 41 | public int swapOddEvenBits(int x) { 42 | return ((x & 0xaaaaaaaa) >>> 1) + ((x & 0x55555555) << 1); 43 | } 44 | } 45 | ``` -------------------------------------------------------------------------------- /Java/The Spiral Matrix II.java: -------------------------------------------------------------------------------- 1 | M 2 | 1534346957 3 | tags: Array 4 | 5 | #### Move forward till end 6 | - Similar concept as `The Maze`: keep walking until hit wall, turn back 7 | - fix direction `dx[direction % 4]` 8 | 9 | ``` 10 | /* 11 | Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 12 | 13 | Example: 14 | 15 | Input: 3 16 | Output: 17 | [ 18 | [ 1, 2, 3 ], 19 | [ 8, 9, 4 ], 20 | [ 7, 6, 5 ] 21 | ] 22 | */ 23 | 24 | /* 25 | Use while loop, reach end and stop 26 | */ 27 | class Solution { 28 | int[] dx = {0, 1, 0, -1}; 29 | int[] dy = {1, 0, -1, 0}; 30 | public int[][] generateMatrix(int n) { 31 | int[][] grid = new int[n][n]; 32 | int step = 1, i = 0, j = 0, direction = 0; 33 | grid[i][j] = step++; 34 | while (step <= n * n) { 35 | int x = dx[direction % 4]; 36 | int y = dy[direction % 4]; 37 | i += x; 38 | j += y; 39 | while (i >= 0 && i < n && j >= 0 && j < n && grid[i][j] == 0) { 40 | grid[i][j] = step++; 41 | i += x; 42 | j += y; 43 | } 44 | i -= x; 45 | j -= y; 46 | direction++; 47 | } 48 | return grid; 49 | } 50 | } 51 | ``` -------------------------------------------------------------------------------- /Java/Two Sum IV - Input is a BST.java: -------------------------------------------------------------------------------- 1 | E 2 | 1533407180 3 | tags: Tree 4 | 5 | HashSet to store visited items. Same old 2 sum trick. 6 | 7 | ``` 8 | /* 9 | Given a Binary Search Tree and a target number, 10 | return true if there exist two elements in the BST such that their sum is equal to the given target. 11 | 12 | Example 1: 13 | Input: 14 | 5 15 | / \ 16 | 3 6 17 | / \ \ 18 | 2 4 7 19 | 20 | Target = 9 21 | 22 | Output: True 23 | Example 2: 24 | Input: 25 | 5 26 | / \ 27 | 3 6 28 | / \ \ 29 | 2 4 7 30 | 31 | Target = 28 32 | 33 | Output: False 34 | */ 35 | 36 | // hashmap, in-order traverse for smaller items, recursively 37 | class Solution { 38 | Set set = new HashSet<>(); 39 | 40 | public boolean findTarget(TreeNode root, int k) { 41 | if (root == null) return false; 42 | if (findTarget(root.left, k)) return true; 43 | if (set.contains(k - root.val)) return true; 44 | set.add(root.val); 45 | if (findTarget(root.right, k)) return true; 46 | 47 | return false; 48 | } 49 | } 50 | ``` -------------------------------------------------------------------------------- /Java/[lint]. Longest Words.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Hash Table, String, Lint 3 | 4 | 给一串String, 找到最长的长度, 把最长的String全都return 5 | 6 | #### Hash Table 7 | - > 8 | - 存最长值, 最后map.get(max) 9 | 10 | ``` 11 | /* 12 | Given a dictionary, find all of the longest words in the dictionary. 13 | 14 | Example 15 | Given 16 | 17 | { 18 | "dog", 19 | "google", 20 | "facebook", 21 | "internationalization", 22 | "blabla" 23 | } 24 | the longest words are(is) ["internationalization"]. 25 | 26 | Given 27 | 28 | { 29 | "like", 30 | "love", 31 | "hate", 32 | "yes" 33 | } 34 | the longest words are ["like", "love", "hate"]. 35 | 36 | Challenge 37 | It's easy to solve it in two passes, can you do it in one pass? 38 | 39 | Tags Expand 40 | Enumeration String LintCode Copyright 41 | 42 | Thoughts: 43 | Two pass: 1st, get longest length. 2nd pass, get all words. 44 | 45 | One pass: 46 | 1. Use hashmap: > 47 | 2. keep track of the longest length 48 | 49 | */ 50 | 51 | /* 52 | Thoughts: 53 | 1. one pass, save in . 54 | 2. Maintain max length 55 | 3. return 56 | */ 57 | public class Solution { 58 | public List longestWords(String[] dictionary) { 59 | if (dictionary == null || dictionary.length == 0) { 60 | return null; 61 | } 62 | Map> map = new HashMap<>(); 63 | int max = 0; 64 | 65 | for (String word : dictionary) { 66 | int length = word.length(); 67 | map.putIfAbsent(length, new ArrayList<>()); 68 | map.get(length).add(word); 69 | max = Math.max(max, length); 70 | } 71 | return map.get(max); 72 | } 73 | } 74 | ``` -------------------------------------------------------------------------------- /Java/[lint]. Nth to Last Node in List.java: -------------------------------------------------------------------------------- 1 | E 2 | tags: Linked List, Lint 3 | 4 | #### Linked List 5 | - 先找到nth node 6 | - 然后head开始跑 7 | - node 到底,而head ~ node刚好是 n 距离。所以head就是要找的last nth 8 | 9 | ``` 10 | /* 11 | Find the nth to last element of a singly linked list. 12 | 13 | The minimum number of nodes in list is n. 14 | 15 | Example 16 | Given a List 3->2->1->5->null and n = 2, return node whose value is 1. 17 | 18 | Tags Expand 19 | Cracking The Coding Interview Linked List 20 | 21 | Thinking process: 22 | 1. Find nth node in normal order. 23 | 2. Have a head at index0. 24 | 3. Move both head and nth node. WHen nth node hit null/end, then the moving head is the nth to last node in list. 25 | */ 26 | 27 | /** 28 | * Definition for ListNode. 29 | * public class ListNode { 30 | * int val; 31 | * ListNode next; 32 | * ListNode(int val) { 33 | * this.val = val; 34 | * this.next = null; 35 | * } 36 | * } 37 | */ 38 | public class Solution { 39 | /** 40 | * @param head: The first node of linked list. 41 | * @param n: An integer. 42 | * @return: Nth to last node of a singly linked list. 43 | */ 44 | ListNode nthToLast(ListNode head, int n) { 45 | if (head == null || n < 0) { 46 | return null; 47 | } 48 | int count = 0; 49 | ListNode node = head; 50 | while (node != null && count < n) { 51 | node = node.next; 52 | count++; 53 | } 54 | while (node != null) { 55 | node = node.next; 56 | head = head.next; 57 | } 58 | return head; 59 | } 60 | } 61 | 62 | 63 | 64 | 65 | ``` -------------------------------------------------------------------------------- /Others/HackerrankNote.md: -------------------------------------------------------------------------------- 1 | Notes: 2 | System ouput: What out for format with space: " " 3 | Don't println() when print() is needed. 4 | Or: can choose to build a String rst, and print at the end. 5 | 6 | Be careful with root node : ) always 7 | 8 | Safe way to do LCA on Binary Search Tree: traditional way of 2 lists 9 | 10 | -------------------------------------------------------------------------------- /Others/README.md: -------------------------------------------------------------------------------- 1 | # Other Problems 2 | 3 | This section captures other programs that does not appear in LintCode. There might not be a clear solution to problems here, but here we'll try to capture some 'how to' or good thoughts. 4 | 5 | And, due to the non-consistency, there won't be auto-generated list view : ). -------------------------------------------------------------------------------- /Others/RemoveNodeFromLinkedList.java: -------------------------------------------------------------------------------- 1 | //Remove node from linkedlist 2 | //H L L L 0 3 | Node current = head;//L 4 | Node node = current; 5 | Node prev = new Node('0'); 6 | prev.next = node; 7 | while (current != null) {//1L 8 | 9 | while (node.next != null) {//21L 10 | if (current.value == node.next.value ) { 11 | prev.next = prev.next.next; 12 | } 13 | prev = prev.next; 14 | node = node.next; 15 | 16 | } 17 | prev = current; 18 | current = current.next; 19 | node = current; 20 | } 21 | return head; 22 | -------------------------------------------------------------------------------- /Others/Solution$TreeNode.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awangdev/leet-code/11cb3779bca977c66374f749adc6e41fede36b79/Others/Solution$TreeNode.class -------------------------------------------------------------------------------- /Others/Solution.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awangdev/leet-code/11cb3779bca977c66374f749adc6e41fede36b79/Others/Solution.class -------------------------------------------------------------------------------- /Others/Sort Anagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Sort Anagram 3 | My guess this problem is: Sort a list of strings and make sure all the anagrams are grouped together. 4 | 5 | The clarification needed would be: 6 | 1. Does the output need to be in alphabetical order and how to define the rules, since anagram will not be in perfect order comparing with other non-same-group strings. 7 | 8 | 2. If no need of alphabetical order, but just group anagram words together, this would turn to a regular anagram problem. 9 | Use HashMap to store sorted string as KEY, and a list of strings as value. 10 | Then output all contents from map. 11 | 12 | */ -------------------------------------------------------------------------------- /Others/TopTenURL.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list of URLs, find top 10 most visited URLs 3 | 4 | Some points this problem might cover: 5 | 6 | 7 | */ 8 | 9 | /* 10 | 1. MapReduce related problem 11 | http://stackoverflow.com/questions/17928158/find-top-10-most-frequent-visited-url-data-is-stored-accross-network# 12 | To mimic the process of MapReduce. 13 | 14 | One most voted solution: 15 | It says you can't use map-reduce directly which is a hint the author of the question wants you to think how map reduce works, so we will just mimic the actions of map-reduce: 16 | 17 | pre-processing: let R be the number of servers in cluster, give each server unique id from 0,1,2,...,R-1 18 | (map) For each (string,id) - send the tuple to the server which has the id hash(string) % R. 19 | (reduce) Once step 2 is done (simple control communication), produce the (string,count) of the top 10 strings per server. Note that the tuples where those sent in step2 to this particular server. 20 | (map) Each server will send all his top 10 to 1 server (let it be server 0). It should be fine, there are only 10*R of those records. 21 | (reduce) Server 0 will yield the top 10 across the network. 22 | 23 | Notes: 24 | 25 | The problem with the algorithm, like most big-data algorithms that don't use frameworks is handling failing servers. MapReduce takes care of it for you. 26 | The above algorithm can be translated to a 2 phases map-reduce algorithm pretty straight forward. 27 | */ 28 | 29 | 30 | /* 31 | 2. Top K words in a document: 32 | This is an actaul problem on LintCode 33 | http://www.zrzahid.com/top-k-or-k-most-frequent-words-in-a-document/ 34 | http://www.geeksforgeeks.org/find-the-k-most-frequent-words-from-a-file/ 35 | */ -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/GenerateCodeTable.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awangdev/leet-code/11cb3779bca977c66374f749adc6e41fede36b79/Others/old records/LeetCode-Merged/GenerateCodeTable.class -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Alien Dictionary.java: -------------------------------------------------------------------------------- 1 | /* 2 | There is a new alien language which uses the latin alphabet. 3 | However, the order among letters are unknown to you. 4 | You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. 5 | Derive the order of letters in this language. 6 | 7 | For example, 8 | Given the following words in dictionary, 9 | 10 | [ 11 | "wrt", 12 | "wrf", 13 | "er", 14 | "ett", 15 | "rftt" 16 | ] 17 | The correct order is: "wertf". 18 | 19 | Note: 20 | You may assume all letters are in lowercase. 21 | If the order is invalid, return an empty string. 22 | There may be multiple valid order of letters, return any one of them is fine. 23 | Hide Company Tags Google Facebook 24 | Hide Tags Graph Topological Sort 25 | Hide Similar Problems (M) Course Schedule II 26 | 27 | */ 28 | 29 | /* 30 | NOT DONE 31 | Thoughts: 32 | They have sink node. They form a valid tree, without sycle. 33 | A char can visit another node, does not mean they have order. 34 | A char appear in a lower row means they have different order. 35 | For 1st column, w appears before e, e appears before r. 36 | For 2nd column:r appears before t, t appears before f 37 | For 3rd col: t appears before f. 38 | For 4th col, nothing to compare. 39 | So make in[][]: [w,e] [e,r][r,t][t,f] based on the possible order. 40 | 41 | Then do topological sort on the sequence and mark the sequence like in course schedule II 42 | */ 43 | 44 | public class Solution { 45 | public String alienOrder(String[] words) { 46 | 47 | } 48 | } 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Building Outline.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given N buildings in a x-axis,each building is a rectangle and can be represented by a triple (start, end, height),where start is the start position on x-axis, end is the end position on x-axis and height is the height of the building. Buildings may overlap if you see them from far away,find the outline of them。 3 | 4 | An outline can be represented by a triple, (start, end, height), where start is the start position on x-axis of the outline, end is the end position on x-axis and height is the height of the outline. 5 | 6 | Example 7 | Given 3 buildings: 8 | 9 | [ 10 | [1, 3, 3], 11 | [2, 4, 4], 12 | [5, 6, 1] 13 | ] 14 | The outlines are: 15 | 16 | [ 17 | [1, 2, 3], 18 | [2, 4, 4], 19 | [5, 6, 1] 20 | ] 21 | Note 22 | Please merge the adjacent outlines if they have the same height and make sure different outlines cant overlap on x-axis. 23 | 24 | Tags Expand 25 | LintCode Copyright Heap 26 | */ 27 | 28 | 29 | 30 | public class Solution { 31 | /** 32 | * @param buildings: A list of lists of integers 33 | * @return: Find the outline of those buildings 34 | */ 35 | public ArrayList> buildingOutline(int[][] buildings) { 36 | // write your code here 37 | } 38 | } 39 | 40 | 41 | /* 42 | Attempt1, may not be correct. 43 | Thoughts: 44 | PriorityQueue, sort by start. 45 | 1. Keep track of max height. 46 | 2. Find max height. 47 | 3. Poll() queue 48 | a. on left of highest building, When height increate, record this point(x, height) 49 | b. on right of highest building, when height decreses, record this point. 50 | 51 | */ 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Closest Binary Search Tree Value.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 3 | 4 | Note: 5 | Given target value is a floating point. 6 | You are guaranteed to have only one unique value in the BST that is closest to the target. 7 | 8 | Tags: Tree Binary Search 9 | Similar Problems: (M) Count Complete Tree Nodes, (H) Closest Binary Search Tree Value II 10 | 11 | */ 12 | 13 | 14 | /* 15 | Thoughts: 16 | Binary search, maintain a closest value. 17 | Note: initial closest in real case is just the root, since we start from the root 18 | */ 19 | /** 20 | * Definition for a binary tree node. 21 | * public class TreeNode { 22 | * int val; 23 | * TreeNode left; 24 | * TreeNode right; 25 | * TreeNode(int x) { val = x; } 26 | * } 27 | */ 28 | public class Solution { 29 | public int closestValue(TreeNode root, double target) { 30 | if (root == null) { 31 | return 0; 32 | } 33 | double closest = root.val; 34 | while (root != null) { 35 | if (root.val == target) { 36 | return root.val; 37 | } else { 38 | if (Math.abs(target - closest) >= Math.abs(target - root.val)) { 39 | closest = root.val; 40 | } 41 | if (root.val > target) { 42 | root = root.left; 43 | } else { 44 | root = root.right; 45 | } 46 | } 47 | }//END while 48 | return (int)closest; 49 | } 50 | } -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Excel Sheet Column Number.java: -------------------------------------------------------------------------------- 1 | 好久以前做的一个题了。 2 | 记得:'A' - 'A' = 0 呀。所以 any char - 'A' + 1 = 这个char在我们这个题目里面所代表的数字。 3 | 其次,26个字母代表着26位运算。和10位一样嘛,那第一位x26就好了。 4 | ``` 5 | /* 6 | 7 | Given a column title as appear in an Excel sheet, return its corresponding column number. 8 | 9 | For example: 10 | 11 | A -> 1 12 | 13 | B -> 2 14 | 15 | C -> 3 16 | 17 | ... 18 | 19 | Z -> 26 20 | 21 | AA -> 27 22 | 23 | AB -> 28 24 | 25 | */ 26 | 27 | public class Solution {//ABC -> 'A', 'B', 'C' 28 | 29 | public int titleToNumber(String s) {//S = AA 30 | 31 | int rst = 0; 32 | 33 | char[] arr = s.toCharArray(); 34 | 35 | for (int i = 0; i < arr.length; i++) {//i = 0,1,2 // (char c : arr) 36 | 37 | rst = rst * 26 + arr[i] - 'A' + 1;//rst =1, 26 + 1 = 27, 38 | 39 | } 40 | 41 | return rst; 42 | 43 | } 44 | 45 | } 46 | ``` -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/ExcelSheetColumnNumber .java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a column title as appear in an Excel sheet, return its corresponding column number. 3 | 4 | For example: 5 | 6 | A -> 1 7 | B -> 2 8 | C -> 3 9 | ... 10 | Z -> 26 11 | AA -> 27 12 | AB -> 28 13 | */ 14 | 15 | 16 | public class Solution {//ABC -> 'A', 'B', 'C' 17 | public int titleToNumber(String s) {//S = AA 18 | int rst = 0; 19 | char[] arr = s.toCharArray(); 20 | for (int i = 0; i < arr.length; i++) {//i = 0,1,2 // (char c : arr) 21 | rst = rst * 26 + arr[i] - 'A' + 1;//rst =1, 26 + 1 = 27, 22 | } 23 | return rst; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Implement strStr().java: -------------------------------------------------------------------------------- 1 | 还挺多坑的. 2 | 1. border condition。 如果 haystack.length() < needle.length() 的话,必须错。但是这个可以优化省略。 3 | 2. 当S2是“”的时候,也就是能在s1的其实位置找到s2....index = 0. 4 | 3. 记得如何在s1里面找s2. 就是把遍历s1的 i , 加上遍历s2的 j。 5 | 6 | 优化: 7 | 1. s1, s2长短可以不比较。因为forloop的时候: s1.length() - s2.length() + 1,如果s2长于s1,这里自然就断了。 8 | 2. if(s1.charAT(i+j) == s2.charAT(j)). 可以省略。For loop 里面就Check到这个了。 9 | ``` 10 | /* 11 | Implement strStr(). 12 | 13 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 14 | 15 | Hide Company Tags Facebook 16 | Hide Tags Two Pointers String 17 | Hide Similar Problems (H) Shortest Palindrome 18 | 19 | */ 20 | public class Solution { 21 | public int strStr(String haystack, String needle) { 22 | if (needle == null || needle.length() == 0) { 23 | return 0; 24 | } 25 | /* 26 | else if (haystack == null || haystack.length() == 0 27 | || haystack.length() < needle.length()) { 28 | return -1; 29 | }*/ 30 | int i = 0; 31 | int j = 0; 32 | 33 | for (i = 0; i < haystack.length() - needle.length() + 1; i++) { 34 | // if (haystack.charAt(i + j) == needle.charAt(j)) { 35 | for (j = 0; j < needle.length(); j++) { 36 | if (haystack.charAt(i + j) != needle.charAt(j)) { 37 | break; 38 | } 39 | } 40 | if (j == needle.length()) { 41 | return i; 42 | } 43 | // } 44 | } 45 | return -1; 46 | } 47 | } 48 | ``` -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Jump Game.java: -------------------------------------------------------------------------------- 1 | LintCode做过。 2 | 用一个farest can go 来做个一个点的DP,记录可以跑到得最远的地方。 3 | ``` 4 | /* 5 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 6 | 7 | Each element in the array represents your maximum jump length at that position. 8 | 9 | Determine if you are able to reach the last index. 10 | 11 | For example: 12 | A = [2,3,1,1,4], return true. 13 | 14 | A = [3,2,1,0,4], return false. 15 | 16 | Hide Tags Array Greedy 17 | 18 | */ 19 | 20 | public class Solution { 21 | public boolean canJump(int[] nums) { 22 | if (nums == null || nums.length <= 1) { 23 | return true; 24 | } 25 | int farest = 0; 26 | for (int i = 0; i < nums.length; i++) { 27 | farest = Math.max(farest, nums[i] + i); 28 | if (farest >= nums.length - 1) { 29 | return true; 30 | } 31 | if (farest <= i) { 32 | return false; 33 | } 34 | } 35 | return true; 36 | } 37 | } 38 | ``` -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 3 | 4 | For example, given the array [−2,1,−3,4,−1,2,1,−5,4], 5 | the contiguous subarray [4,−1,2,1] has the largest sum = 6. 6 | 7 | click to show more practice. 8 | 9 | More practice: 10 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 11 | 12 | Hide Tags Divide and Conquer Array Dynamic Programming 13 | 14 | Thinking process: 15 | 1. DP: store calculated sum for comparison use: compare with max to get true max value. 16 | 2. Max sum from previous index to current: 17 | at index i, try to compare if pre + current > current index value. If yes, use pre + current; if NO, just use current as max. 18 | Compare max with Sum[i] for final max vlaualuealuee. 19 | 20 | */ 21 | 22 | public class Solution { 23 | public int maxSubArray(int[] A) { 24 | if (A == null || A.length == 0) { 25 | return 0; 26 | } 27 | int[] sum = new int[A.length]; 28 | sum[0] = A[0]; 29 | int max = sum[0]; 30 | for (int i = 1; i < sum.length; i++) { 31 | sum[i] = Math.max(A[i], sum[i - 1] + A[i]); 32 | max = Math.max(max, sum[i]); 33 | } 34 | return max; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Median of Two Sorted Arrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 3 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 4 | */ 5 | 6 | 7 | /* 8 | THoughts: 9 | max-heap on left and min-heap on right; Center: the median 10 | left heap size: x 11 | right heap size: x, or x + 1 12 | 13 | However, this might (m+n)Log(m+n) 14 | 15 | */ 16 | 17 | //NOT DONE 18 | public class Solution { 19 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 20 | if (nums1 == null && nums2 == null) { 21 | return 0; 22 | } 23 | //min-heap 24 | PriorityQueue minHeap = new PriorityQueue(); 25 | PriorityQueue maxHeap = new PriorityQueue(1, new Comparator(){ 26 | public int compare(int x, int y){ 27 | return y - x; 28 | } 29 | }); 30 | 31 | int median = Integer.MIN_VALUE; 32 | 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Merge Two Sorted Lists.java: -------------------------------------------------------------------------------- 1 | /* 2 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 3 | 4 | Tags: Linked List 5 | Similar Problems: (H) Merge k Sorted Lists, (E) Merge Sorted Array, (M) Sort List, (M) Shortest Word Distance II 6 | 7 | */ 8 | 9 | /* 10 | Thouhts: 11 | Loop throgh both list. Make sure to check the border cases 12 | */ 13 | 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * public class ListNode { 18 | * int val; 19 | * ListNode next; 20 | * ListNode(int x) { val = x; } 21 | * } 22 | */ 23 | public class Solution { 24 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 25 | if (l1 == null && l2 == null) { 26 | return null; 27 | } 28 | ListNode node = new ListNode(0); 29 | ListNode dummy = node; 30 | while (l1 != null || l2 != null) { 31 | if (l1 == null) { 32 | node.next = l2; 33 | break; 34 | } else if (l2 == null) { 35 | node.next = l1; 36 | break; 37 | } else { 38 | if (l1.val < l2.val) { 39 | node.next = l1; 40 | l1 = l1.next; 41 | } else { 42 | node.next = l2; 43 | l2 = l2.next; 44 | } 45 | node = node.next; 46 | } 47 | }//end while 48 | return dummy.next; 49 | } 50 | } -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Min Stack.java: -------------------------------------------------------------------------------- 1 | 双Stack. 小心stack.peek() 而不是 pop 2 | ``` 3 | /* 4 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 5 | 6 | push(x) -- Push element x onto stack. 7 | pop() -- Removes the element on top of the stack. 8 | top() -- Get the top element. 9 | getMin() -- Retrieve the minimum element in the stack. 10 | 11 | Tags: Stack, Design 12 | Similar Problems: (H) Sliding Window Maximum 13 | 14 | 15 | Thoughts: 16 | Use a regular Stack: linked list. 17 | Save that minimum integer in a HashMap with each stack value. At each level of the stack, it always stores the min till that moment. 18 | Use another stack to hold that 'up-to-date' min values. 19 | 20 | Note: 21 | Stack: peek() 22 | 23 | */ 24 | 25 | class MinStack { 26 | Stack stack = new Stack(); 27 | Stack min = new Stack(); 28 | public void push(int x) { 29 | stack.push(x); 30 | if (min.isEmpty() || x < min.peek()){ 31 | min.push(x); 32 | } else { 33 | min.push(min.peek()); 34 | } 35 | } 36 | 37 | public void pop() { 38 | stack.pop(); 39 | min.pop(); 40 | } 41 | 42 | public int top() { 43 | return stack.peek(); 44 | } 45 | 46 | public int getMin() { 47 | return min.peek(); 48 | } 49 | } 50 | 51 | 52 | ``` -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Reverse Linked List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a singly linked list. 3 | 4 | Hint: 5 | A linked list can be reversed either iteratively or recursively. Could you implement both? 6 | 7 | Tags: Linked List 8 | Similar Problems: (M) Reverse Linked List II, (M) Binary Tree Upside Down, (E) Palindrome Linked List 9 | 10 | */ 11 | /* 12 | Thoughts: 13 | Cut off everything from [2 ~ ] and save it in cutoff; 14 | Append old reversed list to current head. Make itself as the new reversedList. Basically: append the 1st element to head of the reversedList, like a stack. 15 | Save head = cutOff: basically moves on to next element. 16 | */ 17 | /** 18 | * Definition for singly-linked list. 19 | * public class ListNode { 20 | * int val; 21 | * ListNode next; 22 | * ListNode(int x) { val = x; } 23 | * } 24 | */ 25 | public class Solution { 26 | public ListNode reverseList(ListNode head) { 27 | if (head == null) { 28 | return head; 29 | } 30 | ListNode reversedList = null; 31 | while (head != null) { 32 | ListNode cutOff = head.next; 33 | head.next = reversedList; 34 | reversedList = head; 35 | head = cutOff; 36 | } 37 | return reversedList; 38 | } 39 | } -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Summary Ranges.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted integer array without duplicates, return the summary of its ranges. 3 | 4 | For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"]. 5 | 6 | Tags: Array 7 | Similar Problems: (M) Missing Ranges 8 | 9 | 10 | */ 11 | /* 12 | Thoughts: basic implementation, use a arraylist to catch candidates. 13 | Detect condition, and return results. 14 | */ 15 | public class Solution { 16 | public List summaryRanges(int[] nums) { 17 | List rst = new ArrayList(); 18 | if (nums == null || nums.length == 0) { 19 | return rst; 20 | } 21 | ArrayList list = new ArrayList(); 22 | for (int i = 0; i < nums.length; i++) { 23 | list.add(nums[i]); 24 | if (i + 1 == nums.length || nums[i] + 1 != nums[i + 1]) { 25 | if (list.size() == 1) { 26 | rst.add(list.get(0) + ""); 27 | } else { 28 | rst.add(list.get(0) + "->" + list.get(list.size() - 1)); 29 | } 30 | list = new ArrayList(); 31 | } 32 | } 33 | return rst; 34 | } 35 | } 36 | 37 | //O(n) -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Two Sum II - Input array is sorted.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | 4 | 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. Please note that your returned answers (both index1 and index2) are not zero-based. 5 | 6 | You may assume that each input would have exactly one solution. 7 | 8 | Input: numbers={2, 7, 11, 15}, target=9 9 | Output: index1=1, index2=2 10 | 11 | Tags: Array Two Pointers, Binary Search 12 | Similar Problems: (M) Two Sum 13 | 14 | */ 15 | 16 | 17 | /* 18 | Thoughts: 19 | Do a binary search, but do not over-complicate it: 20 | Start, end. Check if nums[start] + nums[end] == target. 21 | binary move it: in fact, moving the two border, 1 position at a time 22 | */ 23 | 24 | public class Solution { 25 | public int[] twoSum(int[] nums, int target) { 26 | int[] rst = new int[2]; 27 | if (nums == null || nums.length <= 1) { 28 | return rst; 29 | } 30 | int start = 0; 31 | int end = nums.length - 1; 32 | while(start < end) { 33 | long sum = (long)(nums[start] + nums[end]); 34 | if (target == sum) { 35 | rst[0] = start + 1; 36 | rst[1] = end + 1; 37 | break; 38 | } else if (target > sum) { 39 | start++; 40 | } else { 41 | end--; 42 | } 43 | }//END while 44 | return rst; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Two Sum.java: -------------------------------------------------------------------------------- 1 | E 2 | Same as https://github.com/awangdev/LintCode/blob/master/Java/2%20Sum.java 3 | 4 | ``` 5 | /* 6 | Given an array of integers, find two numbers such that they add up to a specific target number. 7 | 8 | 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. Please note that your returned answers (both index1 and index2) are not zero-based. 9 | 10 | You may assume that each input would have exactly one solution. 11 | 12 | Input: numbers={2, 7, 11, 15}, target=9 13 | Output: index1=1, index2=2 14 | 15 | Array, Hash Table 16 | Similar Problems: (M) 3Sum, (M) 4Sum (M), Two Sum II - Input array is sorted, (E) Two Sum III - Data structure design 17 | 18 | */ 19 | 20 | /* 21 | Thought: 22 | Hash added value . 23 | Check remaining value == target ? 24 | */ 25 | public class Solution { 26 | public int[] twoSum(int[] nums, int target) { 27 | int[] rst = new int[2]; 28 | if (nums == null || nums.length <= 1) { 29 | return rst; 30 | } 31 | HashMap map = new HashMap(); 32 | for (int i = 0; i < nums.length; i++) { 33 | int remaining = target - nums[i]; 34 | if (!map.containsKey(remaining)) { 35 | map.put(nums[i], i); 36 | } else { 37 | rst[0] = map.get(remaining) + 1; 38 | rst[1] = i + 1; 39 | break; 40 | } 41 | } 42 | return rst; 43 | } 44 | } 45 | ``` -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/Ugly Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a program to check whether a given number is an ugly number. 3 | 4 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 5 | For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 6 | 7 | Note that 1 is typically treated as an ugly number. 8 | 9 | 10 | Hide Tags Math 11 | Hide Similar Problems (E) Happy Number (E) Count Primes (M) Ugly Number II 12 | 13 | */ 14 | /* 15 | Thoughts: 16 | Find all prime factors, check if other factors exist rather than 2,3,5. 17 | 3 while loops. 18 | If num % 5 = 0 , keep it going. 19 | If num % 3 = 0, keep it going. 20 | If num % 2 = 0, keep it going ... 21 | At the end, it should == 1. If not, return false; 22 | */ 23 | 24 | 25 | public class Solution { 26 | public boolean isUgly(int num) { 27 | if (num <= 0) { 28 | return false; 29 | } else if (num == 1) { 30 | return true; 31 | } 32 | 33 | while (num != 0 && num % 5 == 0) { 34 | num = num / 5; 35 | } 36 | while (num != 0 && num % 3 == 0) { 37 | num = num / 3; 38 | } 39 | while (num != 0 && num % 2 == 0) { 40 | num = num / 2; 41 | } 42 | return num == 1; 43 | } 44 | } -------------------------------------------------------------------------------- /Others/old records/LeetCode-Merged/Java/reverseInteger.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse Integer 3 | 4 | Reverse digits of an integer. 5 | 6 | Example1: x = 123, return 321 7 | Example2: x = -123, return -321 8 | //input = 1534236469 9 | 10 | Thinking process: 11 | Make sure of operators. 12 | Note: check for overflow using long. When integer is > Integer.MAX_VALUE, then it's overflow. 13 | Initialize long : long x = 1234L; 14 | Convert using (int) 15 | 16 | */ 17 | public class Solution { 18 | public int reverse(int x) { 19 | if (x == 0) { 20 | return x; //123 21 | } 22 | boolean sign = x > 0; //sign = true 23 | long rst = 0L; 24 | x = Math.abs(x); // 123 25 | while (x != 0) { //x = 123, 12, 1 26 | rst = rst * 10 + x % 10; //rst = 3, 30 + 2 = 32, 320 + 1 = 321 27 | x = x / 10; //x = 12; 1; 0 28 | } 29 | if (rst < 0 || rst > Integer.MAX_VALUE) { 30 | return 0; 31 | } 32 | return sign ? (int)rst : -(int)rst; 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/A+B.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | Bit Operation 4 | 5 | a & b: 每bit可能出得余数 6 | a ^ b: 每bit在此次操作可能留下的值,XOR 操作 7 | 每次左移余数1位,然后存到b, 再去跟a做第一步。loop until b == 0 8 | 9 | 10 | ``` 11 | /* 12 | Write a function that add two numbers A and B. You should not use + or any arithmetic operators. 13 | 14 | Example 15 | Given a=1 and b=2 return 3 16 | 17 | Note 18 | There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it. 19 | 20 | Challenge 21 | Of course you can just return a + b to get accepted. But Can you challenge not do it like that? 22 | 23 | Clarification 24 | Are a and b both 32-bit integers? 25 | 26 | Yes. 27 | Can I use bit operation? 28 | 29 | Sure you can. 30 | Tags Expand 31 | Cracking The Coding Interview Bit Manipulation 32 | 33 | 34 | */ 35 | 36 | /* 37 | Thought: 38 | Bit operation. Just to remmeber this problem, doing A+B using bit. 39 | */ 40 | class Solution { 41 | public int aplusb(int a, int b) { 42 | while (b != 0) { 43 | int carry = a & b; 44 | a = a ^ b; 45 | b = carry << 1; 46 | } 47 | return a; 48 | } 49 | }; 50 | 51 | 52 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Best Time to Buy and Sell Stock I.java: -------------------------------------------------------------------------------- 1 | M 2 | 3 | 理解意思是关键: 4 | 每天都就交易价格,n天只让买卖一次,那就找个最低价买进,找个最高价卖出。 5 | 记录每天最小值Min是多少。O(n) 6 | 每天都算和当下的Min买卖,profit最大多少。 7 | 8 | 9 | ``` 10 | /* 11 | Say you have an array for which the ith element is the price of a given stock on day i. 12 | 13 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), 14 | design an algorithm to find the maximum profit. 15 | 16 | Have you met this question in a real interview? Yes 17 | Example 18 | Given an example [3,2,3,1,2], return 1 19 | 20 | Tags Expand 21 | Greedy Enumeration Array Facebook Uber 22 | 23 | */ 24 | 25 | /* 26 | 27 | Thoughts 28 | First to understand what this question is asking: 29 | Each element is a price of the same stock on that specific day. Of course we want to buy in with min-price and sell out with max-price. 30 | Find the min-price by looping through the array. 31 | Find the max-profit: price[i] - min-price, which requires a loop through the loop again. 32 | We put above 2 tasks into one-pass for loop 33 | 34 | */ 35 | public class Solution { 36 | /** 37 | * @param prices: Given an integer array 38 | * @return: Maximum profit 39 | */ 40 | public int maxProfit(int[] prices) { 41 | if (prices == null || prices.length == 0) { 42 | return 0; 43 | } 44 | int min = Integer.MAX_VALUE; 45 | int profit = 0; 46 | for (int i = 0; i < prices.length; i++) { 47 | min = Math.min(min, prices[i]); 48 | profit = Math.max(profit, prices[i] - min); 49 | } 50 | return profit; 51 | } 52 | } 53 | 54 | 55 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Classical Binary Search.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | while: start + 1 < end 4 | mid = start + (end - start) / 2; 5 | 末尾double check start, end. 6 | 7 | 8 | ``` 9 | /* 10 | Find any position of a target number in a sorted array. 11 | Return -1 if target does not exist. 12 | 13 | Example 14 | Given [1, 2, 2, 4, 5, 5]. 15 | 16 | For target = 2, return 1 or 2. 17 | 18 | For target = 5, return 4 or 5. 19 | 20 | For target = 6, return -1. 21 | 22 | Challenge 23 | O(logn) time 24 | 25 | Tags Expand 26 | Binary Search 27 | */ 28 | 29 | /* 30 | Thoughts: classic 31 | start,mid,end 32 | */ 33 | public class Solution { 34 | /** 35 | * @param A an integer array sorted in ascending order 36 | * @param target an integer 37 | * @return an integer 38 | */ 39 | public int findPosition(int[] A, int target) { 40 | if (A == null || A.length == 0) { 41 | return -1; 42 | } 43 | int start = 0; 44 | int end = A.length - 1; 45 | int mid; 46 | while(start + 1 < end) { 47 | mid = start + (end - start) / 2; 48 | if (target == A[mid]) { 49 | return mid; 50 | } else if (target > A[mid]) { 51 | start = mid; 52 | } else { 53 | end = mid; 54 | } 55 | }//end while 56 | if (A[start] == target || A[end] == target) { 57 | return A[start] == target ? start : end; 58 | } 59 | return -1; 60 | } 61 | } 62 | ``` 63 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | 40% Accepted 3 | You are climbing a stair case. It takes n steps to reach to the top. 4 | 5 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 6 | 7 | Example 8 | Tags Expand 9 | 10 | Thinking process: 11 | State: at i level, f[i] is the ways to climb to i position. 12 | Function: f[i] = f[i-1] + f[i-2]. 13 | f[i] is constructed from 2 branches: 14 | Last step is 1 from f[i-1] 15 | Last step is 2 from f[i-2] 16 | This idea can be presented using a tree. However we don’t need to do recursive. We just need to use two pointers to withhold 2 level’s values. 17 | Init: The for loop starts at level2, so before level 2 there are 2 init states: 18 | f[0] == 1. This means we jump 2 steps from level0 to level2. 19 | f[i] == 1. This means we jump 1 steps to level1, then jump another step to level2 20 | Answer: f[n] 21 | */ 22 | 23 | public class Solution { 24 | /** 25 | * @param n: An integer 26 | * @return: An integer 27 | */ 28 | public int climbStairs(int n) { 29 | if (n <= 2) { 30 | return n; 31 | } 32 | int last = 1; //Init f[1] 33 | int lastlast = 1; //Init f[0] 34 | int now = 0; 35 | for (int i = 2; i <= n; i++) { //Start from level2 36 | now = last + lastlast; 37 | lastlast = last; 38 | last = now; 39 | } 40 | return now; 41 | } 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Compare Strings.java: -------------------------------------------------------------------------------- 1 | /* 2 | Compare two strings A and B, determine whether A contains all of the characters in B. 3 | 4 | The characters in string A and B are all Upper Case letters. 5 | 6 | Example 7 | For A = "ABCD", B = "ABC", return true. 8 | 9 | For A = "ABCD" B = "AABC", return false. 10 | 11 | Tags Expand 12 | Basic Implementation String LintCode Copyright 13 | 14 | Thinking process: 15 | Count the number of occurance for StringA. 16 | Count the number of occurance for StringB. 17 | Check if all of StringB's char# <= StringA's char# at each index. 18 | */ 19 | 20 | public class Solution { 21 | /** 22 | * @param A : A string includes Upper Case letters 23 | * @param B : A string includes Upper Case letter 24 | * @return : if string A contains all of the characters in B return true else return false 25 | */ 26 | public boolean compareStrings(String A, String B) { 27 | if (A == null || B == null || A.length() < B.length()) { 28 | return false; 29 | } 30 | int[] countA = new int[26]; 31 | int[] countB = new int[26]; 32 | for (int i = 0; i < A.length(); i++) { 33 | countA[A.charAt(i) - 'A']++; 34 | } 35 | for (int i = 0; i < B.length(); i++) { 36 | countB[B.charAt(i) - 'A']++; 37 | if (countB[B.charAt(i) - 'A'] > countA[B.charAt(i) - 'A']) { 38 | return false; 39 | } 40 | } 41 | return true; 42 | } 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Convert Integer A to Integer B.java: -------------------------------------------------------------------------------- 1 | /* 2 | Determine the number of bits required to convert integer A to integer B 3 | 4 | Example 5 | Given n = 31, m = 14,return 2 6 | 7 | (31)10=(11111)2 8 | 9 | (14)10=(01110)2 10 | 11 | Tags Expand 12 | Cracking The Coding Interview Bit Manipulation Binary Representation 13 | 14 | Thinking process: 15 | Assume the integer is 32 bit. 16 | XOR a and b, shift by 1 bit everytime -> want to check the XORed value at index 0 : just & 1 will do. 17 | Count the above calculated result: how many bit difference do a and b have. 18 | */ 19 | 20 | class Solution { 21 | /** 22 | *@param a, b: Two integer 23 | *return: An integer 24 | */ 25 | public static int bitSwapRequired(int a, int b) { 26 | int count = 0; 27 | for (int i = 0; i < 32; i++) { 28 | count += (a ^ b) >> i & 1; 29 | } 30 | return count; 31 | } 32 | }; 33 | 34 | 35 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Cosine Similarity.java: -------------------------------------------------------------------------------- 1 | 按题目意思,写出来就好了。 2 | ``` 3 | /* 4 | Cosine similarity is a measure of similarity between two vectors of an inner product space that measures the cosine of the angle between them. 5 | The cosine of 0° is 1, and it is less than 1 for any other angle. 6 | 7 | See wiki: Cosine Similarity 8 | 9 | Here is the formula: 10 | http://www.lintcode.com/en/problem/cosine-similarity/# 11 | 12 | Given two vectors A and B with the same size, calculate the cosine similarity. 13 | 14 | Return 2.0000 if cosine similarity is invalid (for example A = [0] and B = [0]). 15 | 16 | Example 17 | Given A = [1, 2, 3], B = [2, 3 ,4]. 18 | 19 | Return 0.9926. 20 | 21 | Given A = [0], B = [0]. 22 | 23 | Return 2.0000 24 | 25 | */ 26 | 27 | /* 28 | Thoughts 29 | Based on the given equation. Write up calculation 30 | Check border. 31 | */ 32 | 33 | class Solution { 34 | /** 35 | * @param A: An integer array. 36 | * @param B: An integer array. 37 | * @return: Cosine similarity. 38 | */ 39 | public double cosineSimilarity(int[] A, int[] B) { 40 | if (A == null || B == null || A.length == 0 || B.length == 0 || A.length != B.length) { 41 | return 2; 42 | } 43 | 44 | double sumProduct = 0; 45 | double sumASq = 0; 46 | double sumBSq = 0; 47 | for (int i = 0; i < A.length; i++) { 48 | sumProduct += A[i]*B[i]; 49 | sumASq += A[i] * A[i]; 50 | sumBSq += B[i] * B[i]; 51 | } 52 | if (sumASq == 0 && sumBSq == 0) { 53 | return 2.0; 54 | } 55 | return sumProduct / (Math.sqrt(sumASq) * Math.sqrt(sumBSq)); 56 | } 57 | } 58 | 59 | 60 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Count 1 in Binary.java: -------------------------------------------------------------------------------- 1 | /* 2 | Count how many 1 in binary representation of a 32-bit integer. 3 | 4 | Example 5 | Given 32, return 1 6 | 7 | Given 5, return 2 8 | 9 | Given 1023, return 9 10 | 11 | Challenge 12 | If the integer is n bits with m 1 bits. Can you do it in O(m) time? 13 | 14 | Tags Expand 15 | Binary Bit Manipulation 16 | 17 | Thoughts: 18 | 1. break string into char[] 19 | 2. convert char[] into integer using Character.getNumericValue() 20 | 21 | */ 22 | 23 | 24 | 25 | 26 | public class Solution { 27 | /** 28 | * @param num: an integer 29 | * @return: an integer, the number of ones in num 30 | */ 31 | public int countOnes(int num) { 32 | if (num < 0) { 33 | return 0; 34 | } 35 | String bits = Integer.toBinaryString(num); 36 | char[] bitArray = bits.toCharArray(); 37 | int sum = 0; 38 | for (int i = 0; i < bitArray.length; i++) { 39 | sum += Character.getNumericValue(bitArray[i]); 40 | } 41 | return sum; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Delete Node in the Middle of Singly Linked List.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node. 3 | 4 | Example 5 | Given 1->2->3->4, and node 3. return 1->2->4 6 | 7 | Tags Expand 8 | Cracking The Coding Interview Linked List 9 | 10 | Thoughts: 11 | 1. Only have this node, make it look like its next 12 | 2. remove next 13 | 14 | */ 15 | 16 | 17 | /** 18 | * Definition for ListNode. 19 | * public class ListNode { 20 | * int val; 21 | * ListNode next; 22 | * ListNode(int val) { 23 | * this.val = val; 24 | * this.next = null; 25 | * } 26 | * } 27 | */ 28 | public class Solution { 29 | /** 30 | * @param node: the node in the list should be deleted 31 | * @return: nothing 32 | */ 33 | public void deleteNode(ListNode node) { 34 | if (node == null) { 35 | return; 36 | } 37 | node.val = node.next.val; 38 | node.next = node.next.next; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Fast Power.java: -------------------------------------------------------------------------------- 1 | /* 2 | Calculate the a^n % b where a, b and n are all 32bit integers. 3 | 4 | Example 5 | For 2^31 % 3 = 2 6 | 7 | For 100^1000 % 1000 = 0 8 | 9 | Challenge 10 | O(logn) 11 | 12 | Tags Expand 13 | Divide and Conquer 14 | 15 | Thoughts: 16 | Learn online: 17 | (a * b) % p = (a % p * b % p) % p 18 | Than mean: a ^ n can be divided into a^(n/2) * a^(n/2), that can be used for recursion: divde and conqure. 19 | 20 | Note: when n is odd number, it cannot be evenly divided into n/2 and n/2. This case needs special treatment: n = n/2 + n/2 + 1; 21 | */ 22 | 23 | class Solution { 24 | /* 25 | * @param a, b, n: 32bit integers 26 | * @return: An integer 27 | */ 28 | public int fastPower(int a, int b, int n) { 29 | if (n == 0) { 30 | return 1 % b; 31 | } 32 | if (n == 1) { 33 | return a % b; 34 | } 35 | 36 | long recurPow = fastPower(a, b, n / 2); 37 | recurPow = (recurPow * recurPow) % b; 38 | 39 | if (n % 2 == 1) { 40 | recurPow = recurPow * a % b; 41 | } 42 | 43 | return (int)recurPow; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Fibonacci.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Nth number in Fibonacci sequence. 3 | 4 | A Fibonacci sequence is defined as follow: 5 | 6 | The first two numbers are 0 and 1. 7 | The i th number is the sum of i-1 th number and i-2 th number. 8 | The first ten numbers in Fibonacci sequence is: 9 | 10 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ... 11 | 12 | 13 | Example 14 | Given 1, return 0 15 | 16 | Given 2, return 1 17 | 18 | Given 10, return 34 19 | 20 | Note 21 | The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases. 22 | 23 | Tags Expand 24 | Enumeration Mathematics Non Recursion 25 | 26 | Thoughts: 27 | 1. If non-recursion, do for loop for that n 28 | 2. Note: this specfiic problem is not 0-based. it's 1-based. 29 | 3. return fib[n] 30 | */ 31 | 32 | class Solution { 33 | /** 34 | * @param n: an integer 35 | * @return an integer f(n) 36 | */ 37 | public int fibonacci(int n) { 38 | if (n <= 1) { 39 | return 0; 40 | } 41 | int[] fib = new int[n + 1]; 42 | fib[1] = 0; 43 | fib[2] = 1; 44 | for (int i = 3; i <= n; i++) { 45 | fib[i] = fib[i - 1] + fib[i - 2]; 46 | } 47 | return fib[n]; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Find Minimum in Rotated Sorted Array II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Medium Find Minimum in Rotated Sorted Array II My Submissions 3 | 4 | 40% Accepted 5 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 6 | 7 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 8 | 9 | Find the minimum element. 10 | 11 | The array may contain duplicates. 12 | 13 | Example 14 | Given [4,4,5,6,7,0,1,2] return 0 15 | 16 | Tags Expand 17 | Binary Search Divide and Conqueri 18 | 19 | Thinking process: 20 | It seems using binary search will leads to O(n), so just use a for loop with O(n) 21 | */ 22 | 23 | public class Solution { 24 | /** 25 | * @param num: a rotated sorted array 26 | * @return: the minimum number in the array 27 | */ 28 | public int findMin(int[] num) { 29 | if (num == null || num.length == 0) { 30 | return -1; 31 | } 32 | int min = Integer.MAX_VALUE; 33 | for (int i = 0; i < num.length; i++) { 34 | if (min > num[i]) { 35 | min = num[i]; 36 | } 37 | } 38 | return min; 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Find Minimum in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | /* 2 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 5 | 6 | Find the minimum element. 7 | 8 | You may assume no duplicate exists in the array. 9 | 10 | Example 11 | Given [4,5,6,7,0,1,2] return 0 12 | 13 | Tags Expand 14 | Binary Search 15 | 16 | Thinking process: 17 | Understand how to use binary in this problem: compare the mid point with end point. 18 | In this problem, because the sorted line is cut at one point then rotate, so one of the line is absolutely greater than the other line. 19 | Situation 1: 20 | if mid < end : that means minimum is on the end point's line. Move end to left. end = mid. 21 | Situation 2: 22 | if mid > end: that means there must be a mountain-jump somewhere after mid and before end, which is the minimum point. Now move start to mid. 23 | */ 24 | 25 | public class Solution { 26 | /** 27 | * @param num: a rotated sorted array 28 | * @return: the minimum number in the array 29 | */ 30 | public int findMin(int[] num) { 31 | if (num == null || num.length == 0) { 32 | return -1; 33 | } 34 | int start = 0; 35 | int end = num.length - 1; 36 | int mid = 0; 37 | while (start + 1 < end) { 38 | mid = start + (end - start) / 2; 39 | if (num[mid] > num[end]) { 40 | start = mid; 41 | } else { 42 | end = mid; 43 | } 44 | } 45 | if (num[start] < num[end]) { 46 | return num[start]; 47 | } else { 48 | return num[end]; 49 | } 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Find Peak Element II.java: -------------------------------------------------------------------------------- 1 | /* 2 | There is an integer matrix which has the following features: 3 | 4 | The numbers in adjacent positions are different. 5 | The matrix has n rows and m columns. 6 | For all i < m, A[0][i] < A[1][i] && A[n - 2][i] > A[n - 1][i]. 7 | For all j < n, A[j][0] < A[j][1] && A[j][m - 2] > A[j][m - 1]. 8 | We define a position P is a peek if: 9 | 10 | A[j][i] > A[j+1][i] && A[j][i] > A[j-1][i] && A[j][i] > A[j][i+1] && A[j][i] > A[j][i-1] 11 | Find a peak element in this matrix. Return the index of the peak. 12 | 13 | Have you met this question in a real interview? Yes 14 | Example 15 | Given a matrix: 16 | 17 | [ 18 | [1 ,2 ,3 ,6 ,5], 19 | [16,41,23,22,6], 20 | [15,17,24,21,7], 21 | [14,18,19,20,10], 22 | [13,14,11,10,9] 23 | ] 24 | return index of 41 (which is [1,1]) or index of 24 (which is [2,2]) 25 | 26 | Note 27 | The matrix may contains multiple peeks, find any of them. 28 | 29 | Challenge 30 | Solve it in O(n+m) time. 31 | 32 | If you come up with an algorithm that you thought it is O(n log m) or O(m log n), can you prove it is actually O(n+m) or propose a similar but O(n+m) algorithm? 33 | 34 | Tags Expand 35 | Binary Search LintCode Copyright Matrix 36 | */ 37 | 38 | /* 39 | NOT DONE. Will try if have time 40 | */ 41 | 42 | 43 | class Solution { 44 | /** 45 | * @param A: An integer matrix 46 | * @return: The index of the peak 47 | */ 48 | public List findPeakII(int[][] A) { 49 | // write your code here 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/First Missing Positive.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted integer array, find the first missing positive integer. 3 | 4 | Example 5 | Given [1,2,0] return 3, and [3,4,-1,1] return 2. 6 | 7 | Challenge 8 | Your algorithm should run in O(n) time and uses constant space. 9 | 10 | Tags Expand 11 | Array 12 | 13 | Thoughts: 14 | It means: after it's sorted, what's the first missing postive int counted from 1 ---> more 15 | 16 | 1. Arrays.sort(); 17 | 2. count = first non-zero element in A. 18 | 3. count +1, and see if maches the current A[i]? 19 | 20 | NOTE: 21 | Deal with negative and positive number separately 22 | Watch out for redundant number: ask if the list has duplicated elements 23 | */ 24 | 25 | 26 | public class Solution { 27 | /** 28 | * @param A: an array of integers 29 | * @return: an integer 30 | */ 31 | public int firstMissingPositive(int[] A) { 32 | if (A == null || A.length == 0) { 33 | return 1; 34 | } 35 | Arrays.sort(A); 36 | int count = -1; 37 | for (int i = 0; i < A.length; i++) { 38 | if (A[i] > 0) { 39 | if (count < 0) {//process 1st positive element 40 | count = A[i]; 41 | if (count != 1) { 42 | return 1; 43 | } 44 | } 45 | else if (A[i] == A[i - 1]) {//watch out for duplicates 46 | count--; 47 | } 48 | else if(A[i] != count) {//if not match, kick out 49 | return count; 50 | } 51 | count++; 52 | } 53 | } 54 | if (count < 0) {//if all negative, return 1 55 | return 1; 56 | } 57 | return count; 58 | } 59 | } -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Happy Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write an algorithm to determine if a number is happy. 3 | 4 | A happy number is a number defined by the following process: 5 | Starting with any positive integer, replace the number by the sum of the squares of its digits, 6 | and repeat the process until the number equals 1 (where it will stay), 7 | or it loops endlessly in a cycle which does not include 1. 8 | Those numbers for which this process ends in 1 are happy numbers. 9 | 10 | Example 11 | 19 is a happy number 12 | 13 | 1^2 + 9^2 = 82 14 | 8^2 + 2^2 = 68 15 | 6^2 + 8^2 = 100 16 | 1^2 + 0^2 + 0^2 = 1 17 | Tags Expand 18 | Hash Table Mathematics 19 | */ 20 | 21 | /* 22 | Thoughts: 23 | Try some examples then find out: if it's not happy number, the 'sum of square of its digits' will 24 | repeatedly occur. Use hashset to track existance. 25 | */ 26 | public class Solution { 27 | public boolean isHappy(int n) { 28 | if (n <= 0) { 29 | return false; 30 | } 31 | long sum = n; 32 | HashSet set = new HashSet(); 33 | while (sum != 1) { 34 | String s = String.valueOf(sum); 35 | sum = 0; 36 | for (char c : s.toCharArray()){ 37 | sum += (c-'0')*(c-'0'); 38 | } 39 | if (set.contains(sum)) { 40 | return false; 41 | } else { 42 | set.add(sum); 43 | } 44 | } 45 | return true; 46 | } 47 | } 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/HashWithArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Self Test: 3 | Implement HashTable with just array and integer. 4 | 5 | Thoughts: 6 | A simple approach is to % size of the array, if the key exist, move 1 slot over. 7 | 8 | A bug will be: when exceeds the size of array, there will be no avialable space, 9 | and it'll run into error. 10 | 11 | Inspired here :http://www.algolist.net/Data_structures/Hash_table/Simple_example 12 | 1. create a entry class. 13 | 2. hash the key, and put Entry into that hased index. 14 | */ 15 | 16 | Class Entry{ 17 | int key; 18 | int value; 19 | public Entry(int key, int value) { 20 | this.key = key; 21 | this.value = value; 22 | } 23 | 24 | public getKey(){ 25 | return this.key; 26 | } 27 | 28 | public getValue() { 29 | return this.value; 30 | } 31 | } 32 | 33 | Class HashMap { 34 | int[] table; 35 | int SIZE = 128; 36 | public HashMap(){ 37 | table = new int[SIZE]; 38 | for (int i = 0; i < SIZE; i++) { 39 | table[i] = null; 40 | } 41 | } 42 | 43 | public void put(int key, int value){ 44 | int hash = key % SIZE; 45 | while (table[hash] != null && table[hash].getKey() != key) { 46 | hash = (hash + 1) % SIZE; 47 | } 48 | table[key] = new Entry(key, value); 49 | } 50 | 51 | public int get(int key) { 52 | int hash = key % SIZE; 53 | while (table[hash] != null && table[hash].getKey() != key) { 54 | hash = (hash + 1) % SIZE; 55 | } 56 | if (table[hash] == null) { 57 | return -1; 58 | } 59 | return table[hash].getValue(); 60 | } 61 | } 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Identical Binary Tree.java: -------------------------------------------------------------------------------- 1 | Divide, && all. 2 | 注意 null states 3 | ``` 4 | /* 5 | Check if two binary trees are identical. Identical means the two binary trees have the same structure and every identical position has the same value. 6 | 7 | Example 8 | 1 1 9 | / \ / \ 10 | 2 2 and 2 2 11 | / / 12 | 4 4 13 | are identical. 14 | 15 | 1 1 16 | / \ / \ 17 | 2 3 and 2 3 18 | / \ 19 | 4 4 20 | are not identical. 21 | */ 22 | 23 | /* 24 | Thoughts: 25 | Do a divide and conquer traversal on left and right. 26 | && all results. 27 | */ 28 | 29 | /** 30 | * Definition of TreeNode: 31 | * public class TreeNode { 32 | * public int val; 33 | * public TreeNode left, right; 34 | * public TreeNode(int val) { 35 | * this.val = val; 36 | * this.left = this.right = null; 37 | * } 38 | * } 39 | */ 40 | public class Solution { 41 | /** 42 | * @param a, b, the root of binary trees. 43 | * @return true if they are identical, or false. 44 | */ 45 | public boolean isIdentical(TreeNode a, TreeNode b) { 46 | if (a == null && b == null) { 47 | return true; 48 | } else if ( a == null || b == null) { 49 | return false; 50 | } else { 51 | return a.val == b.val && isIdentical(a.left, b.left) && isIdentical(a.right, b.right); 52 | } 53 | } 54 | } 55 | 56 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Implement Stack.java: -------------------------------------------------------------------------------- 1 | stack 后入先出. 2 | Data Structure: ArrayList 3 | return/remove ArrayList的末尾项。 4 | 5 | ``` 6 | /* 7 | Implement Stack 8 | 9 | Implement a stack. You can use any data structure inside a stack except stack itself to implement it. 10 | 11 | 12 | Example 13 | push(1) 14 | pop() 15 | push(2) 16 | top() // return 2 17 | pop() 18 | isEmpty() // return true 19 | push(3) 20 | isEmpty() // return false 21 | Tags Expand 22 | Array Stack 23 | */ 24 | 25 | /* 26 | Thoughts: 27 | use arraylist and a index tracker - leng 28 | push: add to end 29 | pop: remove end 30 | top: get end. 31 | isEmpty: return length 32 | */ 33 | 34 | class Stack { 35 | private ArrayList list = new ArrayList(); 36 | // Push a new item into the stack 37 | public void push(int x) { 38 | list.add(x); 39 | } 40 | 41 | // Pop the top of the stack 42 | public void pop() { 43 | if (list.size() > 0) { 44 | list.remove(list.size() - 1); 45 | } 46 | } 47 | 48 | // Return the top of the stack 49 | public int top() { 50 | if (list.size() > 0) { 51 | return list.get(list.size() - 1); 52 | } 53 | return -1; 54 | } 55 | 56 | // Check the stack is empty or not. 57 | public boolean isEmpty() { 58 | return list.size() == 0; 59 | } 60 | } 61 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Interleaving Positive and Negative Numbers.java: -------------------------------------------------------------------------------- 1 | 不管遇到啥,先排个序。 2 | 这里主要要特别考虑,正数多还是负数多的问题。 3 | count一下,然后举两个小栗子就看出来端倪了。 4 | 然后Two Pointer 5 | ``` 6 | /* 7 | Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers. 8 | 9 | Example 10 | Given [-1, -2, -3, 4, 5, 6], after re-range, it will be [-1, 5, -2, 4, -3, 6] or any other reasonable answer. 11 | 12 | Note 13 | You are not necessary to keep the original order of positive integers or negative integers. 14 | 15 | Challenge 16 | Do it in-place and without extra memory. 17 | 18 | Tags Expand 19 | Two Pointers 20 | */ 21 | 22 | /* 23 | Thoughts: 24 | Sort, so it becomes [-1,-2,-3,-4,4,5,6,7] 25 | Two pointer start,end. 26 | Every round, start +=2, end -= 2; 27 | Note: have to find out how many negative/positive integers first. 28 | */ 29 | 30 | class Solution { 31 | /** 32 | * @param A: An integer array. 33 | * @return: void 34 | */ 35 | public void rerange(int[] A) { 36 | if (A == null || A.length == 0) { 37 | return; 38 | } 39 | Arrays.sort(A); 40 | int count = 0; 41 | for (int num : A){ 42 | count += num >= 0 ? 1 : -1; 43 | } 44 | int start = 0; 45 | int end = A.length - 1; 46 | if (count < 0) { 47 | start++; 48 | } else if (count > 0){ 49 | end--; 50 | } 51 | 52 | while (start < end) { 53 | if (A[start] < 0 && A[end] >= 0) { 54 | int temp = A[start]; 55 | A[start] = A[end]; 56 | A[end] = temp; 57 | } 58 | start += 2; 59 | end -= 2; 60 | } 61 | } 62 | } 63 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Largest Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | Example 5 | Given [1, 20, 23, 4, 8], the largest formed number is 8423201. 6 | 7 | Note 8 | The result may be very large, so you need to return a string instead of an integer. 9 | 10 | Tags Expand 11 | Sort 12 | 13 | Thoughts: 14 | Use a comparator with String.comareTo, then uset Arrays.sort(...) 15 | 16 | */ 17 | 18 | class CustomComparator implements Comparator { 19 | public int compare(String s1, String s2) { 20 | return (s2 + s1).compareTo(s1 + s2); 21 | } 22 | } 23 | public class Solution { 24 | /** 25 | *@param num: A list of non negative integers 26 | *@return: A string 27 | */ 28 | public String largestNumber(int[] num) { 29 | if (num == null || num.length == 0) { 30 | return ""; 31 | } 32 | String[] strs = new String[num.length]; 33 | for (int i = 0; i < num.length; i++) { 34 | strs[i] = num[i] + ""; 35 | } 36 | Arrays.sort(strs, new CustomComparator()); 37 | StringBuffer sb= new StringBuffer(); 38 | for (int i = 0; i < num.length; i++) { 39 | sb.append(strs[i]); 40 | } 41 | String rst = sb.toString(); 42 | if (rst.charAt(0) == '0') { 43 | return "0"; 44 | } 45 | return rst; 46 | } 47 | } 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Largest Rectangle in Histogram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Example 3 | Given height = [2,1,5,6,2,3], 4 | return 10. 5 | 6 | Tags Expand 7 | Array Stack 8 | 9 | Thinking Process: 10 | ///TODO: missing thinking process for Largest Rectangle in Histogram 11 | 12 | */ 13 | 14 | public class Solution { 15 | /** 16 | * @param height: A list of integer 17 | * @return: The area of largest rectangle in the histogram 18 | */ 19 | public int largestRectangleArea(int[] height) { 20 | if (height == null || height.length == 0) { 21 | return 0; 22 | } 23 | Stack stack = new Stack(); 24 | int max = 0; 25 | for (int i = 0; i <= height.length; i++) { 26 | int current = (i == height.length) ? -1 : height[i]; 27 | while (!stack.empty() && current <= height[stack.peek()]) { 28 | int h = height[stack.pop()]; 29 | int w = stack.empty() ? i : i - stack.peek() - 1; 30 | max = Math.max(max, w * h); 31 | } 32 | stack.push(i); 33 | } 34 | return max; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Last Position of Target.java: -------------------------------------------------------------------------------- 1 | ``` 2 | 有重复,不是末尾点,继续binary search 3 | /* 4 | Find the last position of a target number in a sorted array. Return -1 if target does not exist. 5 | 6 | Example 7 | Given [1, 2, 2, 4, 5, 5]. 8 | 9 | For target = 2, return 2. 10 | 11 | For target = 5, return 5. 12 | 13 | For target = 6, return -1. 14 | 15 | Tags Expand 16 | Binary Search 17 | */ 18 | 19 | /* 20 | Thoughts: 21 | Regular binary search for it. 22 | found condition: A[mid] == target && A[mid + 1] != target 23 | 24 | */ 25 | public class Solution { 26 | /** 27 | * @param A an integer array sorted in ascending order 28 | * @param target an integer 29 | * @return an integer 30 | */ 31 | public int lastPosition(int[] A, int target) { 32 | if (A == null || A.length == 0) { 33 | return -1; 34 | } 35 | int start = 0; 36 | int end = A.length - 1; 37 | int mid; 38 | 39 | while(start + 1 < end) { 40 | mid = start + (end - start)/2; 41 | if (A[mid] == target) { 42 | if (mid + 1 < A.length && A[mid + 1] == target) { 43 | start = mid; 44 | } else { 45 | return mid; 46 | } 47 | } else if (A[mid] < target) { 48 | start = mid; 49 | } else { 50 | end = mid; 51 | } 52 | } 53 | 54 | if (A[end] == target) { 55 | return end; 56 | } else if (A[start] == target) { 57 | return start; 58 | } 59 | 60 | return -1; 61 | } 62 | } 63 | 64 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Length of Last Word.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Example 7 | Given s = "Hello World", return 5. 8 | 9 | Note 10 | A word is defined as a character sequence consists of non-space characters only. 11 | 12 | Tags Expand 13 | String 14 | 15 | Thoughts: 16 | 1. Split by space 17 | 2. return last word's length 18 | 19 | Note: Java split: have to add '\\' in order to pass the key word. 20 | */ 21 | 22 | 23 | 24 | public class Solution { 25 | /** 26 | * @param s A string 27 | * @return the length of last word 28 | */ 29 | public int lengthOfLastWord(String s) { 30 | if (s == null || s.length() == 0) { 31 | return 0; 32 | } 33 | String[] arr = s.split("\\ "); 34 | String lastWord = arr[arr.length - 1]; 35 | 36 | return lastWord.length(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Longest Palindromic Substring.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 3 | 4 | Example 5 | Given the string = "abcdzdcab", return "cdzdc". 6 | 7 | Challenge 8 | O(n2) time is acceptable. Can you do it in O(n) time. 9 | 10 | Tags Expand 11 | String 12 | */ 13 | /* 14 | O(n) way, not done yet 15 | */ 16 | 17 | 18 | /* 19 | O(n^2) 20 | Thoughts: 21 | Like Palindrome Partioning II, try to use isPal[i][j] to verify each string (i,j). 22 | If string(i,j) is valid, note down the (i,j) portion and find the longest. 23 | This is a standard O(n^2) process 24 | */ 25 | public class Solution { 26 | /** 27 | * @param s input string 28 | * @return the longest palindromic substring 29 | */ 30 | public String longestPalindrome(String s) { 31 | if (s == null || s.length() == 0) { 32 | return s; 33 | } 34 | boolean isPal[][] = new boolean[s.length()][s.length()]; 35 | String maxStr = ""; 36 | for (int j = 0; j < s.length(); j++) { 37 | for (int i = 0; i <= j; i++) { 38 | if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || isPal[i + 1][j - 1])) { 39 | isPal[i][j] = true; 40 | maxStr = maxStr.length() > s.substring(i, j + 1).length() ? maxStr : s.substring(i, j + 1); 41 | } 42 | } 43 | }//end for j 44 | return maxStr; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Majority Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it. 3 | 4 | Example 5 | For [1, 1, 1, 1, 2, 2, 2], return 1 6 | 7 | Challenge 8 | O(n) time and O(1) space 9 | 10 | Tag: Enumeration 11 | 12 | Thinking process: 13 | Natural thinking process: count how many you have for 1st element, if next one is the same, count++, if next one is not the same, count- -. 14 | When count ==0, that means other types of element has same amount as the 1st majority number, they are even. 15 | From this point, count the value at current position as the majority number, keep the loop rolling. 16 | Note: this solutions works only when the given array has a valid solution. 17 | CounterCase:[111223], with actually return 3 as the majority number. But again, this is not a valid input in this case. 18 | */ 19 | 20 | public class Solution { 21 | /** 22 | * @param nums: a list of integers 23 | * @return: find a majority number 24 | */ 25 | public int majorityNumber(ArrayList nums) { 26 | if (nums == null || nums.size() == 0) { 27 | return -1; 28 | } 29 | int majorNum = nums.get(0); 30 | int count = 1; 31 | for (int i = 1; i < nums.size(); i++) { 32 | if (majorNum == nums.get(i)) { 33 | count++; 34 | } else { 35 | count--; 36 | } 37 | if (count == 0) { 38 | majorNum = nums.get(i); 39 | count = 1; 40 | } 41 | } 42 | return majorNum; 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | DFS 2 | Divide and conquer 3 | ``` 4 | /* 5 | 71% Accepted 6 | Given a binary tree, find its maximum depth. 7 | 8 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 9 | 10 | Example 11 | Given a binary tree as follow: 12 | 13 | 1 14 | 15 | / \ 16 | 17 | 2 3 18 | 19 | / \ 20 | 21 | 4 5 22 | 23 | The maximum depth is 3 24 | 25 | Tags Expand 26 | Tree Binary Tree Depth First Search 27 | 28 | Thinking process: 29 | check if root is null, return 0 if so. 30 | Divide and return integer as the depth 31 | Conquer: find the max and return depth + 1. 32 | */ 33 | 34 | /** 35 | * Definition of TreeNode: 36 | * public class TreeNode { 37 | * public int val; 38 | * public TreeNode left, right; 39 | * public TreeNode(int val) { 40 | * this.val = val; 41 | * this.left = this.right = null; 42 | * } 43 | * } 44 | */ 45 | public class Solution { 46 | /** 47 | * @param root: The root of binary tree. 48 | * @return: An integer. 49 | */ 50 | public int maxDepth(TreeNode root) { 51 | if (root == null) { 52 | return 0; 53 | } 54 | 55 | int left = maxDepth(root.left); 56 | int right = maxDepth(root.right); 57 | 58 | return Math.max(left, right) + 1; 59 | } 60 | } 61 | 62 | 63 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Maximum Subarray III.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Given an array of integers and a number k, find k non-overlapping subarrays which have the largest sum. 4 | 5 | The number in each subarray should be contiguous. 6 | 7 | Return the largest sum. 8 | 9 | Have you met this question in a real interview? Yes 10 | Example 11 | Given [-1,4,-2,3,-2,3], k=2, return 8 12 | 13 | Note 14 | The subarray should contain at least one number 15 | 16 | Tags Expand 17 | LintCode Copyright Dynamic Programming Subarray Array 18 | */ 19 | 20 | /* 21 | NOT DONE 22 | */ 23 | public class Solution { 24 | /** 25 | * @param nums: A list of integers 26 | * @param k: An integer denote to find k non-overlapping subarrays 27 | * @return: An integer denote the sum of max k non-overlapping subarrays 28 | */ 29 | public int maxSubArray(ArrayList nums, int k) { 30 | // write your code 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Median of two Sorted Arrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Median of two Sorted Arrays 4 | 5 | There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. 6 | 7 | Example 8 | Given A=[1,2,3,4,5,6] and B=[2,3,4,5], the median is 3.5. 9 | 10 | Given A=[1,2,3] and B=[4,5], the median is 3. 11 | 12 | Challenge 13 | The overall run time complexity should be O(log (m+n)). 14 | 15 | Tags Expand 16 | Sorted Array Divide and Conquer Array Zenefits Uber Google 17 | 18 | */ 19 | 20 | /* 21 | Thoughts: 22 | Trivial: merge and find median. NOPE: have to be in log(m+n) time 23 | http://www.jiuzhang.com/solutions/median-of-two-sorted-arrays/ 24 | 25 | http://fisherlei.blogspot.com/2012/12/leetcode-median-of-two-sorted-arrays.html 26 | 27 | */ 28 | 29 | class Solution { 30 | /** 31 | * @param A: An integer array. 32 | * @param B: An integer array. 33 | * @return: a double whose format is *.5 or *.0 34 | */ 35 | public double findMedianSortedArrays(int[] A, int[] B) { 36 | // write your code here 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | A够长,那么可以从A的尾部开始加新元素。 2 | 注意,从尾部,是大数字优先的。 3 | ``` 4 | /* 5 | Given two sorted integer arrays A and B, merge B into A as one sorted array. 6 | 7 | Note 8 | You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively. 9 | 10 | Example 11 | A = [1, 2, 3, empty, empty] B = [4,5] 12 | 13 | After merge, A will be filled as [1,2,3,4,5] 14 | 15 | Tags Expand 16 | Array Sorted Array 17 | */ 18 | 19 | /* 20 | Thinking process: 21 | 1. start from the end, track back. End index = m + n; 22 | 2. when ever check a position, need to do index-1, because index=m+n is the size of array. 23 | 3. Make sure to clean up the second array B. 24 | */ 25 | class Solution { 26 | /** 27 | * @param A: sorted integer array A which has m elements, 28 | * but size of A is m+n 29 | * @param B: sorted integer array B which has n elements 30 | * @return: void 31 | */ 32 | public void mergeSortedArray(int[] A, int m, int[] B, int n) { 33 | // write your code here 34 | int index = m + n; 35 | while (m > 0 && n > 0) { 36 | if (A[m - 1] > B[n - 1]) { 37 | A[--index] = A[--m]; 38 | } else { 39 | A[--index] = B[--n]; 40 | } 41 | }//While 42 | 43 | while (n > 0) { 44 | A[--index] = B[--n]; 45 | } 46 | } 47 | } 48 | 49 | 50 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Middle of Linked List.java: -------------------------------------------------------------------------------- 1 | 快慢指针 2 | 3 | 不在乎slow是不是到底,因为fast肯定先到。 4 | 确保fast, fast.next不是Null就好 5 | 6 | 7 | return slow 8 | ``` 9 | /* 10 | Find the middle node of a linked list. 11 | 12 | Have you met this question in a real interview? Yes 13 | Example 14 | Given 1->2->3, return the node with value 2. 15 | 16 | Given 1->2, return the node with value 1. 17 | 18 | Tags Expand 19 | Linked List 20 | 21 | */ 22 | /* 23 | Thoughts: 24 | Practice LinkedList, fast and slow pointer 25 | */ 26 | 27 | public class Solution { 28 | /** 29 | * @param head: the head of linked list. 30 | * @return: a middle node of the linked list 31 | */ 32 | public ListNode middleNode(ListNode head) { 33 | if (head == null || head.next == null) { 34 | return head; 35 | } 36 | 37 | ListNode slow = head; 38 | ListNode fast = head.next; 39 | while (fast!= null && fast.next != null) { 40 | slow = slow.next; 41 | fast = fast.next.next; 42 | } 43 | return slow; 44 | } 45 | } 46 | 47 | 48 | /** 49 | * Definition for ListNode 50 | * public class ListNode { 51 | * int val; 52 | * ListNode next; 53 | * ListNode(int x) { 54 | * val = x; 55 | * next = null; 56 | * } 57 | * } 58 | */ 59 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Min Stack.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | 双Stack:一个正常stack,另一个minStack存当下level最小值. 注意维护minStack的变化 4 | 5 | 6 | ``` 7 | /* 8 | Implement a stack with min() function, which will return the smallest number in the stack. 9 | 10 | It should support push, pop and min operation all in O(1) cost. 11 | 12 | Example 13 | push(1) 14 | pop() // return 1 15 | push(2) 16 | push(3) 17 | min() // return 2 18 | push(1) 19 | min() // return 1 20 | Note 21 | min operation will never be called if there is no number in the stack. 22 | 23 | Tags Expand 24 | Stack 25 | 26 | Thoughts: 27 | using 2 stacks: one regular, the other one trackes min element 28 | MinStack (0 ~ i): for i elements in regular stack, at each ith, the min element is stored at MinStack(i). This means, there can be duplicated mins for different ith. 29 | 30 | Note: remember to check if minStack isEmpty(), empty stack does not have peek() 31 | */ 32 | 33 | public class MinStack { 34 | private Stack stack; 35 | private Stack minStack; 36 | public MinStack() { 37 | stack = new Stack(); 38 | minStack = new Stack(); 39 | } 40 | 41 | public void push(int number) { 42 | stack.push(number); 43 | if (minStack.isEmpty()) { 44 | minStack.push(number); 45 | } else { 46 | minStack.push(minStack.peek() >= number ? number : minStack.peek()); 47 | } 48 | } 49 | 50 | public int pop() { 51 | minStack.pop(); 52 | return stack.pop(); 53 | } 54 | 55 | public int min() { 56 | return minStack.peek(); 57 | } 58 | } 59 | 60 | 61 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Minimum Subarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, find the subarray with smallest sum. 3 | 4 | Return the sum of the subarray. 5 | 6 | Example 7 | For [1, -1, -2, 1], return -3 8 | 9 | Note 10 | The subarray should contain at least one integer. 11 | 12 | Tags Expand 13 | Greedy LintCode Copyright Subarray Array 14 | 15 | Thoughts: 16 | Note: sub-array has order. It's not sub-set 17 | 1. On each index: decide to add with nums.get(i), to use the new lowest value nums.get(i). That means: 18 | If the new value is negative (it has decresing impact on sum) and the sum is larger than new value, just use the new value. 19 | In another case, if sum has been nagative, so sum + new value will be even smaller, then use sum. 20 | 2. Every time compare the currMin with the overall minimum value, call it minRst. 21 | 22 | Note: remember to pre-set init value for curMin, minRst. 23 | */ 24 | 25 | 26 | public class Solution { 27 | /** 28 | * @param nums: a list of integers 29 | * @return: A integer indicate the sum of minimum subarray 30 | */ 31 | public int minSubArray(ArrayList nums) { 32 | if (nums == null || nums.size() == 0) { 33 | return 0; 34 | } 35 | int curMin = nums.get(0); 36 | int minRst = nums.get(0); 37 | for (int i = 1; i < nums.size(); i++) { 38 | curMin = Math.min(nums.get(i), curMin + nums.get(i)); 39 | minRst = Math.min(curMin, minRst); 40 | } 41 | return minRst; 42 | } 43 | } -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/MinimumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | 6 | Example 7 | Given a binary tree as follow: 8 | 9 | 1 10 | 11 | / \ 12 | 13 | 2 3 14 | 15 | / \ 16 | 17 | 4 5 18 | 19 | The minimum depth is 2 20 | 21 | Tags Expand 22 | Depth First Search 23 | 24 | Thinking Process: 25 | Note: a little different from maxDepth: 26 | If 1,#,2: the left route 1-# does not count as a path, so the minDepth is actually 2 in this example. 27 | We need a helper function to calculate the minimum. 28 | */ 29 | 30 | /** 31 | * Definition of TreeNode: 32 | * public class TreeNode { 33 | * public int val; 34 | * public TreeNode left, right; 35 | * public TreeNode(int val) { 36 | * this.val = val; 37 | * this.left = this.right = null; 38 | * } 39 | * } 40 | */ 41 | public class Solution { 42 | /** 43 | * @param root: The root of binary tree. 44 | * @return: An integer. 45 | */ 46 | //recursive: 47 | public int minDepth(TreeNode root) { 48 | if (root == null) { 49 | return 0; 50 | } 51 | return getMin(root); 52 | } 53 | 54 | public int getMin(TreeNode root) { 55 | if (root == null) { 56 | return Integer.MAX_VALUE; 57 | } 58 | if (root.left == null && root.right == null) { 59 | return 1; 60 | } 61 | return Math.min(getMin(root.left), getMin(root.right)) + 1; 62 | } 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Nim Game.java: -------------------------------------------------------------------------------- 1 | 著名Nim游戏。 2 | 写一些,发现n=4,5,6,7,8...etc之后的情况有规律性。 3 | 最终很简单n%4!=0就可以了 4 | ``` 5 | /* 6 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 7 | 8 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 9 | 10 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 11 | 12 | Hint: 13 | 14 | If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner? 15 | 16 | 17 | Hide Similar Problems (M) Flip Game II 18 | 19 | */ 20 | 21 | 22 | /* 23 | Thoughts: 24 | If n = 4, we can do the following: 25 | 1 0 0 0 26 | 1 1 0 0 27 | 1 1 1 0 28 | But we'll fail. 29 | 30 | n = 5, we pick 1, 2nd player gets n = 4. 31 | n = 6, we pick 2, 2nd player gets n = 4. 32 | n = 7, we pick 3, 2nd player gets n = 4. 33 | n = 8, regarless whatever we pick, the opponent can make 1st gets n = 4, we fail. 34 | ... 35 | ... 36 | whenever n % 4 = 0, 1st player fail. 37 | 38 | */ 39 | 40 | public class Solution { 41 | public boolean canWinNim(int n) { 42 | return n % 4 != 0; 43 | } 44 | } 45 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Nth to Last Node in List.java: -------------------------------------------------------------------------------- 1 | 先找到nth node 2 | 然后head开始跑。 3 | 4 | node 到底,而head ~ node刚好是 n 距离。所以head就是要找的last nth 5 | ``` 6 | /* 7 | Find the nth to last element of a singly linked list. 8 | 9 | The minimum number of nodes in list is n. 10 | 11 | Example 12 | Given a List 3->2->1->5->null and n = 2, return node whose value is 1. 13 | 14 | Tags Expand 15 | Cracking The Coding Interview Linked List 16 | 17 | Thinking process: 18 | 1. Find nth node in normal order. 19 | 2. Have a head at index0. 20 | 3. Move both head and nth node. WHen nth node hit null/end, then the moving head is the nth to last node in list. 21 | */ 22 | 23 | /** 24 | * Definition for ListNode. 25 | * public class ListNode { 26 | * int val; 27 | * ListNode next; 28 | * ListNode(int val) { 29 | * this.val = val; 30 | * this.next = null; 31 | * } 32 | * } 33 | */ 34 | public class Solution { 35 | /** 36 | * @param head: The first node of linked list. 37 | * @param n: An integer. 38 | * @return: Nth to last node of a singly linked list. 39 | */ 40 | ListNode nthToLast(ListNode head, int n) { 41 | if (head == null || n < 0) { 42 | return null; 43 | } 44 | int count = 0; 45 | ListNode node = head; 46 | while (node != null && count < n) { 47 | node = node.next; 48 | count++; 49 | } 50 | while (node != null) { 51 | node = node.next; 52 | head = head.next; 53 | } 54 | return head; 55 | } 56 | } 57 | 58 | 59 | 60 | 61 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/O(1) Check Power of 2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Using O(1) time to check whether an integer n is a power of 2. 3 | Example 4 | For n=4, return true 5 | 6 | For n=5, return false 7 | 8 | Challenge 9 | O(1) time 10 | 11 | Tags Expand 12 | Binary 13 | 14 | Thinking process: 15 | Any integer that's power of 2, follows one pattern. They are all: 1000000000....000 format. 16 | so (n - 1) becomes: 01111111111...111. 17 | If bit-and them togeter, it will be 0. 18 | 19 | */ 20 | 21 | class Solution { 22 | /* 23 | * @param n: An integer 24 | * @return: True or false 25 | */ 26 | public boolean checkPowerOf2(int n) { 27 | if (n <= 0) { 28 | return false; 29 | } 30 | return (n & (n - 1)) == 0; 31 | } 32 | }; 33 | 34 | 35 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Partition Array by Odd and Even.java: -------------------------------------------------------------------------------- 1 | /* 2 | Partition an integers array into odd number first and even number second. 3 | 4 | Example 5 | Given [1, 2, 3, 4], return [1, 3, 2, 4] 6 | 7 | Challenge 8 | Do it in-place. 9 | 10 | Tags Expand 11 | Two Pointers Array 12 | 13 | Thougths: 14 | Use two pointers: nextOddPt, firstEvenPt 15 | 1. Whenever nextOddPt > firstEvenPt, swapt them 16 | 2. Incrase nextOddPt in a for loop 17 | Note: 18 | After each swap, have to start checking again from beginning-switching point, which will be firstEvenPt. Need to set i = firstEvenPt. 19 | However, since for loop will do i++, we need to set i = firstEvenPt - 1; 20 | And firstEvenPt only needs to be update once so use -1 to check if it's set. 21 | */ 22 | 23 | public class Solution { 24 | /** 25 | * @param nums: an array of integers 26 | * @return: nothing 27 | */ 28 | public void partitionArray(int[] nums) { 29 | if (nums == null || nums.length == 0){ 30 | return; 31 | } 32 | int nextOddPt = -1; 33 | int firstEvenPt = -1; 34 | for (int i = 0; i < nums.length; i++) { 35 | if (nums[i] % 2 == 1) { 36 | nextOddPt = i; 37 | } else { 38 | if (firstEvenPt == -1) { 39 | firstEvenPt = i; 40 | } 41 | } 42 | if (nextOddPt > firstEvenPt && firstEvenPt != -1) { 43 | int temp = nums[nextOddPt]; 44 | nums[nextOddPt] = nums[firstEvenPt]; 45 | nums[firstEvenPt] = temp; 46 | i = firstEvenPt - 1; 47 | firstEvenPt = -1; 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Pow(x,n).java: -------------------------------------------------------------------------------- 1 | 注意n/2的奇数偶数。 2 | n的正负。 3 | n == 0的情况。 4 | ``` 5 | /* 6 | Pow(x, n) 7 | 8 | Implement pow(x, n). 9 | 10 | Have you met this question in a real interview? Yes 11 | Example 12 | Pow(2.1, 3) = 9.261 13 | Pow(0, 1) = 0 14 | Pow(1, 0) = 1 15 | Note 16 | You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than 1e-3. 17 | 18 | Challenge 19 | O(logn) time 20 | 21 | Tags Expand 22 | Binary Search LinkedIn Divide and Conquer Mathematics Facebook 23 | */ 24 | 25 | /* 26 | Everytime: if divide the power n by 2, then it equlas to pow(x,n/2) * pow(x, n/2). 27 | Also consider n could be negative. Let myPow handle the negative n. basically return 1/myPow(x,n) 28 | Cnsider the case of 0: x^0 = 1. 29 | use a helper funtion: when n%2 == 0, regular; if n%2 ==1, do pow(x, (n-1)/2) * x. 30 | Note: n/2 = (n-1)/2. So this can be optmized. 31 | */ 32 | 33 | public class Solution { 34 | /** 35 | * @param x the base number 36 | * @param n the power number 37 | * @return the result 38 | */ 39 | public double myPow(double x, int n) { 40 | if(n >= 0) { 41 | return pow(x, n); 42 | } else { 43 | return 1/pow(x, n); 44 | } 45 | } 46 | 47 | public double pow(double x, int n) { 48 | if (n == 0) { 49 | return 1; 50 | } 51 | double num = pow(x, n/2); 52 | if (n % 2 == 0) { 53 | return num * num; 54 | } 55 | return num * num * x; 56 | } 57 | } 58 | 59 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Product of Array Exclude Itself.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integers array A. 3 | 4 | Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation. 5 | 6 | Example 7 | For A = [1, 2, 3], return [6, 3, 2]. 8 | 9 | Tags Expand 10 | Forward-Backward Traversal LintCode Copyright 11 | 12 | Thought: 13 | Trivial way would be first calculate the zigma(A[0]* ... A[n-1]) then divide by B[i]. However, not allowed in this question. 14 | 15 | The other way: do for loop again and again? that will be n^2 time. 16 | 17 | */ 18 | 19 | 20 | 21 | public class Solution { 22 | /** 23 | * @param A: Given an integers array A 24 | * @return: A Long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] 25 | */ 26 | public ArrayList productExcludeItself(ArrayList A) { 27 | if (A == null || A.size() == 0) { 28 | return null; 29 | } 30 | ArrayList rst = new ArrayList(); 31 | for (int i = 0; i < A.size(); i++) { 32 | long num = 1; 33 | for (int j = 0; j < A.size(); j++) { 34 | if (j != i) { 35 | num *= A.get(j); 36 | } 37 | } 38 | rst.add(num); 39 | } 40 | return rst; 41 | } 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Remove Duplicates from Sorted List.java: -------------------------------------------------------------------------------- 1 | 一旦node.next 和node是重复,跳 2 | ``` 3 | /* 4 | 40% 通过 5 | Given a sorted linked list, delete all duplicates such that each element appear only once. 6 | 7 | 样例 8 | Given 1->1->2, return 1->2. 9 | Given 1->1->2->3->3, return 1->2->3. 10 | 11 | 标签 Expand 12 | Linked List 13 | 14 | Thinking process: 15 | check head null 16 | Use dummy node to reserve head 17 | while everything when head.next is not null 18 | compare head.val == head.next.val? 19 | If so, head.next = head.next.next 20 | */ 21 | 22 | /** 23 | * Definition for ListNode 24 | * public class ListNode { 25 | * int val; 26 | * ListNode next; 27 | * ListNode(int x) { 28 | * val = x; 29 | * next = null; 30 | * } 31 | * } 32 | */ 33 | public class Solution { 34 | /** 35 | * @param ListNode head is the head of the linked list 36 | * @return: ListNode head of linked list 37 | */ 38 | public static ListNode deleteDuplicates(ListNode head) { 39 | if (head == null) { 40 | return head; 41 | } 42 | ListNode node = head; 43 | while (node.next != null) { 44 | if (node.val == node.next.val) { 45 | node.next = node.next.next; 46 | } else { 47 | node = node.next; 48 | } 49 | } 50 | return head; 51 | } 52 | } 53 | 54 | 55 | 56 | 57 | /* 58 | Use two pointers: 59 | http://gongxuns.blogspot.com/2012/12/leetcode-remove-duplicates-from-sorted_11.html 60 | */ 61 | 62 | 63 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Remove Linked List Elements.java: -------------------------------------------------------------------------------- 1 | 如果match. parent.next = node.next. 2 | 如果不match, parent 和 node 一起移动 3 | ``` 4 | /* 5 | Remove all elements from a linked list of integers that have value val. 6 | 7 | Have you met this question in a real interview? Yes 8 | Example 9 | Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5 10 | 11 | Tags Expand 12 | Linked List 13 | */ 14 | 15 | /* 16 | Thoughts: 17 | While loop through. Maintain a parent, so it can be used to skip current node. 18 | */ 19 | 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * public class ListNode { 24 | * int val; 25 | * ListNode next; 26 | * ListNode(int x) { val = x; } 27 | * } 28 | */ 29 | public class Solution { 30 | /** 31 | * @param head a ListNode 32 | * @param val an integer 33 | * @return a ListNode 34 | */ 35 | public ListNode removeElements(ListNode head, int val) { 36 | if (head == null) { 37 | return head; 38 | } 39 | ListNode parent = new ListNode(0); 40 | parent.next = head; 41 | ListNode dummy = parent; 42 | while (head != null) { 43 | if (head.val == val) { 44 | parent.next = head.next; 45 | } else { 46 | parent = parent.next; 47 | } 48 | head = head.next; 49 | } 50 | return dummy.next; 51 | } 52 | } 53 | 54 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Reverse Integer.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer). 3 | 4 | Example 5 | Given x = 123, return 321 6 | 7 | Given x = -123, return -321 8 | 9 | Tags Expand 10 | Integer 11 | 12 | Thoughts: 13 | 1. Use long to capture the result. If > Integer.MAX_VALUE,return 0; 14 | 2. Use string to reverse, the conver to long 15 | 3. use string builder to reverse string 16 | 17 | */ 18 | 19 | 20 | public class Solution { 21 | /** 22 | * @param n the integer to be reversed 23 | * @return the reversed integer 24 | */ 25 | public int reverseInteger(int n) { 26 | long num = (long)n; 27 | int sign = n > 0 ? 1 : -1; 28 | String rst = new StringBuilder(Math.abs(num)+"").reverse().toString(); 29 | num = Long.parseLong(rst) * sign; 30 | 31 | if (num > Integer.MAX_VALUE || num < Integer.MIN_VALUE) { 32 | return 0; 33 | } else { 34 | return (int)num; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Reverse Linked List.java: -------------------------------------------------------------------------------- 1 | E 2 | 3 | 建立新list。每次把newList append 在current node的后面。 4 | 用head来循环所有node。 5 | 6 | ``` 7 | /* 8 | Reverse a linked list. 9 | 10 | Have you met this question in a real interview? Yes 11 | Example 12 | For linked list 1->2->3, the reversed linked list is 3->2->1 13 | 14 | Challenge 15 | Reverse it in-place and in one-pass 16 | 17 | Tags Expand 18 | Linked List Facebook Uber 19 | */ 20 | 21 | //Use empty node, add to tail, append empty node to next node. keep going like that 22 | public class Solution { 23 | public ListNode reverseList(ListNode head) { 24 | if (head == null || head.next == null) { 25 | return head; 26 | } 27 | ListNode newList = null; 28 | 29 | while (head != null) { 30 | ListNode temp = head.next; 31 | head.next = newList; 32 | newList = head; 33 | head = temp; 34 | } 35 | return newList; 36 | } 37 | } 38 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Rotate Image.java: -------------------------------------------------------------------------------- 1 | M 2 | 3 | 找到个转角度的规律公式。用一个temp。in place. 4 | 5 | ``` 6 | /* 7 | You are given an n x n 2D matrix representing an image. 8 | Rotate the image by 90 degrees (clockwise). 9 | 10 | Have you met this question in a real interview? Yes 11 | Example 12 | Given a matrix 13 | 14 | [ 15 | [1,2], 16 | [3,4] 17 | ] 18 | rotate it by 90 degrees (clockwise), return 19 | 20 | [ 21 | [3,1], 22 | [4,2] 23 | ] 24 | Challenge 25 | Do it in-place. 26 | 27 | Tags Expand 28 | Cracking The Coding Interview Matrix 29 | */ 30 | 31 | 32 | //in matrix, to find next position: r = c; c = (w - r). Work on the equation => oldR = w - c, oldC = r 33 | //In pace: do loop, change 4 at once. do a quater of the matrix 34 | public class Solution { 35 | public void rotate(int[][] matrix) { 36 | if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 37 | return; 38 | } 39 | int width = matrix.length; 40 | for (int i = 0; i < width/2; i++) { 41 | for (int j = 0; j < Math.ceil(width/2.0); j++) { 42 | int temp = matrix[i][j]; 43 | matrix[i][j] = matrix[width - 1 - j][i]; 44 | matrix[width - 1 - j][i] = matrix[width - 1 - i][width - 1 - j]; 45 | matrix[width - 1 - i][width - 1 - j] = matrix[j][width - 1 - i]; 46 | matrix[j][width - 1 - i] = temp; 47 | } 48 | } 49 | } 50 | } 51 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Rotate String.java: -------------------------------------------------------------------------------- 1 | 还是三步rotate. 2 | 有个坑:offset可能很长,那么要%length,才能得到真正需要rotate的部分。 3 | Note: rotate 一个 full length之后,是string 不变 4 | ``` 5 | /* 6 | 17% Accepted 7 | Given a string and an offset, rotate string by offset. (rotate from left to right) 8 | 9 | Example 10 | Given "abcdefg" 11 | 12 | for offset=0, return "abcdefg" 13 | 14 | for offset=1, return "gabcdef" 15 | 16 | for offset=2, return "fgabcde" 17 | 18 | for offset=3, return "efgabcd" 19 | 20 | ... 21 | 22 | 23 | Tags Expand 24 | String 25 | */ 26 | 27 | public class Solution { 28 | /* 29 | * param A: A string 30 | * param offset: Rotate string with offset. 31 | * return: Rotated string. 32 | */ 33 | public char[] rotateString(char[] A, int offset) { 34 | if (A == null || A.length == 0) return A; 35 | offset = offset % (A.length); 36 | reverse(A, 0, A.length - offset - 1); 37 | reverse(A, A.length - offset, A.length - 1); 38 | reverse(A, 0, A.length - 1); 39 | return A; 40 | } 41 | 42 | 43 | //Helper function: reverse certain range of array 44 | public void reverse(char[] A, int start, int end) { 45 | for (int i = start, j = end; i < j; i++, j--) { 46 | char temp = A[j]; 47 | A[j] = A[i]; 48 | A[i] = temp; 49 | } 50 | } 51 | }; 52 | 53 | 54 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Single Number II.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given 3*n + 1 numbers, every numbers occurs triple times except one, find it. 3 | Example 4 | Given [1,1,2,3,3,3,2,2,4,1] return 4 5 | 6 | Challenge 7 | One-pass, constant extra space 8 | Thinking process: 9 | Still using bit manipulation. We need to erase all of the 3-appearance number and leave the single number out. A few steps: 10 | Store the final result by continuously bit OR with the result variable. 11 | Want to XOR the 3 numbers, but can’t erase them as if only 2 duplicate numbers:Consider the number as 3-based number, so XOR can be understand this way 12 | when add 3 numbers together, add each individual bit. If the sum is 3, then set it as 0. If not 3, leave as is. 13 | 3. Store the bits in a integer array, which simulates a binary version of the integer 14 | 4. When each bit’s XOR process finishes, bit OR it with result 15 | */ 16 | 17 | public class Solution { 18 | public int singleNumberII(int[] A) { 19 | if (A == null || A.length == 0) { 20 | return -1; 21 | } 22 | //present the XOR results in binary format 23 | int[] bits = new int[32]; 24 | int rst = 0; 25 | for (int i = 0; i < 32; i++) { 26 | for (int j = 0; j < A.length; j++){ 27 | //XOR the numbers in a 3-base fashion. Whenever bit[i] has a number 3, set it back to 0. 28 | bits[i] += A[j] >> i & 1; 29 | bits[i] %= 3; 30 | } 31 | //OR it to the result. However, each time only the i - spot is updated with the bits[i]. 32 | rst |= bits[i] << i; 33 | } 34 | return rst; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Single Number.java: -------------------------------------------------------------------------------- 1 | /* 2 | 62% Accepted 3 | Given 2*n + 1 numbers, every numbers occurs twice except one, find it. 4 | 5 | Example 6 | Given [1,2,2,1,3,4,3], return 4 7 | 8 | Challenge 9 | One-pass, constant extra space 10 | 11 | Tags Expand 12 | Greedy 13 | 14 | Manipulate bits: 15 | Thinking process: 16 | One-pass and constant extra space. 17 | since all numbers appears twice, consider them as in bits format. Two identical number XOR will be zero. If we XOR everything double-numbers together, it will be zero. At the end, we use o XOR our target number, the result is actually the target number. 18 | Very smart trick to use bits. 19 | In order to compare from index 0 to the end, we need to extract index 0 first as result before for loop. And start for loop at i = 1. 20 | */ 21 | 22 | public class Solution { 23 | /** 24 | *@param A : an integer array 25 | *return : a integer 26 | */ 27 | public int singleNumber(int[] A) { 28 | if (A == null || A.length == 0) { 29 | return 0; 30 | } 31 | int rst = A[0]; 32 | for (int i = 1; i < A.length; i++) { 33 | rst = rst ^ A[i]; 34 | } 35 | return rst; 36 | } 37 | } 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Singleton.java: -------------------------------------------------------------------------------- 1 | /* 2 | Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton. 3 | 4 | You job is to implement a getInstance method for given class, return the same instance of this class every time you call this method. 5 | 6 | 7 | Example 8 | In Java: 9 | 10 | A a = A.getInstance(); 11 | A b = A.getInstance(); 12 | a should equal to b. 13 | 14 | Challenge 15 | If we call getInstance concurrently, can you make sure your code could run correctly? 16 | 17 | Tags Expand 18 | LintCode Copyright OO Design 19 | 20 | Thoughts: 21 | ... 22 | Was not clear to me. Need to loop up more on synchronized/volatile 23 | Good reference: 24 | http://www.cnblogs.com/EdwardLiu/p/4443230.html 25 | 26 | */ 27 | 28 | 29 | class Solution { 30 | public static volatile Solution solution = null; 31 | /** 32 | * @return: The same instance of this class every time 33 | */ 34 | public static Solution getInstance() { 35 | if (solution == null) { 36 | synchronized (Solution.class) { 37 | // Double check 38 | if (solution == null) { 39 | solution = new Solution(); 40 | } 41 | } 42 | } 43 | return solution; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Sqrt(x).java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | 6 | Example 7 | sqrt(3) = 1 8 | 9 | sqrt(4) = 2 10 | 11 | sqrt(5) = 2 12 | 13 | sqrt(10) = 3 14 | Challenge 15 | O(log(x)) 16 | 17 | Tags Expand 18 | Binary Search 19 | 20 | Thinking process: 21 | Binary search. While loop until the head and tail meets. 22 | */ 23 | 24 | class Solution { 25 | /** 26 | * @param x: An integer 27 | * @return: The sqrt of x 28 | */ 29 | public int sqrt(int x) { 30 | long start = 0; 31 | long end = x; 32 | while (end >= start) { 33 | long mid = start + (end - start) / 2; 34 | if (mid * mid > x) { 35 | end = mid - 1; 36 | } else if (mid * mid < x) { 37 | start = mid + 1; 38 | } else { 39 | return (int)mid; 40 | } 41 | } 42 | //When start > end, while loop ends. That means, end must be the largest possible integer that end^2 is closest to x. 43 | return (int)end; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Swap Nodes in Pairs.java: -------------------------------------------------------------------------------- 1 | swap总是confuse. 2 | 画三个block, 1,2,3. 连线。 3 | ``` 4 | /* 5 | Swap Nodes in Pairs 6 | 7 | Given a linked list, swap every two adjacent nodes and return its head. 8 | 9 | Example 10 | Given 1->2->3->4, you should return the list as 2->1->4->3. 11 | 12 | Challenge 13 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 14 | 15 | Tags Expand 16 | Linked List 17 | */ 18 | 19 | /* 20 | Thoughts: 21 | 1. swap 22 | 2. move 2 steps, then swap again. 23 | 3. becareful node.next == null, that's the end of list. no swapping. 24 | */ 25 | 26 | /** 27 | * Definition for singly-linked list. 28 | * public class ListNode { 29 | * int val; 30 | * ListNode next; 31 | * ListNode(int x) { val = x; } 32 | * } 33 | */ 34 | 35 | public class Solution { 36 | /** 37 | * @param head a ListNode 38 | * @return a ListNode 39 | */ 40 | public ListNode swapPairs(ListNode head) { 41 | if (head == null) { 42 | return head; 43 | } 44 | ListNode dummy = new ListNode(0); 45 | dummy.next = head; 46 | head = dummy; 47 | while (head.next != null && head.next.next != null) { 48 | ListNode n1 = head.next; 49 | ListNode n2 = head.next.next; 50 | 51 | n1.next = n2.next; 52 | n2.next = n1; 53 | n1 = n2; 54 | 55 | head = head.next.next; 56 | } 57 | return dummy.next; 58 | } 59 | } 60 | 61 | ``` -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Unique Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 3 | 4 | 5 | 6 | Example 7 | Given n = 3, there are a total of 5 unique BST's. 8 | 9 | 1 3 3 2 1 10 | \ / / / \ \ 11 | 3 2 1 1 3 2 12 | / / \ \ 13 | 2 1 2 3 14 | Tags Expand 15 | Catalan Number Dynamic Programming 16 | 17 | Thinking proces: 18 | Knowing what is Catalan number. 19 | C(n+1) = SUM(C(i)*C(n-i)) 20 | OR: C(n) = SUM(C(i)*C(n-i-1)). 21 | */ 22 | 23 | public class Solution { 24 | /** 25 | * @paramn n: An integer 26 | * @return: An integer 27 | */ 28 | public int numTrees(int n) { 29 | if (n <= 1) { 30 | return 1; 31 | } 32 | int[] count = new int[n + 1]; 33 | count[0] = 1; 34 | count[1] = 1; 35 | for (int i = 2; i < n + 1; i++) { 36 | for (int j = 0; j < i; j++) { 37 | count[i] += count[j] * count[i - j - 1]; 38 | } 39 | } 40 | return count[n]; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Others/old records/LintCode-Backup/Update Bits.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j) 3 | 4 | 5 | 6 | Example 7 | Given N = (10000000000)2, M = (10101)2, i = 2, j = 6 8 | 9 | return N = (10001010100)2 10 | 11 | Challenge 12 | Minimum number of operations? 13 | 14 | Tags Expand 15 | Cracking The Coding Interview Bit Manipulation Binary Representation 16 | 17 | Thinking process: 18 | Create a mask: xxxx000000xxxx. 19 | Trick part: when it encounters negative number or dealing with index at edge index = 31, it starts having issue. Interesting fix: use long for masks. 20 | */ 21 | 22 | class Solution { 23 | /** 24 | *@param n, m: Two integer 25 | *@param i, j: Two bit positions 26 | *return: An integer 27 | */ 28 | public int updateBits(int n, int m, int i, int j) { 29 | //Create mask: xxx00000xxx 30 | long rightMask = ~0 >> i; 31 | rightMask = ~(rightMask << i);// 00000xxx 32 | long leftMask = ~0 >> (j + 1); 33 | leftMask = leftMask << (j + 1);//xxxxx00000000 34 | long mask = leftMask | rightMask;//xxx00000xxx 35 | n = (int) (n & mask); 36 | n = (int) (n | (m << i)); 37 | return n; 38 | } 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /Others/亚麻/FindFirstDuplicate.java: -------------------------------------------------------------------------------- 1 | /* 2 | 给你一个字符串,找出其中第一个重复的单词。比如,He had had a book. 返回had。 3 | 若真是这么简单, loop through str by ' '。每个单词都尝试在str里面找重复 4 | 5 | regular expression: "\\s+" 6 | */ 7 | 8 | public class Solution { 9 | 10 | public static String findFirstDuplicatedWord(String str) { 11 | if (str == null || str.length() == 0) { 12 | return str; 13 | } 14 | 15 | String[] arr = str.split("\\s+"); 16 | ArrayList list = new ArrayList(); 17 | for (int i = 0; i < arr.length; i++) { 18 | if (list.contains(arr[i])) { 19 | return arr[i]; 20 | } 21 | list.add(arr[i]); 22 | } 23 | 24 | return ""; 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println("START"); 29 | 30 | String str = "a is a sample program ok a";// is a a is 31 | 32 | String rst = findFirstDuplicatedWord(str); 33 | 34 | System.out.println(rst); 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /fails.md: -------------------------------------------------------------------------------- 1 | #### UnionFind.union, without checking rootA != rootB 2 | - P: Number of Connected Components in an Undirected Graph 3 | - when rootA == rootB, union exist already, no need to union again. 4 | 5 | #### Don't forget to map.put(i, new ArrayList<>()) 6 | - P: Number of Connected Components in an Undirected Graph 7 | - in DFS approach when initializing the adjacent list: use `map.put(x,y)`, not `add` 8 | 9 | 10 | #### forgot to cast int to char 11 | - P: wordladder 12 | - `sb.setCharAt(i, (char) j + 'a');` 13 | - Given input list: list.contains(), list.remove() are **O(logn)**!!! 14 | - Make sure to convert it to HashSet() if need to use contains()/remove() 15 | 16 | #### Check input range for SegmentTree problem 17 | - P: Segment Tree Query II 18 | - Forgot to validate [start, end] range. 19 | - Need to fail if completely out of range, or override one side of the range if partial of the range is applicable 20 | 21 | #### Jump too fast into 1 approach 22 | - P: Max Points on a line 23 | - Jump too fast into DP, when seeing a board, but ignored the fact: it's not nxn and not applicable. 24 | 25 | #### 正数/负数 26 | - P: Expression Add Operators 27 | - dfs都对, 但是负数的地方, 忘记加符号: be consistent and mindful about negative number 28 | - dfs(rst, list, s, i + 1, sum - currValue, **`- currValue`**, target); 29 | 30 | #### i++, i--, testing 31 | - code快, 写错++, -- 32 | - testing时候忽略了++,--, 那么其实就没有在真的test. 33 | 34 | #### Doubly Link BST 35 | - 问清楚, 最后的 head 跟 tail也要link在一起 36 | - 在DFS中, 当dfs的结果出来以后(right or left linked list), 其实就可以利用结果的性质, 而不用再重新干做. 37 | - `leftTail = leftHead.left`, `rightTail = rightHead.left` -------------------------------------------------------------------------------- /review/Adjacency Matrix.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Adjacency Matrix (1) 5 | **0. [277. Find the Celebrity.java](https://github.com/awangdev/LintCode/blob/master/Java/277.%20Find%20the%20Celebrity.java)** Level: Medium Tags: [Adjacency Matrix, Array, Graph, Greedy, Pruning] 6 | 7 | 8 | 有n个人, 其中有个人是celebrity, 注意必要条件 `Celeb knows nobody; Everyone else knows the celeb`. 找到celeb 9 | 10 | Note: the relationship graph can be presented as an adjacency matrix, but graph is not directly used in this problem. 11 | 12 | #### Pruning 13 | - Given assumption: 1) `only 1 celebrity`, 2) person k, who knows nobody ahead of him or after him. 14 | - if first pass finds candidate, `person k`, it means: 15 | - person [0, k-1] are not celebrity: they know a previous or current candidate 16 | - person k knows no one between [k + 1, n): k+1 to n-1 can not be the celebrity either. 17 | - person k is just the last standing possible celebrity 18 | - second pass validation: we do not know if `knows(celeb, [0~k-1] )`. Do a final O(n) check 19 | - time:O(n), space O(1) 20 | - DO NOT: Brutle compare all -> all: O(n^2) handshakes. 21 | 22 | ##### 思考逻辑 23 | - 先写出来[0 ~ n - 1], 最简单的方式 O(n^2) 检查, 记录每个人的状态. 24 | - 逐渐发现, 因为 celeb 谁都不会认识, 那么当任何candidate knows anyone, 他自身就不是celeb. 25 | - 我们可以greedy地, 一旦fail一个, 就立刻假设下一个是celeb candidate 26 | - 最终还是要检查一遍, 避免错漏. 27 | - 想一下happy case: 如果 celeb=0, 那么 know(celeb, i) 永远都是false, 然后 celeb一直保持0, 坚持到verify所有人. 28 | 29 | 30 | 31 | --- 32 | 33 | -------------------------------------------------------------------------------- /review/Analysis.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Analysis (1) 5 | **0. [41. First Missing Positive.java](https://github.com/awangdev/LintCode/blob/master/Java/41.%20First%20Missing%20Positive.java)** Level: Hard Tags: [Analysis, Array, Edge Case] 6 | 7 | 8 | 给一串无序数字, 有负数: 找这个array里面第一个 missing的 positive integer 9 | 10 | missing positive integer 其实是以 [1, n] 来做比较的. 11 | 12 | #### Array分析, index 技巧 13 | - 用while loop, 不断地尝试把 number 送到该放的地方 14 | - 如果 index = nums[i] 超过了nums.length, 当然就不移动了 15 | - 注意: 检查 val != nums[val], avoid infinitely loop 16 | - 检验: nums[i] 是否等于 i, 如果不对, 就找到了结果 17 | 18 | #### Edge Case 19 | 1. 如果nums==null, 其实missing positive integer 自然而然是 1 20 | 1. 有可能这串数字里没有断开的integer, 但是最大的integer在首位 (因为index超标, 无法被放到正确的地方) 21 | - 这种时候, n被放在 index 0, 其实就是说, 下一个integer应该是 n + 1 22 | 1. 最终, 如果array本来就是完全sorted, 也不缺, 还符合角标的条件, 那么唯一下一个就是array范围外的第一个positive number: n 23 | 24 | 25 | 26 | --- 27 | 28 | -------------------------------------------------------------------------------- /review/Backpack.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Backpack (1) 5 | **0. [416. Partition Equal Subset Sum.java](https://github.com/awangdev/LintCode/blob/master/Java/416.%20Partition%20Equal%20Subset%20Sum.java)** Level: Medium Tags: [Backpack, DP] 6 | 7 | #### Backpack DP 8 | - the problem turns into: can we find a subset of items that sum up to target sum? 9 | - create `boolean dp[j]` to represent if we can sum up to j, where j = sum value 10 | - want to try out all items in num, 11 | 12 | #### DFS 13 | - use dfs to find a subset of items that sum up to target sum? 14 | 15 | 16 | 17 | --- 18 | 19 | -------------------------------------------------------------------------------- /review/Binary Search on Value.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Binary Search on Value (1) 5 | **0. [287. Find the Duplicate Number.java](https://github.com/awangdev/LintCode/blob/master/Java/287.%20Find%20the%20Duplicate%20Number.java)** Level: Medium Tags: [Array, Binary Search, Binary Search on Value, Cycle Detection, Slow Fast Pointer, Two Pointers] 6 | 7 | 8 | #### Method1: Slow Fast Pointer 9 | - Use LinkedList Cycle Concept: 10 | - Each element the array is like a `Node {int currIndex; int val;}`, where the `val` is also pointer to next Node 11 | - A node is like a portal; a pointer can: 1) visit a node by currIndex, 2) pick up newIndex = `nums[currIndex]`, then keep repeating step 1 and 2. 12 | - Important: since nums is immutable, the pointer footprint is unique/linear 13 | - Just like linked list. Therefore, use slow/fast pointer to detect cycle. 14 | - https://leetcode.com/problems/find-the-duplicate-number/solution/ 15 | - it is now the same as `142. Linked List Cycle II` 16 | 17 | #### Method2: Binary Search on value 18 | - 注意不要思维定式: binary search `NOT on index` 19 | - `binary search on value`: [1, n] 20 | - O(logN) 21 | - validate(nums, candidate): for loop to count number of `value <= candidate` 22 | - `count == candidate`: no duplicate from [1 ~ candidate]. 23 | - `count < candidate`: missing element in [1~ candidate], so duplicates are in later range. start = mid; 24 | - `count > candidate`: there are duplicates in [1~ candidate]. end = mid; 25 | - Time: O(nLogN) 26 | - Space: O(1) 27 | 28 | 29 | 30 | --- 31 | 32 | -------------------------------------------------------------------------------- /review/Bitwise DP.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Bitwise DP (1) 5 | **0. [Counting Bits.java](https://github.com/awangdev/LintCode/blob/master/Java/Counting%20Bits.java)** Level: Medium Tags: [Bit Manipulation, Bitwise DP, DP] 6 | 7 | 给一个数组, 算里面有多少bit 1. 8 | 9 | #### Bitwise DP 10 | - 对于每一个数字, 其实很简单就能算出来: 每次 >>1, 然后 & 1 就可以count 1s. Time: 一个数字可以 >>1 O(logN) 次 11 | - 现在要对[0 ~ num] 都计算, 也就是N个数字, 时间复杂度: O(nLogN). 12 | - 用DP来优化, 查找过的number的1s count, 存下来在 dp[number]里面. 13 | - 计算你顺序从 0 -> num, count过的数字就可以重复利用. 14 | - Bit题目 用num的数值本身表示DP的状态. 15 | - 这里, dp[i] 并不是和 dp[i-1]有逻辑关系; 而是dp[i] 和dp[i>>1], 从binary representation看出有直接关系. 16 | 17 | 18 | 19 | --- 20 | 21 | -------------------------------------------------------------------------------- /review/Brainteaser.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Brainteaser (2) 5 | **0. [Nim Game.java](https://github.com/awangdev/LintCode/blob/master/Java/Nim%20Game.java)** Level: Easy Tags: [Brainteaser, DP, Game Theory] 6 | 7 | #### Brainteaser 8 | - 著名Nim游戏 9 | - 写一些,发现n=4,5,6,7,8...etc之后的情况有规律性: 谁先手拿到4就输了. 10 | - 最终很简单n%4!=0就可以了, time, space O(1) 11 | 12 | #### DP 13 | - 正规地找规律做, 就跟 coins in a line 一样, 按照先手后手来做 14 | - 可以rolling array 优化空间 15 | - Time O(n), 当然啦, 这个题目这样会timeout, 可以使用brainteaser的做法写出结果. 16 | 17 | 18 | 19 | --- 20 | 21 | **1. [319. Bulb Switcher.java](https://github.com/awangdev/LintCode/blob/master/Java/319.%20Bulb%20Switcher.java)** Level: Medium Tags: [Brainteaser, Math] 22 | 23 | 24 | #### Brainteaser 25 | - https://leetcode.com/problems/bulb-switcher/discuss/77104/Math-solution.. 26 | 27 | #### Brutle: 28 | - if just impl, it take O(n^2): 29 | - repating: some pos are toggled mutiple times: if we know total times, easy to determin each pos. 30 | - loop over [2, n], count times on each index 31 | 32 | 33 | 34 | --- 35 | 36 | -------------------------------------------------------------------------------- /review/Edge Case.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Edge Case (2) 5 | **0. [686. Repeated String Match.java](https://github.com/awangdev/LintCode/blob/master/Java/686.%20Repeated%20String%20Match.java)** Level: Easy Tags: [Basic Implementation, Edge Case, String] 6 | 7 | Track: 纸上分析edge case. 8 | Validation helps speed it up. 9 | 10 | 11 | 12 | --- 13 | 14 | **1. [41. First Missing Positive.java](https://github.com/awangdev/LintCode/blob/master/Java/41.%20First%20Missing%20Positive.java)** Level: Hard Tags: [Analysis, Array, Edge Case] 15 | 16 | 17 | 给一串无序数字, 有负数: 找这个array里面第一个 missing的 positive integer 18 | 19 | missing positive integer 其实是以 [1, n] 来做比较的. 20 | 21 | #### Array分析, index 技巧 22 | - 用while loop, 不断地尝试把 number 送到该放的地方 23 | - 如果 index = nums[i] 超过了nums.length, 当然就不移动了 24 | - 注意: 检查 val != nums[val], avoid infinitely loop 25 | - 检验: nums[i] 是否等于 i, 如果不对, 就找到了结果 26 | 27 | #### Edge Case 28 | 1. 如果nums==null, 其实missing positive integer 自然而然是 1 29 | 1. 有可能这串数字里没有断开的integer, 但是最大的integer在首位 (因为index超标, 无法被放到正确的地方) 30 | - 这种时候, n被放在 index 0, 其实就是说, 下一个integer应该是 n + 1 31 | 1. 最终, 如果array本来就是完全sorted, 也不缺, 还符合角标的条件, 那么唯一下一个就是array范围外的第一个positive number: n 32 | 33 | 34 | 35 | --- 36 | 37 | -------------------------------------------------------------------------------- /review/Garph.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Garph (1) 5 | **0. [785. Is Graph Bipartite.java](https://github.com/awangdev/LintCode/blob/master/Java/785.%20Is%20Graph%20Bipartite.java)** Level: Medium Tags: [BFS, DFS, Garph] 6 | 7 | 8 | #### DFS marking each node with a state 9 | - `bipartite` require each node to be in exact 1 party, which means it only has 1 state 10 | - DFS to mark node with one state; and mark its edges as reversed state 11 | - If any node state has been assigned by different from desired one, return false. 12 | 13 | #### BFS, Queue 14 | - Use `Boolean states[i]` to represent visted & state 15 | - Try all nodes with for loop, and skip visited nodes (similar validation rules as in dfs) 16 | - In `int next : graph[curr]`, test next level first before adding. 17 | 18 | 19 | 20 | --- 21 | 22 | -------------------------------------------------------------------------------- /review/Geometry.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Geometry (2) 5 | **0. [Perfect Rectangle.java](https://github.com/awangdev/LintCode/blob/master/Java/Perfect%20Rectangle.java)** Level: Hard Tags: [Design, Geometry, Hash Table] 6 | 7 | 看的list of coordinates 是否能组成perfect rectangle, 并且不允许overlap area. 8 | 9 | #### 画图发现特点 10 | - 特点1: 所有给出的点(再找出没有specify的对角线点), 如果最后组成perfect rectangle, 都应该互相消除, 最后剩下4个corner 11 | - 特点2: 找到所有点里面的min/max (x,y), 最后组成的 maxArea, 应该跟过程中accumulate的area相等 12 | - 特点1确保中间没有空心的部分, 保证所有的重合点都会互相消除, 最后剩下4个顶点 13 | - 特点2确保没有重合: 重合的area会最终超出maxArea 14 | 15 | 16 | 17 | --- 18 | 19 | **1. [149. Max Points on a Line.java](https://github.com/awangdev/LintCode/blob/master/Java/149.%20Max%20Points%20on%20a%20Line.java)** Level: Hard Tags: [Array, Geometry, Hash Table, Math] 20 | 21 | 22 | 给list of (x,y) coordinates. Determine # of points on the same line 23 | 24 | #### Observation 25 | - If given n points, we can calculate all possible slopes. O(n^2) times 26 | - For the two dots that generates the same slope, these dots could be on **parallel** slopes 27 | - figure out how to prune the parallel dots 28 | 29 | #### Trick: prune parallel dots using greatest common divider 30 | - GCD: greatest common divider 31 | - Devide the x and y by their greatest common divider, such that x and y can be reduced to minimum value 32 | - All other x and y can be reduced to such condition as well 33 | - track the final reduced (x,y) in a map: they are the key to the count 34 | - No need to use Map> to perform 2 level mapping; just `map`, where the key is "x@y" 35 | 36 | 37 | 38 | --- 39 | 40 | -------------------------------------------------------------------------------- /review/Interval.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Interval (1) 5 | **0. [Number of Airplane in the sky.java](https://github.com/awangdev/LintCode/blob/master/Java/Number%20of%20Airplane%20in%20the%20sky.java)** Level: Medium Tags: [Array, Interval, PriorityQueue, Sort, Sweep Line] 6 | 7 | #### Sweep Line 8 | - 把Interval拆分成数轴上的Point 9 | - 起飞mark 1 10 | - 降落mark -1 11 | - 用PriorityQueue排序, loop through queue, 计算(起飞+降落)值可能有的max。 12 | 13 | #### 注意 14 | - 同时起飞和降落,就是 1 - 1 = 0. 所以在while loop里面有第二个while loop, 15 | - 当坐标x重合时,在这里做完所有x点的加减,然后再比较 max。 16 | - 这避免了错误多count,或者少count 17 | 18 | 19 | 20 | --- 21 | 22 | -------------------------------------------------------------------------------- /review/KMP.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## KMP (1) 5 | **0. [Shortest Palindrome.java](https://github.com/awangdev/LintCode/blob/master/Java/Shortest%20Palindrome.java)** Level: Hard Tags: [KMP, String] 6 | 7 | #### Divide by mid point, Brutle 8 | - check (mid, mid+1), or (mid-1, mid+1). 9 | - If the two position matches, that is a palindrome candidate 10 | - 比较front string 是否是 end string 的substring 11 | - O(n^2) 12 | - timeout on last case: ["aaaaaa....aaaacdaaa...aaaaaa"] 13 | 14 | #### KMP 15 | - TODO 16 | 17 | 18 | 19 | --- 20 | 21 | -------------------------------------------------------------------------------- /review/List.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## List (1) 5 | **0. [118. Pascal's Triangle.java](https://github.com/awangdev/LintCode/blob/master/Java/118.%20Pascal's%20Triangle.java)** Level: Easy Tags: [Array, Basic Implementation, List] 6 | 7 | 8 | 9 | 10 | --- 11 | 12 | -------------------------------------------------------------------------------- /review/Lock.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Lock (1) 5 | **0. [1117. Building H2O.java](https://github.com/awangdev/LintCode/blob/master/Java/1117.%20Building%20H2O.java)** Level: Medium Tags: [Lock, Semaphore, Thread] 6 | 7 | 8 | #### Meethod1: Use lock & counter to lock a thread based on counter 9 | - when counter != 2 , it will execute hydrogen() two times so that 'H' will reach 2 10 | - when count == 2, it will execute oxygen() once so that 'O' will reach 2 11 | 12 | #### Method2: use Semaphore to manage the life cycle of 'H' and 'O' 13 | - to start: H is at count 2 and O is at count 0. They need both be at 0 to be unlocked 14 | - hydrogen(): 15 | - `h.acquire()` will execute 2 times until H.count is reduced to 0 16 | - `o.release` will add O.count by 1 for 2 times 17 | - oxygen(): 18 | - `o.acquire(2)` can only occur when O.count == 2 due to the 2 calls in `hydrogen(..)` 19 | - `h.release(2)` will restore the H.count back to 2 20 | - semaphore: https://www.geeksforgeeks.org/semaphore-in-java/ 21 | 22 | 23 | 24 | --- 25 | 26 | -------------------------------------------------------------------------------- /review/PQ.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## PQ (1) 5 | **0. [743. Network Delay Time.java](https://github.com/awangdev/LintCode/blob/master/Java/743.%20Network%20Delay%20Time.java)** Level: Medium Tags: [BFS, DFS, Graph, Heap, PQ] 6 | 7 | 8 | quesiton: sorting by travel delay/time will find better answer earlier? 9 | 10 | #### Method1: BFS with PQ on graph 11 | - `Dijkstras algorithm` is based on repeatedly making the candidate move that has the least distance travelled. 12 | - PQ: pick close node to vist, and add siblings back to PQ 13 | - avoid visited 14 | - time: O(nLogn), visit n nodes, each time insert to heap takes O(logn) time 15 | - space: O(n) 16 | 17 | #### Method2: DFS with Sort 18 | - 1) build graph map, 2) traverse map, 3) prioritize short delay nodes first 19 | - use a map`` globally track dealy to nodes; compare all at the end 20 | 21 | 22 | 23 | --- 24 | 25 | -------------------------------------------------------------------------------- /review/Pruning.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Pruning (1) 5 | **0. [277. Find the Celebrity.java](https://github.com/awangdev/LintCode/blob/master/Java/277.%20Find%20the%20Celebrity.java)** Level: Medium Tags: [Adjacency Matrix, Array, Graph, Greedy, Pruning] 6 | 7 | 8 | 有n个人, 其中有个人是celebrity, 注意必要条件 `Celeb knows nobody; Everyone else knows the celeb`. 找到celeb 9 | 10 | Note: the relationship graph can be presented as an adjacency matrix, but graph is not directly used in this problem. 11 | 12 | #### Pruning 13 | - Given assumption: 1) `only 1 celebrity`, 2) person k, who knows nobody ahead of him or after him. 14 | - if first pass finds candidate, `person k`, it means: 15 | - person [0, k-1] are not celebrity: they know a previous or current candidate 16 | - person k knows no one between [k + 1, n): k+1 to n-1 can not be the celebrity either. 17 | - person k is just the last standing possible celebrity 18 | - second pass validation: we do not know if `knows(celeb, [0~k-1] )`. Do a final O(n) check 19 | - time:O(n), space O(1) 20 | - DO NOT: Brutle compare all -> all: O(n^2) handshakes. 21 | 22 | ##### 思考逻辑 23 | - 先写出来[0 ~ n - 1], 最简单的方式 O(n^2) 检查, 记录每个人的状态. 24 | - 逐渐发现, 因为 celeb 谁都不会认识, 那么当任何candidate knows anyone, 他自身就不是celeb. 25 | - 我们可以greedy地, 一旦fail一个, 就立刻假设下一个是celeb candidate 26 | - 最终还是要检查一遍, 避免错漏. 27 | - 想一下happy case: 如果 celeb=0, 那么 know(celeb, i) 永远都是false, 然后 celeb一直保持0, 坚持到verify所有人. 28 | 29 | 30 | 31 | --- 32 | 33 | -------------------------------------------------------------------------------- /review/Reservior Sampling.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Reservior Sampling (1) 5 | **0. [398. Random Pick Index.java](https://github.com/awangdev/LintCode/blob/master/Java/398.%20Random%20Pick%20Index.java)** Level: Medium Tags: [Reservior Sampling] 6 | 7 | 8 | #### Reservior sampling 9 | - Random choose: think about reservoir sampling. https://www.youtube.com/watch?v=A1iwzSew5QY 10 | - Use random generator rd.nextInt(x) pick integer between [0, x) 11 | - try all numbers, when target is met, we want to model reservoir sampling: 12 | - item was chosen out of i samples, and all other samples are failed. 13 | - where we can use 'count' to represent the denominator/base to choose. 14 | - `**HAVE TO finish all samples** to make sure equal opportunity` 15 | - we can pick that last matched item as result 16 | - `rd.nextInt(count++) == 0` make sure we are always picking num == 0 to meet definition of reservoir sampling. 17 | - probability theory: 18 | - If multiply these probablities together to get the probability of one item being chosen with reservior sampling: 19 | - probability = 1/i * (1 - 1/i+1) * (1 - 1/i+2) ....(1 - 1/n) = 1/n 20 | 21 | 22 | 23 | 24 | --- 25 | 26 | -------------------------------------------------------------------------------- /review/Rotation.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Rotation (1) 5 | **0. [189. Rotate Array.java](https://github.com/awangdev/LintCode/blob/master/Java/189.%20Rotate%20Array.java)** Level: Easy Tags: [Array, Rotation] 6 | 7 | #### Rotate array in place 8 | - rotate all 9 | - rotate 2 sides: < k or >= 10 | 11 | 12 | #### Rotate by buffer the k array 13 | 14 | 15 | 16 | --- 17 | 18 | -------------------------------------------------------------------------------- /review/Semaphore.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Semaphore (1) 5 | **0. [1117. Building H2O.java](https://github.com/awangdev/LintCode/blob/master/Java/1117.%20Building%20H2O.java)** Level: Medium Tags: [Lock, Semaphore, Thread] 6 | 7 | 8 | #### Meethod1: Use lock & counter to lock a thread based on counter 9 | - when counter != 2 , it will execute hydrogen() two times so that 'H' will reach 2 10 | - when count == 2, it will execute oxygen() once so that 'O' will reach 2 11 | 12 | #### Method2: use Semaphore to manage the life cycle of 'H' and 'O' 13 | - to start: H is at count 2 and O is at count 0. They need both be at 0 to be unlocked 14 | - hydrogen(): 15 | - `h.acquire()` will execute 2 times until H.count is reduced to 0 16 | - `o.release` will add O.count by 1 for 2 times 17 | - oxygen(): 18 | - `o.acquire(2)` can only occur when O.count == 2 due to the 2 calls in `hydrogen(..)` 19 | - `h.release(2)` will restore the H.count back to 2 20 | - semaphore: https://www.geeksforgeeks.org/semaphore-in-java/ 21 | 22 | 23 | 24 | --- 25 | 26 | -------------------------------------------------------------------------------- /review/Thread.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Thread (1) 5 | **0. [1117. Building H2O.java](https://github.com/awangdev/LintCode/blob/master/Java/1117.%20Building%20H2O.java)** Level: Medium Tags: [Lock, Semaphore, Thread] 6 | 7 | 8 | #### Meethod1: Use lock & counter to lock a thread based on counter 9 | - when counter != 2 , it will execute hydrogen() two times so that 'H' will reach 2 10 | - when count == 2, it will execute oxygen() once so that 'O' will reach 2 11 | 12 | #### Method2: use Semaphore to manage the life cycle of 'H' and 'O' 13 | - to start: H is at count 2 and O is at count 0. They need both be at 0 to be unlocked 14 | - hydrogen(): 15 | - `h.acquire()` will execute 2 times until H.count is reduced to 0 16 | - `o.release` will add O.count by 1 for 2 times 17 | - oxygen(): 18 | - `o.acquire(2)` can only occur when O.count == 2 due to the 2 calls in `hydrogen(..)` 19 | - `h.release(2)` will restore the H.count back to 2 20 | - semaphore: https://www.geeksforgeeks.org/semaphore-in-java/ 21 | 22 | 23 | 24 | --- 25 | 26 | -------------------------------------------------------------------------------- /review/Two Stacks.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Two Stacks (1) 5 | **0. [145. Binary Tree Postorder Traversal.java](https://github.com/awangdev/LintCode/blob/master/Java/145.%20Binary%20Tree%20Postorder%20Traversal.java)** Level: Medium Tags: [Stack, Tree, Two Stacks] 6 | 7 | 8 | 如题, POST-ORDER traversal. 9 | 10 | LeetCode给了hard, 应该是觉得stack的做法比较难想到. 11 | 12 | #### Method1: DFS, Recursive 13 | - trivial, 先加left recursively, 再加right recursively, 然后组成头部. 14 | - Option1 w/o helper; option2 with dfs helper. 15 | 16 | #### Method2, Iterative, Stack 17 | - Option1: reversely add to list 18 | - 双stack的思想, 需要在图纸上画一画 19 | - 原本需要的顺序是: 先leftChild, rightChild, currNode. 20 | - 营造一个stack, reversely process: 先currNode, 再rightChild, 再leftChild 21 | - 这样出来的结果是reverse的, 那么翻转一下就可以了. 22 | - reverse add: `list.add(0, x)`; 23 | - 利用stack的特点 24 | - 每次加element进stack的时候, 想要在 bottom/后process的, 先加 25 | - 想要下一轮立刻process的, 最后push进stack. 26 | - Option2: regular sequence add to stack: add curr, right, left 27 | - Use set to contain the processed children 28 | - only process curr if its children is processed 29 | 30 | 31 | 32 | 33 | --- 34 | 35 | -------------------------------------------------------------------------------- /review/level/NA.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## NA (1) 5 | -------------------------------------------------------------------------------- /review/level/Review.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ## Review (2) 5 | **0. [Maximum Average Subarray II.java](https://github.com/awangdev/LintCode/blob/master/Java/Maximum%20Average%20Subarray%20II.java)** Level: Review Tags: [Array, Binary Search, PreSum] 6 | 7 | 给int[] nums 和 window min size k. window size可以大于K. 找最大的连续数列average value. 8 | 9 | - Binary Search的思想, 用在所要找的这个 average sum 上面. 大小是在[min, max]之中 10 | - 找k的时候, 是>=k都可以, 巧用一个 min(preSum)的概念. 11 | - 找k的时候, 画图, 可以看出来, 其实要的是 k window 里面的sum [x, i], 所以要用 sum[0, i] - sum[0, x] 12 | 13 | 需要仔细去读下面的notes. 14 | 15 | 16 | 17 | --- 18 | 19 | **1. [Maximum Subarray III.java](https://github.com/awangdev/LintCode/blob/master/Java/Maximum%20Subarray%20III.java)** Level: Review Tags: [] 20 | 21 | 22 | 23 | --- 24 | 25 | --------------------------------------------------------------------------------