├── Algorithm(4th_Edition) ├── .classpath ├── .idea │ ├── misc.xml │ ├── modules.xml │ ├── vcs.xml │ └── workspace.xml ├── .project ├── .settings │ └── org.eclipse.jdt.core.prefs ├── Algorithm(4th_Edition).iml ├── JavaConclusion.txt ├── Notes │ ├── Queue │ │ └── QueueConclusion.md │ ├── Tree │ │ ├── BinaryTree.java │ │ ├── CompleteBinaryTree.java │ │ ├── 二叉树BinaryTree.md │ │ ├── 完全二叉树CompleteBinaryTree.md │ │ └── 平衡二叉树BalancedBinaryTree.md │ └── algorithm_note.txt ├── algorithm_note.txt ├── bin │ └── ca │ │ └── mcmaster │ │ └── chapter │ │ └── one │ │ └── MyMath.class ├── lib │ └── algs4.jar └── src │ └── ca │ └── mcmaster │ ├── chapter │ ├── four │ │ └── graph │ │ │ ├── Graph.java │ │ │ ├── Path.java │ │ │ ├── directed │ │ │ ├── BreadFirstPathDirectedGraph.java │ │ │ ├── DepthFirstOrder.java │ │ │ ├── DepthFirstPathDirectedGraph.java │ │ │ ├── Digraph.java │ │ │ ├── DigraphImpl.java │ │ │ ├── DirectedCycle.java │ │ │ ├── DirectedDFS.java │ │ │ ├── SCC.java │ │ │ ├── StrongCircleComponent.java │ │ │ └── Topological.java │ │ │ ├── movies.txt │ │ │ ├── mstree │ │ │ ├── Edge.java │ │ │ ├── EdgeWeightedGraph.java │ │ │ ├── KruskalMST.java │ │ │ ├── LazyPrimMST.java │ │ │ ├── MST.java │ │ │ ├── PrimMst.java │ │ │ ├── mediumEWG.txt │ │ │ └── tinyEWG.txt │ │ │ ├── spt │ │ │ ├── DijkstraSP.java │ │ │ ├── DirectedEdge.java │ │ │ ├── EdgeWeightedDigraph.java │ │ │ ├── SP.java │ │ │ └── tinyEWD.txt │ │ │ ├── tinyCG.txt │ │ │ ├── tinyDAG.txt │ │ │ ├── tinyDG.txt │ │ │ ├── tinyG.txt │ │ │ └── undirected │ │ │ ├── AbstractCC.java │ │ │ ├── AbstractPath.java │ │ │ ├── AbstractSearch.java │ │ │ ├── BreadthFirstPath.java │ │ │ ├── ConnectionComponent.java │ │ │ ├── DFSCC.java │ │ │ ├── DeepFirstSearch.java │ │ │ ├── DepthFirstPath.java │ │ │ ├── Search.java │ │ │ ├── SymbolGraph.java │ │ │ ├── SymbolGraphImpl.java │ │ │ ├── UFSearch.java │ │ │ └── UndirectedGraph.java │ ├── one │ │ ├── BinarySearch.java │ │ ├── Evaluate.java │ │ ├── FIFO │ │ │ ├── FifoQueue.java │ │ │ └── ListFIFOQueue.java │ │ ├── MyMath.java │ │ ├── MyString.java │ │ ├── bag │ │ │ ├── Bag.java │ │ │ └── ListBag.java │ │ ├── stack │ │ │ ├── ListStack.java │ │ │ ├── MyStack.java │ │ │ └── ResizingArrayStack.java │ │ ├── sum │ │ │ └── SumProblems.java │ │ └── unionfind │ │ │ ├── QuickFind.java │ │ │ ├── QuickUnion.java │ │ │ ├── UnionFind.java │ │ │ ├── UnionfindAbstract.java │ │ │ ├── WeightedUnionFind.java │ │ │ └── tinyUF.txt │ ├── three │ │ ├── BinarySearchST.java │ │ ├── SearchSTAbstract.java │ │ ├── SequentialSearchST.java │ │ ├── bitree │ │ │ ├── BalancedBinaryTree.java │ │ │ ├── BinaryTreeSymbolTable.java │ │ │ └── BinaryTreeSymbolTableAbstract.java │ │ └── rbtree │ │ │ └── RedBlackBST.java │ └── two │ │ ├── Sort │ │ ├── BubbleSort.java │ │ ├── InsertionSort.java │ │ ├── SelectionSort.java │ │ ├── Sort.java │ │ └── SortOld.java │ │ └── queue │ │ ├── HeapSort.java │ │ ├── MaxPriorityQueue.java │ │ └── MaxPriorityQueueBinaryStack.java │ └── queue │ └── arrayblockingqueue │ ├── ArrayBlockingQueueConsumer.java │ ├── ArrayBlockingQueueProducer.java │ ├── ConcurrentLinkQueueProducer.java │ ├── ConcurrentLinkedQueueConsumer.java │ ├── DelayMsg.java │ ├── DelayQueueConsumer.java │ ├── DelayQueueProducer.java │ ├── LinkedBlockingQueueConsumer.java │ ├── LinkedBlockingQueueProducer.java │ ├── PriorityBlockingQueueConsumer.java │ └── PriorityBlockingQueueProducer.java ├── DataStructrue ├── Graph │ ├── AbstractCC.java │ ├── AbstractPath.java │ ├── AbstractSearch.java │ ├── BreadFirstPathDirectedGraph.java │ ├── BreadthFirstPath.java │ ├── ConnectionComponent.java │ ├── DFSCC.java │ ├── DeepFirstSearch.java │ ├── DepthFirstOrder.java │ ├── DepthFirstPath.java │ ├── DepthFirstPathDirectedGraph.java │ ├── Digraph.java │ ├── DigraphImpl.java │ ├── DijkstraSP.java │ ├── DirectedCycle.java │ ├── DirectedDFS.java │ ├── DirectedEdge.java │ ├── DirectedGraph.md │ ├── Edge.java │ ├── EdgeWeightedDigraph.java │ ├── EdgeWeightedGraph.java │ ├── Graph.java │ ├── LazyPrimMST.java │ ├── MST.java │ ├── MinimumSpanningTrees.md │ ├── Path.java │ ├── PrimMst.java │ ├── SCC.java │ ├── SP.java │ ├── Search.java │ ├── ShortestPath.md │ ├── StrongCircleComponent.java │ ├── SymbolGraph.java │ ├── SymbolGraphImpl.java │ ├── Topological.java │ ├── UFSearch.java │ ├── UndirectedGraph.java │ ├── UndirectedGraph.md │ ├── UnionFind.md │ └── tinyG.txt ├── Map │ ├── ConcurrentHashMap.md │ └── HashMap.md ├── Queue │ ├── ArrayBlockingQueue.md │ ├── ArrayBlockingQueueConsumer.java │ ├── ArrayBlockingQueueProducer.java │ ├── ConcurrentLinkQueueProducer.java │ ├── ConcurrentLinkedQueue.md │ ├── ConcurrentLinkedQueueConsumer.java │ ├── DelayMsg.java │ ├── DelayQueue.md │ ├── DelayQueueConsumer.java │ ├── DelayQueueProducer.java │ ├── LinkedBlockingQueue.md │ ├── LinkedBlockingQueueConsumer.java │ ├── LinkedBlockingQueueProducer.java │ ├── PriorityBlockingQueue.md │ ├── PriorityBlockingQueueConsumer.java │ ├── PriorityBlockingQueueProducer.java │ └── QueueConclusion.md ├── Search │ └── BinarySearch.md ├── Set │ └── TreeSet.md ├── Sort │ ├── BucketSort.md │ ├── CountSort.md │ ├── InsertionSort.md │ ├── MergeSort.md │ ├── QuickSort.md │ ├── SelectionSort.md │ └── Sort.md ├── String │ ├── TrieTree.md │ └── kmp.md ├── Tree │ ├── BinaryTree.java │ ├── BlackRedTree.java │ ├── B树系列.md │ ├── CompleteBinaryTree.java │ ├── 二叉树BinaryTree.md │ ├── 完全二叉树CompleteBinaryTree.md │ ├── 平衡二叉树BalancedBinaryTree.md │ └── 红黑树BlackRedTree.md └── algorithm_note.txt ├── Offer └── ca │ └── mcmaster │ └── offer │ ├── MyQueue.java │ ├── OfferGraph.java │ ├── OfferList.java │ ├── OfferStack.java │ ├── OfferTree.java │ ├── Question1_1.java │ ├── Question1_2.java │ ├── Question1_3.java │ ├── Question1_4.java │ ├── Question1_5.java │ ├── Question1_6.java │ ├── Question1_7.java │ ├── Question1_8.java │ ├── Question2_6.java │ ├── Question2_7.java │ ├── Question3_4.java │ ├── Question3_6.java │ ├── Question3_7.java │ ├── Question4_1.java │ ├── Question4_2.java │ ├── Question4_3.java │ ├── Question4_4.java │ ├── Question4_5.java │ ├── Question4_6.java │ ├── Question4_7.java │ ├── Question4_8.java │ ├── Question4_9.java │ ├── Question5_1.java │ ├── Question5_2.java │ ├── Question5_3.java │ ├── Question5_5.java │ ├── Question5_6.java │ ├── Question9_1.java │ ├── Question9_10.java │ ├── Question9_2.java │ ├── Question9_3.java │ ├── Question9_4.java │ ├── Question9_5.java │ ├── Question9_6.java │ ├── Question9_7.java │ ├── Question9_8.java │ ├── Question9_9.java │ ├── SetOfStack.java │ └── StackWithMin.java ├── README.md └── leetcode ├── 1.Two Sum.md ├── 10. Regular Expression Matching.md ├── 100. Same Tree.md ├── 1000. Minimum Cost to Merge Stones.md ├── 101. Symmetric Tree.md ├── 102. Binary Tree Level Order Traversal.md ├── 103. Binary Tree Zigzag Level Order Traversal.md ├── 104. Maximum Depth of Binary Tree.md ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.md ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.md ├── 107. Binary Tree Level Order Traversal II.md ├── 108. Convert Sorted Array to Binary Search Tree.md ├── 109. Convert Sorted List to Binary Search Tree.md ├── 11. Container With Most Water.md ├── 110. Balanced Binary Tree.md ├── 111. Minimum Depth of Binary Tree.md ├── 112. Path Sum.md ├── 113. Path Sum II.md ├── 114. Flatten Binary Tree to Linked List.md ├── 115. Distinct Subsequences.md ├── 116. Populating Next Right Pointers in Each Node.md ├── 117. Populating Next Right Pointers in Each Node II.md ├── 118. Pascal's Triangle.md ├── 119. Pascal's Triangle II.md ├── 12. Integer to Roman.md ├── 120. Triangle.md ├── 121. Best Time to Buy and Sell Stock.md ├── 122. Best Time to Buy and Sell Stock II.md ├── 123. Best Time to Buy and Sell Stock III.md ├── 124. Binary Tree Maximum Path Sum.md ├── 125. Valid Palindrome.md ├── 126. Word Ladder II.md ├── 127. Word Ladder.md ├── 128. Longest Consecutive Sequence.md ├── 129. Sum Root to Leaf Numbers.md ├── 13. Roman to Integer.md ├── 130. Surrounded Regions.md ├── 131. Palindrome Partitioning.md ├── 132. Palindrome Partitioning II.md ├── 133. Clone Graph.md ├── 134. Gas Station.md ├── 136. Single Number.md ├── 137. Single Number II.md ├── 138. Copy List with Random Pointer.md ├── 139. Word Break.md ├── 14.LongestCommonPrefix.md ├── 140. Word Break II.md ├── 141. Linked List Cycle.md ├── 142. Linked List Cycle II.md ├── 143. Reorder List.md ├── 144. Binary Tree Preorder Traversal.md ├── 145. Binary Tree Postorder Traversal.md ├── 146. LRU Cache.md ├── 147. Insertion Sort List.md ├── 148. Sort List.md ├── 149. Max Points on a Line.md ├── 15. 3Sum.md ├── 150. Evaluate Reverse Polish Notation.md ├── 151. Reverse Words in a String.md ├── 152. Maximum Product Subarray.md ├── 153. Find Minimum in Rotated Sorted Array.md ├── 154. Find Minimum in Rotated Sorted Array II.md ├── 155. Min Stack.md ├── 157. Read N Characters Given Read4.md ├── 158. Read N Characters Given Read4 II - Call multiple times.md ├── 16. 3Sum Closest.md ├── 160. Intersection of Two Linked Lists.md ├── 162. Find Peak Element.md ├── 164. Maximum Gap.md ├── 165. Compare Version Numbers.md ├── 166. Fraction to Recurring Decimal.md ├── 167. Two Sum II - Input array is sorted.md ├── 168. Excel Sheet Column Title.md ├── 169. Majority Element.md ├── 17. Letter Combinations of a Phone Number.md ├── 170. Two Sum III - Data structure design.md ├── 171. Excel Sheet Column Number.md ├── 172. Factorial Trailing Zeroes.md ├── 173. Binary Search Tree Iterator.md ├── 174. Dungeon Game.md ├── 175. Combine Two Tables.md ├── 176. Second Highest Salary.md ├── 177. Nth Highest Salary.md ├── 178. Rank Scores.md ├── 179. Largest Number.md ├── 18. 4Sum.md ├── 180. Consecutive Numbers.md ├── 181. Employees Earning More Than Their Managers.md ├── 182. Duplicate Emails.md ├── 183. Customers Who Never Order.md ├── 184. Department Highest Salary.md ├── 185. Department Top Three Salaries.md ├── 186. Reverse Words in a String II.md ├── 187. Repeated DNA Sequences.md ├── 188. Best Time to Buy and Sell Stock IV.md ├── 189. Rotate Array.md ├── 19. Remove Nth Node From End of List.md ├── 190. Reverse Bits.md ├── 191. Number of 1 Bits.md ├── 198. House Robber.md ├── 199. Binary Tree Right Side View ├── 2. Add Two Numbers.md ├── 20. Valid Parentheses.md ├── 200. Number of Islands.md ├── 201. Bitwise AND of Numbers Range.md ├── 202. Happy Number.md ├── 203. Remove Linked List Elements.md ├── 204. Count Primes.md ├── 205. Isomorphic Strings.md ├── 206. Reverse Linked List.md ├── 207. Course Schedule.md ├── 208. Implement Trie (Prefix Tree).md ├── 209. Minimum Size Subarray Sum.md ├── 21. Merge Two Sorted Lists.md ├── 210. Course Schedule II.md ├── 211. Add and Search Word - Data structure design.md ├── 212. Word Search II.md ├── 213. House Robber II.md ├── 214. Shortest Palindrome.md ├── 215. Kth Largest Element in an Array.md ├── 216. Combination Sum III.md ├── 217. Contains Duplicate.md ├── 218. The Skyline Problem.md ├── 219. Contains Duplicate II.md ├── 22. Generate Parentheses.md ├── 220. Contains Duplicate III.md ├── 221. Maximal Square.md ├── 222. Count Complete Tree Nodes.md ├── 223. Rectangle Area.md ├── 224. Basic Calculator.md ├── 225. Implement Stack using Queues.md ├── 226. Invert Binary Tree.md ├── 227. Basic Calculator II.md ├── 228. Summary Ranges.md ├── 229. Majority Element II.md ├── 23. Merge k Sorted Lists.md ├── 230. Kth Smallest Element in a BST.md ├── 231. Power of Two.md ├── 232. Implement Queue using Stacks.md ├── 234. Palindrome Linked List.md ├── 235. Lowest Common Ancestor of a Binary Search Tree.md ├── 236. Lowest Common Ancestor of a Binary Tree.md ├── 237. Delete Node in a Linked List.md ├── 238. Product of Array Except Self.md ├── 239. Sliding Window Maximum.md ├── 24. Swap Nodes in Pairs.md ├── 240. Search a 2D Matrix II.md ├── 241. Different Ways to Add Parentheses.md ├── 242. Valid Anagram.md ├── 25. Reverse Nodes in k-Group.md ├── 250. Count Univalue Subtrees.md ├── 252. Meeting Rooms.md ├── 253. Meeting Rooms II.md ├── 257. Binary Tree Paths.md ├── 258. Add Digits.md ├── 26. Remove Duplicates from Sorted Array.md ├── 261. Graph Valid Tree.md ├── 263. Ugly Number.md ├── 264. Ugly Number II.md ├── 268. Missing Number.md ├── 269. Alien Dictionary.md ├── 27. Remove Element.md ├── 270. Closest Binary Search Tree Value.md ├── 273. Integer to English Words.md ├── 274. H-Index.md ├── 275. H-Index II.md ├── 276. Paint Fence.md ├── 277. Find the Celebrity.md ├── 278. First Bad Version.md ├── 279. Perfect Squares.md ├── 28. Implement strStr().md ├── 280. Wiggle Sort.md ├── 282. Expression Add Operators.md ├── 283. Move Zeroes.md ├── 284. Peeking Iterator.md ├── 285. Inorder Successor in BST.md ├── 287. Find the Duplicate Number.md ├── 289. Game of Life.md ├── 29. Divide Two Integers.md ├── 290. Word Pattern.md ├── 292. Nim Game.md ├── 295.Find Median from Data Stream.md ├── 297. Serialize and Deserialize Binary Tree.md ├── 299. Bulls and Cows.md ├── 3. Longest Substring Without Repeating Characters.md ├── 30. Substring with Concatenation of All Words.md ├── 300. Longest Increasing Subsequence.md ├── 301. Remove Invalid Parentheses.md ├── 303. Range Sum Query - Immutable.md ├── 304. Range Sum Query 2D - Immutable.md ├── 305. Number Of Island II.md ├── 305. Number of Islands II.md ├── 306. Additive Number.md ├── 307. Range Sum Query - Mutable.md ├── 309. Best Time to Buy and Sell Stock with Cooldown.md ├── 31. Next Permutation.md ├── 310. Minimum Height Trees.md ├── 312. Burst Balloons.md ├── 313. Super Ugly Number.md ├── 314. Binary Tree Vertical Order Traversal.md ├── 315. Count of Smaller Numbers After Self.md ├── 316. Remove Duplicate Letters.md ├── 317. Shortest Distance from All Buildings.md ├── 318. Maximum Product of Word Lengths.md ├── 319. Bulb Switcher.md ├── 32. Longest Valid Parentheses.md ├── 322. Coin Change.md ├── 323. Number of Connected Components in an Undirected Graph.md ├── 324. Wiggle Sort II.md ├── 325. Maximum Size Subarray Sum Equals k.md ├── 328. Odd Even Linked List.md ├── 329. Longest Increasing Path in a Matrix.md ├── 33. Search in Rotated Sorted Array.md ├── 331. Verify Preorder Serialization of a Binary Tree.md ├── 332. Reconstruct Itinerary.md ├── 333. Largest BST Subtree.md ├── 334. Increasing Triplet Subsequence.md ├── 336. Palindrome Pairs.md ├── 337. House Robber III.md ├── 338. Counting Bits.md ├── 339. Nested List Weight Sum.md ├── 34. Find First and Last Position of Element in Sorted Array.md ├── 340. Longest Substring with At Most K Distinct Characters.md ├── 341. Flatten Nested List Iterator.md ├── 342. Power of Four.md ├── 343. Integer Break.md ├── 344. Reverse String.md ├── 345. Reverse Vowels of a String.md ├── 346. Moving Average from Data Stream.md ├── 347. Top K Frequent Elements.md ├── 348. Design Tic-Tac-Toe.md ├── 349. Intersection of Two Arrays.md ├── 35. Search Insert Position.md ├── 350. Intersection of Two Arrays II.md ├── 355. Design Twitter.md ├── 357. Count Numbers with Unique Digits.md ├── 36. Valid Sudoku.md ├── 360. Sort Transfromed Array.md ├── 362. Design Hit Counter.md ├── 364. Nested List Weight Sum II.md ├── 37. Sudoku Solver.md ├── 373. Find K Pairs with Smallest Sums.md ├── 377. Combination Sum IV.md ├── 378. Kth Smallest Element in a Sorted Matrix.md ├── 38. Count and Say.md ├── 380. Insert Delete GetRandom O(1).md ├── 382. Linked List Random Node.md ├── 387. First Unique Character in a String.md ├── 39. Combination Sum.md ├── 392. Is Subsequence.md ├── 393. UTF-8 Validation.md ├── 394. Decode String.md ├── 395. Longest Substring with At Least K Repeating Characters.md ├── 399. Evaluate Division.md ├── 4. Median of Two Sorted Arrays.md ├── 40. Combination Sum II.md ├── 41. First Missing Positive.md ├── 410. Split Array Largest Sum.md ├── 412. Fizz Buzz.md ├── 413. Arithmetic Slices.md ├── 416. Partition Equal Subset Sum.md ├── 42. Trapping Rain Water.md ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List.md ├── 427. Construct Quad Tree.md ├── 428. Serialize and Deserialize N-ary Tree.md ├── 429. N-ary Tree Level Order Traversal.md ├── 43. Multiply Strings.md ├── 435. Non-overlapping Intervals.md ├── 437. Path Sum III.md ├── 438. Find All Anagrams in a String.md ├── 44. Wildcard Matching.md ├── 443. String Compression.md ├── 445. Add Two Numbers II.md ├── 448. Find All Numbers Disappeared in an Array.md ├── 449. Serialize and Deserialize BST.md ├── 45. Jump Game II.md ├── 450. Delete Node in a BST.md ├── 452. Minimum Number of Arrows to Burst Balloons.md ├── 458. Poor Pigs.md ├── 46. Permutations.md ├── 460. LFU Cache.md ├── 468. Validate IP Address.md ├── 47. Permutations II.md ├── 472. Concatenated Words.md ├── 48. Rotate Image.md ├── 489. Robot Room Cleaner.md ├── 49. Group Anagrams.md ├── 490. The Maze.md ├── 494. Target Sum.md ├── 496. Next Greater Element I.md ├── 5. Longest Palindromic Substring.md ├── 50. Pow(x, n).md ├── 501. Find Mode in Binary Search Tree.md ├── 503. Next Greater Element II.md ├── 505. The Maze II.md ├── 508. Most Frequent Subtree Sum.md ├── 509. Fibonacci Number.md ├── 51. N-Queens.md ├── 516. Longest Palindromic Subsequence.md ├── 518. Coin Change 2.md ├── 52. N-Queens II.md ├── 528. Random Pick with Weight.md ├── 53. Maximum Subarray.md ├── 530. Minimum Absolute Difference in BST.md ├── 535. Encode and Decode TinyURL.md ├── 54. Spiral Matrix.md ├── 542. 01 Matrix.md ├── 543. Diameter of Binary Tree.md ├── 545. Boundary of Binary Tree.md ├── 546. Remove Boxes.md ├── 547. Friend Circles.md ├── 55. Jump Game.md ├── 556. Next Greater Element III.md ├── 56. Merge Intervals.md ├── 560. Subarray Sum Equals K.md ├── 564. Find the Closest Palindrome.md ├── 567. Permutation in String.md ├── 57. Insert Interval.md ├── 572. Subtree of Another Tree.md ├── 576. Out of Boundary Paths.md ├── 58. Length of Last Word.md ├── 583. Delete Operation for Two Strings.md ├── 588. Design In-Memory File System.md ├── 589. N-ary Tree Preorder Traversal.md ├── 59. Spiral Matrix II.md ├── 590. N-ary Tree Postorder Traversal.md ├── 6. ZigZag Conversion.md ├── 60. Permutation Sequence.md ├── 609. Find Duplicate File in System.md ├── 61. Rotate List.md ├── 617. Merge Two Binary Trees.md ├── 62. Unique Paths.md ├── 621. Task Scheduler.md ├── 63. Unique Paths II.md ├── 635. Design Log Storage System.md ├── 636. Exclusive Time of Functions.md ├── 637. Average of Levels in Binary Tree.md ├── 64. Minimum Path Sum.md ├── 642. Design Search Autocomplete System.md ├── 647. Palindromic Substrings.md ├── 648. Replace Words.md ├── 65. Valid Number.md ├── 653. Two Sum IV - Input is a BST.md ├── 654. Maximum Binary Tree.md ├── 66. Plus One.md ├── 662. Maximum Width of Binary Tree.md ├── 664. Strange Printer.md ├── 668. Kth Smallest Number in Multiplication Table.md ├── 669. Trim a Binary Search Tree.md ├── 67. Add Binary.md ├── 673. Number of Longest Increasing Subsequence.md ├── 675. Cut Off Trees for Golf Event.md ├── 676. Implement Magic Dictionary.md ├── 677. Map Sum Pairs.md ├── 679. 24 Game.md ├── 68. Text Justification.md ├── 683. K Empty Slots.md ├── 684. Redundant Connection.md ├── 685. Redundant Connection II.md ├── 686. Repeated String Match.md ├── 687. Longest Univalue Path.md ├── 688. Knight Probability in Chessboard.md ├── 69. Sqrt(x).md ├── 692. Top K Frequent Words.md ├── 694. Number of Distinct Islands.md ├── 695. Max Area of Island.md ├── 698. Partition to K Equal Sum Subsets.md ├── 7. Reverse Integer.md ├── 70. Climbing Stairs.md ├── 700. Search in a Binary Search Tree.md ├── 701. Insert into a Binary Search Tree.md ├── 704. Binary Search.md ├── 706. Design HashMap.md ├── 707. Design Linked List.md ├── 71. Simplify Path.md ├── 710. Random Pick with Blacklist.md ├── 712. Minimum ASCII Delete Sum for Two Strings.md ├── 714. Best Time to Buy and Sell Stock with Transaction Fee.md ├── 716. Max Stack.md ├── 717. 1-bit and 2-bit Characters.md ├── 719. Find K-th Smallest Pair Distance.md ├── 72. Edit Distance.md ├── 720. Longest Word in Dictionary.md ├── 721. Accounts Merge.md ├── 726. Number of Atoms.md ├── 729. My Calendar I.md ├── 73. Set Matrix Zeroes.md ├── 731. My Calendar II.md ├── 733. Flood Fill.md ├── 735. Asteroid Collision.md ├── 74. Search a 2D Matrix.md ├── 740. Delete and Earn.md ├── 741. Cherry Pickup.md ├── 743. Network Delay Time.md ├── 745. Prefix and Suffix Search.md ├── 746. Min Cost Climbing Stairs.md ├── 75. Sort Colors.md ├── 752. Open the Lock.md ├── 753. Cracking the Safe.md ├── 755. Pour Water.md ├── 759. Employee Free Time.md ├── 76. Minimum Window Substring.md ├── 763. Partition Labels.md ├── 767. Reorganize String.md ├── 77. Combinations.md ├── 771. Jewels and Stones.md ├── 772. Basic Calculator III.md ├── 773. Sliding Puzzle.md ├── 778. Swim in Rising Water.md ├── 78. Subsets.md ├── 784. Letter Case Permutation.md ├── 785. Is Graph Bipartite.md ├── 786. K-th Smallest Prime Fraction.md ├── 787. Cheapest Flights Within K Stops.md ├── 788. Rotated Digits.md ├── 79. Word Search.md ├── 790. Domino and Tromino Tiling.md ├── 792. Number of Matching Subsequences.md ├── 8. String to Integer (atoi).md ├── 80. Remove Duplicates from Sorted Array II.md ├── 801. Minimum Swaps To Make Sequences Increasing.md ├── 802. Find Eventual Safe States.md ├── 81. Search in Rotated Sorted Array II.md ├── 811. Subdomain Visit Count.md ├── 813. Largest Sum of Averages.md ├── 814. Binary Tree Pruning.md ├── 815. Bus Routes.md ├── 818. Race Car.md ├── 819. Most Common Word.md ├── 82. Remove Duplicates from Sorted List II.md ├── 827. Making A Large Island.md ├── 829. Consecutive Numbers Sum.md ├── 83. Remove Duplicates from Sorted List.md ├── 833. Find And Replace in String.md ├── 836. Rectangle Overlap.md ├── 839. Similar String Groups.md ├── 84. Largest Rectangle in Histogram.md ├── 841. Keys and Rooms.md ├── 842. Split Array into Fibonacci Sequence.md ├── 843. Guess the Word.md ├── 844. Backspace String Compare.md ├── 847. Shortest Path Visiting All Nodes.md ├── 85. Maximal Rectangle.md ├── 850. Rectangle Area II.md ├── 852. Peak Index in a Mountain Array.md ├── 856. Score of Parentheses.md ├── 86. Partition List.md ├── 863. All Nodes Distance K in Binary Tree.md ├── 864. Shortest Path to Get All Keys.md ├── 872. Leaf-Similar Trees.md ├── 875. Koko Eating Bananas.md ├── 88. Merge Sorted Array.md ├── 886. Possible Bipartition.md ├── 89. Gray Code.md ├── 895. Maximum Frequency Stack.md ├── 9. Palindrome Number.md ├── 90. Subsets II.md ├── 901. Online Stock Span.md ├── 904. Fruit Into Baskets.md ├── 907. Sum of Subarray Minimums.md ├── 909. Snakes and Ladders.md ├── 91. Decode Ways.md ├── 92. Reverse Linked List II.md ├── 923. 3Sum With Multiplicity.md ├── 924. Minimize Malware Spread.md ├── 929. Unique Email Addresses.md ├── 93. Restore IP Addresses.md ├── 931. Minimum Falling Path Sum.md ├── 933. Number of Recent Calls.md ├── 934. Shortest Bridge.md ├── 935. Knight Dialer.md ├── 937. Reorder Log Files.md ├── 939. Minimum Area Rectangle.md ├── 94. Binary Tree Inorder Traversal.md ├── 943. Find the Shortest Superstring.md ├── 947. Most Stones Removed with Same Row or Column.md ├── 95. Unique Binary Search Trees II.md ├── 952. Largest Component Size by Common Factor.md ├── 957. Prison Cells After N Days.md ├── 959. Regions Cut By Slashes.md ├── 96. Unique Binary Search Trees.md ├── 965. Univalued Binary Tree.md ├── 968. Binary Tree Cameras.md ├── 97. Interleaving String.md ├── 973. K Closest Points to Origin.md ├── 975. Odd Even Jump.md ├── 977. Squares of a Sorted Array.md ├── 979. Distribute Coins in Binary Tree.md ├── 98. Validate Binary Search Tree.md ├── 980. Unique Paths III.md ├── 981. Time Based Key-Value Store.md ├── 983. Minimum Cost For Tickets.md ├── 986. Interval List Intersections.md ├── 987. Vertical Order Traversal of a Binary Tree.md ├── 99. Recover Binary Search Tree.md ├── 990. Satisfiability of Equality Equations.md ├── 992. subarrays with k different integers.md ├── 993. Cousins in Binary Tree.md ├── 994. Rotting Oranges.md ├── 996. Number of Squareful Arrays.md ├── 997. Find the Town Judge.md └── Offer ├── Question1_1.md ├── Question1_2.md ├── Question1_3.md ├── Question1_4.md ├── Question1_5.md ├── Question1_6.md ├── Question1_7.md ├── Question1_8.md ├── Question2_1.md ├── Question2_2.md ├── Question2_3.md ├── Question2_4.md ├── Question2_5.md ├── Question2_6.md ├── Question2_7.md ├── Question3_1.md ├── Question3_2.md ├── Question3_3.md ├── Question3_4.md ├── Question3_5.md ├── Question3_6.md ├── Question3_7.md ├── Question4_1.md ├── Question4_2.md ├── Question4_3.md ├── Question4_4.md ├── Question4_5.md ├── Question4_6.md ├── Question4_7.md ├── Question4_8.md ├── Question4_9.md ├── Question5_1.md ├── Question5_2.md ├── Question5_3.md ├── Question5_5.md ├── Question5_6.md ├── Question9_1.md ├── Question9_10.md ├── Question9_2.md ├── Question9_3.md ├── Question9_4.md ├── Question9_5.md ├── Question9_6.md ├── Question9_7.md ├── Question9_8.md ├── Question9_9.md └── 程序员面试金典 第5版.pdf /Algorithm(4th_Edition)/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Algorithm(4th_Edition) 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/Algorithm(4th_Edition).iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/bin/ca/mcmaster/chapter/one/MyMath.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Seanforfun/Algorithm-and-Leetcode/4ea49415a05d1c6ed54a384841fa46f86c2810e2/Algorithm(4th_Edition)/bin/ca/mcmaster/chapter/one/MyMath.class -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/lib/algs4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Seanforfun/Algorithm-and-Leetcode/4ea49415a05d1c6ed54a384841fa46f86c2810e2/Algorithm(4th_Edition)/lib/algs4.jar -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/Path.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public interface Path { 4 | /** 5 | * @Description: If there is a path from s to v 6 | * @param v 7 | * @return 8 | */ 9 | public boolean hasPathTo(int v); 10 | /** 11 | * @Description: Return the path from s to v if it exists and return null if not existing. 12 | * @param v 13 | * @return 14 | */ 15 | Iterable pathTo(int v); 16 | } 17 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/directed/DepthFirstOrder.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | import java.util.Queue; 4 | import java.util.Stack; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | 7 | public class DepthFirstOrder { 8 | private final boolean[] marked; 9 | private final Queue pre; 10 | private final Queue post; 11 | private final Stack reversePost; 12 | public DepthFirstOrder(Digraph g){ 13 | pre = new LinkedBlockingQueue(); 14 | post = new LinkedBlockingQueue<>(); 15 | reversePost = new Stack<>(); 16 | marked = new boolean[g.V()]; 17 | for(int v = 0; v < g.V(); v++) 18 | if(!marked[v]) dfs(g, v); 19 | } 20 | 21 | private void dfs(Digraph g, int v){ 22 | pre.offer(v); 23 | marked[v] = true; 24 | for(int w : g.adj(v)) 25 | if(!marked[w]) dfs(g, w); 26 | post.offer(v); 27 | reversePost.push(v); 28 | } 29 | public Iterable pre(){ 30 | return this.pre; 31 | } 32 | public Iterable post(){ 33 | return this.post(); 34 | } 35 | public Iterable reversePost(){ 36 | return this.reversePost; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/directed/Digraph.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | public interface Digraph { 4 | /** 5 | * @Description: Number of vertex. 6 | * @return 7 | */ 8 | public int V(); 9 | /** 10 | * @Description: Number of edge. 11 | * @return 12 | */ 13 | public int E(); 14 | /** 15 | * @Description: Add an edge between two vertex. v->w. 16 | * @param v 17 | * @param w 18 | */ 19 | public void addEdge(int v, int w); 20 | /** 21 | * @Description: Return vertex point out from v. 22 | * @param v 23 | * @return 24 | */ 25 | public Iterable adj(int v); 26 | /** 27 | * @Description: Get the reverse graph of current graph. 28 | * @return 29 | */ 30 | public Digraph reverse(); 31 | /** 32 | * @Description: Print current graph. 33 | */ 34 | public void display(); 35 | } 36 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/directed/DirectedDFS.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | 7 | import ca.mcmaster.chapter.one.bag.Bag; 8 | import ca.mcmaster.chapter.one.bag.ListBag; 9 | 10 | public class DirectedDFS { 11 | private final boolean[] marked; 12 | public DirectedDFS(Digraph g, int s){ 13 | this.marked = new boolean[g.V()]; 14 | dfs(g, s); 15 | } 16 | public DirectedDFS(Digraph g, Iterable sources){ 17 | marked = new boolean[g.V()]; 18 | for(int s : sources) 19 | if(!marked[s]) dfs(g, s); 20 | } 21 | private void dfs(Digraph g, int s) { 22 | marked[s] = true; 23 | for(int w : g.adj(s)) 24 | if(!marked[w]) dfs(g, w); 25 | } 26 | public boolean mark(int v){ 27 | return marked[v]; 28 | } 29 | public static void main(String[] args) throws FileNotFoundException { 30 | Digraph g = new DigraphImpl(new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/tinyDG.txt"))); 31 | Bag bag = new ListBag(); 32 | bag.add(1); 33 | bag.add(2); 34 | bag.add(6); 35 | DirectedDFS d = new DirectedDFS(g, bag); 36 | StringBuilder sb = new StringBuilder(); 37 | for(int v = 0; v < g.V(); v++){ 38 | if(d.mark(v)) sb.append(v + " "); 39 | } 40 | System.out.println(sb.toString()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/directed/SCC.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | public interface SCC { 4 | /** 5 | * @Description: Check if v and w are connected. 6 | * @param v 7 | * @param w 8 | * @return 9 | */ 10 | public boolean strongConnected(int v, int w); 11 | /** 12 | * @Description: The number of strong connected component. 13 | * @return 14 | */ 15 | public int count(); 16 | /** 17 | * @Description: Which of the strong component belongs to. 18 | * @param v 19 | * @return 20 | */ 21 | int id(int v); 22 | } 23 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/directed/StrongCircleComponent.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | public class StrongCircleComponent implements SCC { 4 | private boolean[] marked; 5 | private int[] id; 6 | private int count; 7 | public StrongCircleComponent(Digraph g) { 8 | marked = new boolean[g.V()]; 9 | id = new int[g.V()]; 10 | DepthFirstOrder order = new DepthFirstOrder(g.reverse()); 11 | for(int s : order.reversePost()){ //从栈中顺序读取顶点 12 | if(!marked[s]){ 13 | dfs(g, s); count++; 14 | } 15 | } 16 | } 17 | 18 | private void dfs(Digraph g, int v){ 19 | marked[v] = true; 20 | id[v] = count; 21 | for(int w : g.adj(v)) 22 | if(!marked[w]) 23 | dfs(g, w); 24 | } 25 | @Override 26 | public boolean strongConnected(int v, int w) { 27 | return id[v] == id[w]; 28 | } 29 | 30 | @Override 31 | public int count() { 32 | return count; 33 | } 34 | 35 | @Override 36 | public int id(int v) { 37 | return id[v]; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/directed/Topological.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | 7 | public class Topological { 8 | private Iterable order; 9 | public Topological(Digraph g){ 10 | DirectedCycle dc = new DirectedCycle(g); 11 | if(!dc.hasCycle()){ 12 | DepthFirstOrder dfo = new DepthFirstOrder(g); 13 | order = dfo.reversePost(); 14 | } 15 | } 16 | public Iterable order(){ 17 | return order; 18 | } 19 | public boolean isDAG(){ 20 | return order != null; 21 | } 22 | public static void main(String[] args) throws FileNotFoundException { 23 | Digraph g = new DigraphImpl(new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/tinyDG.txt"))); 24 | Topological topological = new Topological(g); 25 | StringBuilder sb = new StringBuilder(); 26 | for(int i : topological.order()){ 27 | sb.append(i + " "); 28 | } 29 | System.out.println(sb.toString()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/mstree/Edge.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.mstree; 2 | 3 | public class Edge implements Comparable { 4 | private final int v; 5 | private final int w; 6 | private final double weight; 7 | public Edge(int v, int w, double weight){ 8 | this.v = v; 9 | this.w = w; 10 | this.weight = weight; 11 | } 12 | @Override 13 | public int compareTo(Edge o) { 14 | if(this.weight - o.weight > 0) return 1; 15 | else if(this.weight == o.weight) return 0; 16 | else return -1; 17 | } 18 | public double weight(){ 19 | return this.weight; 20 | } 21 | public int either(){ 22 | return v; 23 | } 24 | public int other(int v){ 25 | if(v == this.v) return this.w; 26 | else 27 | return this.v; 28 | } 29 | @Override 30 | public String toString() { 31 | return String.format("%d-%d %.2f", v, w, weight); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/mstree/MST.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.mstree; 2 | 3 | public interface MST { 4 | /** 5 | * @Description: Find the edges on the minimum spanning tree. 6 | * @return 7 | */ 8 | public Iterable edges(); 9 | /** 10 | * @Description: Return the total weight of the tree. 11 | * @return 12 | */ 13 | public double weight(); 14 | } 15 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/mstree/PrimMst.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.mstree; 2 | 3 | import edu.princeton.cs.algs4.IndexMinPQ; 4 | 5 | public class PrimMst implements MST { 6 | private Edge[] edgeTo; 7 | private double[] distTo; 8 | private boolean[] marked; 9 | private IndexMinPQ pq; 10 | public PrimMst(EdgeWeightedGraph g) { 11 | edgeTo = new Edge[g.V()]; 12 | distTo = new double[g.V()]; 13 | marked = new boolean[g.V()]; 14 | for(int i = 0; i < g.V(); i++){ 15 | distTo[i] = Double.POSITIVE_INFINITY; 16 | } 17 | pq = new IndexMinPQ(g.V()); 18 | distTo[0] = 0.0d; 19 | while(!pq.isEmpty()) 20 | visit(g, pq.delMin()); 21 | } 22 | private void visit(EdgeWeightedGraph g, int v){ //当前的顶点不在最小树中 23 | marked[v] = true; 24 | for(Edge e : g.adj(v)){ //遍历连接这个顶点的所有边 25 | int w = e.other(v); //找到这些边中除了v的另一个顶点 26 | if(marked[w]) continue; //v-w已经在树中,失效 27 | if(e.weight() < distTo[w]){ //判断是不是可以替代 28 | edgeTo[w] = e; 29 | distTo[w] = e.weight(); 30 | if(pq.contains(w)) pq.change(w, distTo[w]); 31 | else pq.insert(w, distTo[w]); 32 | } 33 | } 34 | } 35 | @Override 36 | public Iterable edges() { 37 | return null; 38 | } 39 | @Override 40 | public double weight() { 41 | return 0; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/mstree/tinyEWG.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 16 3 | 4 5 0.35 4 | 4 7 0.37 5 | 5 7 0.28 6 | 0 7 0.16 7 | 1 5 0.32 8 | 0 4 0.38 9 | 2 3 0.17 10 | 1 7 0.19 11 | 0 2 0.26 12 | 1 2 0.36 13 | 1 3 0.29 14 | 2 7 0.34 15 | 6 2 0.40 16 | 3 6 0.52 17 | 6 0 0.58 18 | 6 4 0.93 19 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/spt/DirectedEdge.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.spt; 2 | 3 | public class DirectedEdge { 4 | private final int v; //边的起始点 5 | private final int w; //边的指向 6 | private final double weight; //有向边的权重 7 | public DirectedEdge(int v, int w, double weight){ 8 | this.v = v; 9 | this.w = w; 10 | this.weight = weight; 11 | } 12 | public double weight(){ return weight; } 13 | public int from(){ return this.v; } 14 | public int to(){ return this.w; } 15 | @Override 16 | public String toString() { 17 | return String.format("%d -> %d %.2f", v, w, weight); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/spt/SP.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.spt; 2 | 3 | public interface SP { 4 | /** 5 | * @Description: The distance between w and v, if not connected, dist is infinity. 6 | * @param v 7 | * @return 8 | */ 9 | public double distTo(int v); 10 | /** 11 | * @Description: If there is a path from s to v. 12 | * @param v 13 | * @return 14 | */ 15 | public boolean hasPathTo(int v); 16 | /** 17 | * @Description: Path from s to v. 18 | * @param v 19 | * @return 20 | */ 21 | public Iterable pathTo(int v); 22 | } 23 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/spt/tinyEWD.txt: -------------------------------------------------------------------------------- 1 | 8 2 | 15 3 | 4 5 0.35 4 | 5 4 0.35 5 | 4 7 0.37 6 | 5 7 0.28 7 | 7 5 0.28 8 | 5 1 0.32 9 | 0 4 0.38 10 | 0 2 0.26 11 | 7 3 0.39 12 | 1 3 0.29 13 | 2 7 0.34 14 | 6 2 0.40 15 | 3 6 0.52 16 | 6 0 0.58 17 | 6 4 0.93 18 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/tinyCG.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 8 3 | 0 5 4 | 2 4 5 | 2 3 6 | 1 2 7 | 0 1 8 | 3 4 9 | 3 5 10 | 0 2 -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/tinyDAG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 15 3 | 2 3 4 | 0 6 5 | 0 1 6 | 2 0 7 | 11 12 8 | 9 12 9 | 9 10 10 | 9 11 11 | 3 5 12 | 8 7 13 | 5 4 14 | 0 5 15 | 6 4 16 | 6 9 17 | 7 6 -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/tinyDG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 22 3 | 4 2 4 | 2 3 5 | 3 2 6 | 6 0 7 | 0 1 8 | 2 0 9 | 11 12 10 | 12 9 11 | 9 10 12 | 9 11 13 | 7 9 14 | 10 12 15 | 11 4 16 | 4 3 17 | 3 5 18 | 6 8 19 | 8 6 20 | 5 4 21 | 0 5 22 | 6 4 23 | 6 9 24 | 7 6 25 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/tinyG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 13 3 | 0 5 4 | 4 3 5 | 0 1 6 | 9 12 7 | 6 4 8 | 5 4 9 | 0 2 10 | 11 12 11 | 9 10 12 | 0 6 13 | 7 8 14 | 9 11 15 | 5 3 -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/undirected/AbstractCC.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.undirected; 2 | 3 | import ca.mcmaster.chapter.four.graph.Graph; 4 | 5 | public abstract class AbstractCC implements ConnectionComponent { 6 | protected final Graph g; 7 | public AbstractCC(Graph g){ 8 | this.g = g; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/undirected/AbstractPath.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.undirected; 2 | 3 | import ca.mcmaster.chapter.four.graph.Graph; 4 | import ca.mcmaster.chapter.four.graph.Path; 5 | 6 | public abstract class AbstractPath implements Path { 7 | protected final Graph g; 8 | protected final int s; 9 | public AbstractPath(Graph g, int s) { 10 | super(); 11 | this.g = g; 12 | this.s = s; 13 | }; 14 | } 15 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/undirected/AbstractSearch.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.undirected; 2 | 3 | import ca.mcmaster.chapter.four.graph.Graph; 4 | 5 | public abstract class AbstractSearch implements Search { 6 | protected final Graph g; 7 | protected final int s; 8 | public AbstractSearch(Graph g, int s) { 9 | this.g = g; 10 | this.s = s; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/undirected/ConnectionComponent.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.undirected; 2 | 3 | public interface ConnectionComponent { 4 | /** 5 | * @Description: If v and w are connected. 6 | * @param v 7 | * @param w 8 | * @return 9 | */ 10 | public boolean connected(int v, int w); 11 | /** 12 | * @Description: Number of cc in current graph. 13 | * @return 14 | */ 15 | public int count(); 16 | /** 17 | * @Description: Identification of connection component. 18 | * @param v 19 | * @return 20 | */ 21 | public int id(int v); 22 | } 23 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/undirected/DeepFirstSearch.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.undirected; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | 7 | import ca.mcmaster.chapter.four.graph.Graph; 8 | 9 | public class DeepFirstSearch extends AbstractSearch { 10 | private boolean[] marked; 11 | private int count; 12 | public DeepFirstSearch(Graph g, int s) { 13 | super(g, s); 14 | marked = new boolean[g.V()]; 15 | dfs(g, s); 16 | } 17 | private void dfs(Graph g, int v){ 18 | marked[v] = true; //It means current vertex has been accessed. 19 | count++; //update the number of vertex connected to s. 20 | for(int w : g.adj(v)) 21 | if(!marked[w]) dfs(g, w); //Check all point connected to v, if not accessed, access recursively. 22 | } 23 | @Override 24 | public boolean mark(int v) { 25 | return marked[v]; 26 | } 27 | @Override 28 | public int count() { 29 | return this.count; 30 | } 31 | 32 | public static void main(String[] args) throws FileNotFoundException { 33 | Graph g = new UndirectedGraph(new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/tinyG.txt"))); 34 | Search search = new DeepFirstSearch(g, 12); 35 | System.out.println(search.mark(9)); 36 | System.out.println(search.count()); 37 | g.display(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/undirected/Search.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.undirected; 2 | 3 | public interface Search { 4 | /** 5 | * @Description: If s and v are connected. 6 | * @param v 7 | * @return 8 | */ 9 | public boolean mark(int v); 10 | /** 11 | * @Description: Number of vertex connected to source. 12 | * @return 13 | */ 14 | public int count(); 15 | } 16 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/four/graph/undirected/SymbolGraph.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.undirected; 2 | 3 | import ca.mcmaster.chapter.four.graph.Graph; 4 | 5 | public interface SymbolGraph { 6 | /** 7 | * @Description: Is key a vertex. 8 | * @param key 9 | * @return 10 | */ 11 | public boolean contains(String key); 12 | /** 13 | * @Description: Index of key. 14 | * @param key 15 | * @return 16 | */ 17 | public int index(String key); 18 | /** 19 | * @Description: name of v in symbol table 20 | * @param v 21 | * @return 22 | */ 23 | public String name(int v); 24 | 25 | /** 26 | * @Description: Get the anonymous graph object. 27 | * @return 28 | */ 29 | public Graph G(); 30 | } 31 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one; 2 | 3 | public class BinarySearch { 4 | private static int rank(int key, int[] a){ 5 | return rank(key, a, 0, a.length - 1); 6 | } 7 | 8 | public static int rank(int key, int[] a, int low, int hi){ 9 | System.out.println("low is " + low + "; high is " + hi); 10 | if(low > hi){ 11 | return -1; 12 | } 13 | int mid = low + (hi - low)/2; 14 | if(key < a[mid]) 15 | return rank(key, a, low, mid - 1); 16 | else if(key > a[mid]) 17 | return rank(key, a, mid + 1, hi); 18 | else 19 | return mid; 20 | } 21 | 22 | public static void main(String[] args){ 23 | int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 24 | System.out.println(rank(7, a)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/Evaluate.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one; 2 | 3 | import edu.princeton.cs.algs4.Stack; 4 | 5 | public class Evaluate { 6 | public static void main(String[] args){ 7 | String s = "( 1 + ( ( 1 + 1 ) * ( 1 * 1 ) ) )"; 8 | Stack ops = new Stack(); 9 | Stack value = new Stack(); 10 | String[] tokens = s.split(" "); 11 | 12 | //Put all useful values into stack. 13 | for(String t:tokens){ 14 | if(t.equals("(")) continue; 15 | else if(t.equals("+")) ops.push(t); 16 | else if(t.equals("-")) ops.push(t); 17 | else if(t.equals("*")) ops.push(t); 18 | else if(t.equals("/")) ops.push(t); 19 | else if(t.equals(")")){ 20 | String op = ops.pop(); 21 | Double v = value.pop(); 22 | if(op.equals("+")) v = value.pop() + v; 23 | if(op.equals("-")) v = value.pop() - v; 24 | if(op.equals("*")) v = value.pop() * v; 25 | if(op.equals("/")) v = value.pop() / v; 26 | value.push(v); 27 | }else 28 | value.push(Double.parseDouble(t)); 29 | } 30 | System.out.println(value.pop()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/FIFO/FifoQueue.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.FIFO; 2 | 3 | public interface FifoQueue extends Iterable{ 4 | void enqueue(T t); 5 | T dequeue(); 6 | Boolean isEmpty(); 7 | Integer size(); 8 | } 9 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/MyString.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one; 2 | 3 | import edu.princeton.cs.algs4.In; 4 | 5 | public class MyString { 6 | public static Boolean isPalindrome(String s){ 7 | int len = s.length(); 8 | for(int i = 0; i < (len /2); i++){ 9 | if(s.charAt(i) != s.charAt(len - 1 - i)){ 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | 16 | public static Boolean isSorted(String[] s){ 17 | for(int i = 1; i < s.length; i++){ 18 | String pre = s[i-1]; 19 | String next = s[i]; 20 | System.out.println("pre is: " + pre + "; next is: " + next); 21 | if(pre.compareTo(next) > 0) 22 | return false; 23 | } 24 | return true; 25 | } 26 | 27 | public static void main(String[] args){ 28 | // System.out.println(isPalindrome("112233454332211")); 29 | // System.out.println(isSorted(new String[]{"a","e","c","d","e","f"})); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/bag/Bag.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.bag; 2 | 3 | public interface Bag extends Iterable { 4 | void add(T t); 5 | Boolean isEmpty(); 6 | Integer size(); 7 | } 8 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/bag/ListBag.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.bag; 2 | 3 | import java.util.Iterator; 4 | 5 | public class ListBag implements Bag{ 6 | private Node first; 7 | private Integer size = 0; 8 | private class Node{ 9 | T t; 10 | Node next; 11 | } 12 | public void add(T t) { 13 | Node oldFirst = first; 14 | first = new Node(); 15 | first.t = t; 16 | first.next = oldFirst; 17 | size++; 18 | } 19 | public Boolean isEmpty() { return size.equals(0); }; 20 | public Integer size() { return size; } 21 | public Iterator iterator() { 22 | return new ListIterator(); 23 | } 24 | private class ListIterator implements Iterator{ 25 | private Node current = first; 26 | public boolean hasNext() { return current != null; } 27 | public T next() { 28 | if(!hasNext()) throw new IndexOutOfBoundsException(); 29 | T t = current.t; 30 | current = current.next; 31 | return t; 32 | } 33 | public void remove() {} 34 | } 35 | 36 | public static void main(String[] args) { 37 | ListBag bag = new ListBag<>(); 38 | for(int i = 0; i < 10; i++){ 39 | bag.add(i); 40 | } 41 | Iterator it = bag.iterator(); 42 | while (it.hasNext()) { 43 | System.out.println(it.next()); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/stack/MyStack.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.stack; 2 | 3 | public interface MyStack extends Iterable{ 4 | void push(T t); 5 | T pop(); 6 | Boolean isEmpty(); 7 | Integer size(); 8 | } 9 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/sum/SumProblems.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.sum; 2 | 3 | import java.util.Arrays; 4 | 5 | public class SumProblems { 6 | public static int twoSumFast(Integer[] a){ 7 | Arrays.sort(a); 8 | Integer length = a.length; 9 | int cnt = 0; 10 | for(int i = 0; i < length; i++){ 11 | if(Arrays.binarySearch(a, -a[i]) > i){ 12 | cnt++; 13 | } 14 | } 15 | return cnt; 16 | } 17 | 18 | public static int threeSumFast(Integer[] a){ 19 | int cnt = 0; 20 | Arrays.sort(a); 21 | Integer n = a.length; 22 | for(int i = 0; i < n; i++){ 23 | for (int j = i+1; j < n; j++) { 24 | if(Arrays.binarySearch(a, -a[i]-a[j]) > j){ 25 | cnt++; 26 | } 27 | } 28 | } 29 | return cnt; 30 | } 31 | 32 | public static void main(String[] args) { 33 | Integer[] a = new Integer[]{-3,2,4,-2,5,-2,-2}; 34 | System.out.println(threeSumFast(a)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/unionfind/QuickFind.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.unionfind; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.util.Scanner; 6 | 7 | public class QuickFind extends UnionfindAbstract { 8 | public QuickFind(int N) { 9 | super(N); 10 | } 11 | public void union(int p, int q) { 12 | int pId = a[p]; 13 | int qId = a[q]; 14 | if(pId == qId) return; 15 | for(int i = 0; i < a.length; i++) 16 | if(pId == a[i]) a[i] = qId; 17 | count--; 18 | } 19 | public int find(int p) { 20 | return a[p]; 21 | } 22 | public static void main(String[] args) throws FileNotFoundException{ 23 | File f = new File("src/ca/mcmaster/chapter/one/unionfind/tinyUF.txt"); 24 | Scanner scanner = new Scanner(f); 25 | int N = scanner.nextInt(); 26 | QuickFind uf = new QuickFind(N); 27 | while(scanner.hasNext()){ 28 | int p = scanner.nextInt(); 29 | int q = scanner.nextInt(); 30 | if(uf.connected(p, q)) continue; 31 | uf.union(p, q); 32 | System.out.println(p +" <---> "+ q); 33 | } 34 | System.out.println(uf.count() + " components"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/unionfind/QuickUnion.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.unionfind; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.util.Scanner; 6 | 7 | public class QuickUnion extends UnionfindAbstract{ 8 | public QuickUnion(int N) { 9 | super(N); 10 | } 11 | public void union(int p, int q) { 12 | int pRoot = find(p); 13 | int qRoot = find(q); 14 | if(qRoot == pRoot) return; 15 | a[pRoot] = qRoot; 16 | count--; 17 | } 18 | public int find(int p) { 19 | while( p != a[p]) p = a[p]; 20 | return p; 21 | } 22 | public static void main(String[] args) throws FileNotFoundException{ 23 | File f = new File("src/ca/mcmaster/chapter/one/unionfind/tinyUF.txt"); 24 | Scanner scanner = new Scanner(f); 25 | int N = scanner.nextInt(); 26 | QuickFind uf = new QuickFind(N); 27 | while(scanner.hasNext()){ 28 | int p = scanner.nextInt(); 29 | int q = scanner.nextInt(); 30 | if(uf.connected(p, q)) continue; 31 | uf.union(p, q); 32 | System.out.println(p +" <---> "+ q); 33 | } 34 | System.out.println(uf.count() + " components"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/unionfind/UnionFind.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.unionfind; 2 | 3 | public interface UnionFind { 4 | public void union(int p,int q); 5 | public int find(int p); 6 | public Boolean connected(int p, int q); 7 | public int count(); 8 | } 9 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/unionfind/UnionfindAbstract.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.unionfind; 2 | 3 | public abstract class UnionfindAbstract implements UnionFind { 4 | int count; 5 | int[] a; 6 | public UnionfindAbstract(int N) { 7 | count = N; 8 | a = new int[N]; 9 | for(int i = 0; i < N; i++) 10 | a[i] = i; 11 | } 12 | public Boolean connected(int p, int q) { return find(p) == find(q); } 13 | public int count() { return count; } 14 | } 15 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/unionfind/WeightedUnionFind.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.one.unionfind; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.util.Scanner; 6 | 7 | public class WeightedUnionFind extends UnionfindAbstract { 8 | private int[] size; 9 | public WeightedUnionFind(int N) { 10 | super(N); 11 | size = new int[N]; 12 | for(int i = 0; i < N; i++) 13 | size[i] = 1; 14 | } 15 | public void union(int p, int q) { 16 | int pRoot = find(p); 17 | int qRoot = find(q); 18 | if(pRoot == qRoot) return; 19 | if(size[pRoot] > size[qRoot]){ 20 | a[qRoot] = pRoot; 21 | size[pRoot] += size[qRoot]; 22 | } 23 | else{ 24 | a[pRoot] = qRoot; 25 | size[qRoot] += size[pRoot]; 26 | } 27 | count--; 28 | } 29 | public int find(int p) { 30 | while(p != a[p]) p = a[p]; 31 | return p; 32 | } 33 | public static void main(String[] args) throws FileNotFoundException{ 34 | File f = new File("src/ca/mcmaster/chapter/one/unionfind/tinyUF.txt"); 35 | Scanner scanner = new Scanner(f); 36 | int N = scanner.nextInt(); 37 | QuickFind uf = new QuickFind(N); 38 | while(scanner.hasNext()){ 39 | int p = scanner.nextInt(); 40 | int q = scanner.nextInt(); 41 | if(uf.connected(p, q)) continue; 42 | uf.union(p, q); 43 | System.out.println(p +" <---> "+ q); 44 | } 45 | System.out.println(uf.count() + " components"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/one/unionfind/tinyUF.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 4 3 3 | 3 8 4 | 6 5 5 | 9 4 6 | 2 1 7 | 8 9 8 | 5 0 9 | 7 2 10 | 6 1 11 | 1 0 12 | 6 7 -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/three/BinarySearchST.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.three; 2 | 3 | import java.util.Iterator; 4 | 5 | public class BinarySearchST, V> extends SearchSTAbstract { 6 | public BinarySearchST(int capacity) { super(capacity); } 7 | public int binarySearch(K k) { 8 | int lo = 0, hi = N - 1; 9 | while(lo <= hi){ 10 | int mid = lo + (hi - lo) / 2; 11 | int cmp = keys[mid].compareTo(k); 12 | if(cmp < 0) lo = mid + 1; 13 | else if(cmp > 0) hi = mid - 1; 14 | else return mid; 15 | } 16 | return lo; 17 | } 18 | public Integer traditionalBinarySearch(K k, int lo, int hi){ 19 | if(lo > hi) return lo; 20 | int mid = lo + (hi - lo) / 2; 21 | int cmp = keys[mid].compareTo(k); 22 | if(cmp > 0) return traditionalBinarySearch(k, lo, mid - 1); 23 | else if(cmp < 0) return traditionalBinarySearch(k, mid + 1, hi); 24 | else return mid; 25 | } 26 | 27 | public static void main(String[] args) { 28 | BinarySearchST table = new BinarySearchST<>(100); 29 | table.put("a", "a"); 30 | table.put("c", "c"); 31 | table.put("b", "b"); 32 | table.put("d", "d"); 33 | System.out.println(table.get("d")); 34 | table.delete("d"); 35 | System.out.println(table.get("d")); 36 | Iterable queue = table.keys(0, 2); 37 | Iterator it = queue.iterator(); 38 | while (it.hasNext()) { 39 | System.out.println(it.next()); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/three/SequentialSearchST.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.three; 2 | 3 | public class SequentialSearchST { 4 | private class Node{ 5 | K k; 6 | V v; 7 | Node next; 8 | public Node(K k, V v, Node next){ 9 | this.k = k; 10 | this.v = v; 11 | this.next = next; 12 | } 13 | } 14 | private Node first; 15 | public V get(K k){ 16 | Node current = first; 17 | while(current != null){ 18 | if(current.k.equals(k)) return current.v; 19 | current = current.next; 20 | } 21 | return null; 22 | } 23 | 24 | public void put(K k, V v){ 25 | Node current = first; 26 | while(current != null){ 27 | if(current.k.equals(k)){ 28 | current.v = v; 29 | return; 30 | } 31 | current = current.next; 32 | } 33 | first = new Node(k, v, first); 34 | } 35 | 36 | public static void main(String[] args) { 37 | SequentialSearchST table = new SequentialSearchST<>(); 38 | table.put("a", "aaaa"); 39 | table.put("b", "bbbb"); 40 | table.put("c", "cccc"); 41 | table.put("d", "dddd"); 42 | System.out.println(table.get("a")); 43 | System.out.println(table.get("b")); 44 | System.out.println(table.get("c")); 45 | System.out.println(table.get("d")); 46 | table.put("a", "1111"); 47 | System.out.println(table.get("a")); 48 | System.out.println(table.get("p")); 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/three/bitree/BinaryTreeSymbolTableAbstract.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Seanforfun/Algorithm-and-Leetcode/4ea49415a05d1c6ed54a384841fa46f86c2810e2/Algorithm(4th_Edition)/src/ca/mcmaster/chapter/three/bitree/BinaryTreeSymbolTableAbstract.java -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/two/Sort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.two.Sort; 2 | 3 | public class BubbleSort { 4 | public int[] a = {1, 2,1,4,2,6,234,65,23,5,2,657,2,546}; 5 | public int[] sort(){ 6 | for(int i = 0; i < a.length; i++){ 7 | for(int j = i; j < a.length; j++){ 8 | if(a[i] > a[j]){ 9 | int temp = a[i]; 10 | a[i] = a[j]; 11 | a[j] = temp; 12 | } 13 | } 14 | } 15 | return a; 16 | } 17 | public static void main(String[] args) { 18 | BubbleSort sort = new BubbleSort(); 19 | int[] result = sort.sort(); 20 | for(int i : result) 21 | System.out.println(i); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/two/Sort/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.two.Sort; 2 | 3 | public class InsertionSort implements Sort { 4 | @Override 5 | public void sort(Comparable[] a) { 6 | int size = a.length; 7 | for(int i = 0; i < size; i ++){ 8 | for(int j = i; j > 0 && Sort.less(a, j, j - 1); j--){ Sort.swap(a, j, j-1); } 9 | } 10 | } 11 | public static void main(String[] args) { 12 | Sort sort = new SelectionSort<>(); 13 | Integer[] a = {1, 2,1,4,2,6,234,65,23,5,2,657,2,546}; 14 | sort.sort(a); 15 | Sort.show(a); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/two/Sort/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.two.Sort; 2 | 3 | public class SelectionSort implements Sort { 4 | 5 | @Override 6 | public void sort(Comparable[] a) { 7 | int len = a.length; 8 | for(int i = 0; i < len; i++){ 9 | for(int j = i; j < len; j++){ 10 | if(Sort.less(a, i, j)){ Sort.swap(a, i, j); } 11 | } 12 | } 13 | } 14 | public static void main(String[] args) { 15 | Sort sort = new SelectionSort<>(); 16 | Integer[] a = {1, 2,1,4,2,6,234,65,23,5,2,657,2,546}; 17 | sort.sort(a); 18 | Sort.show(a); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/two/Sort/Sort.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.two.Sort; 2 | 3 | public interface Sort { 4 | /** 5 | * @Description: Sort the array in a descent order. 6 | * @param a: array to sort 7 | */ 8 | public void sort(Comparable[] a); 9 | @SuppressWarnings("unchecked") 10 | static boolean less(Comparable[] a, int i, int j){ 11 | return a[i].compareTo((T)a[j]) < 0; 12 | } 13 | static void swap(Comparable[] a, int i, int j){ 14 | Comparable temp = a[i]; 15 | a[i] = a[j]; 16 | a[j] = temp; 17 | } 18 | static void show(Comparable[] a){ 19 | StringBuilder sb = new StringBuilder(); 20 | for(int i = 0; i < a.length; i++) 21 | sb.append(a[i] + " "); 22 | System.out.println(sb.toString()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/two/queue/HeapSort.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.two.queue; 2 | 3 | public class HeapSort { 4 | private static Boolean less(Comparable[] a,int i, int j){ return a[i].compareTo(a[j]) < 0; } 5 | private static void swap(Comparable[] a, int i, int j){ Comparable temp = a[i]; a[i] = a[j]; a[j] = temp; } 6 | public static void sink(Comparable[] a, int k, int length){ 7 | while(2 * k <= length){ 8 | int j = 2 * k; 9 | if(j < length && less(a, j, j+1)) j++; 10 | if(!less(a, k, j)) break; 11 | swap(a, k, j); 12 | k = j; 13 | } 14 | } 15 | public static void heapSort(Comparable[] a){ 16 | int length = a.length-1; 17 | for(int i = length/2; i >=0; i--) sink(a, i, length); 18 | while(length >= 1){ 19 | swap(a, 0, length--); 20 | sink(a, 0, length); 21 | } 22 | } 23 | 24 | public static void show(Comparable[] a){ 25 | for(int i = 0; i < a.length; i++){ 26 | System.out.print(a[i] + " "); 27 | } 28 | System.out.println(); 29 | } 30 | 31 | public static void main(String[] args) { 32 | Integer[] a = new Integer[]{18,27,33,55,6,3,23,2,3,5,2,45,1,4,2,5,7,3,7,456,96,7,23,8}; 33 | heapSort(a); 34 | show(a); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/chapter/two/queue/MaxPriorityQueue.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.two.queue; 2 | 3 | public interface MaxPriorityQueue> { 4 | /** 5 | * @Description: Insert an element into the priority queue 6 | * @param t 7 | */ 8 | public void insert(T t); 9 | 10 | /** 11 | * @Description: Return the max value from the priority queue. 12 | * @return 13 | */ 14 | public T max(); 15 | 16 | /** 17 | * @Description: Return and delete the max value from the priority queue. 18 | * @return 19 | */ 20 | public T delMax(); 21 | 22 | /** 23 | * @Description: Check if current queue is empty. 24 | * @return 25 | */ 26 | public Boolean isEmpty(); 27 | 28 | /** 29 | * @Description: Return the number of the elements left in the queue. 30 | * @return 31 | */ 32 | public int size(); 33 | } 34 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/ArrayBlockingQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | 5 | public class ArrayBlockingQueueConsumer implements Runnable { 6 | private ArrayBlockingQueue queue; 7 | public ArrayBlockingQueueConsumer(ArrayBlockingQueue queue) { 8 | super(); 9 | this.queue = queue; 10 | } 11 | @Override 12 | public void run() { 13 | try { 14 | for(int i = 0; i < 100; i++){ 15 | Thread.currentThread().join(10); 16 | System.out.println("Consumer: get " + queue.take() + " from queue..."); 17 | Thread.sleep(10); 18 | } 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | 24 | public static void main(String[] args) throws InterruptedException { 25 | ArrayBlockingQueue queue = new ArrayBlockingQueue<>(10); 26 | new Thread(new ArrayBlockingQueueConsumer(queue)).start(); 27 | new Thread(new ArrayBlockingQueueProducer(queue)).start(); 28 | Thread.currentThread().join(); 29 | System.out.println("Finish..."); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/ArrayBlockingQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class ArrayBlockingQueueProducer implements Runnable { 7 | private ArrayBlockingQueue queue; 8 | public ArrayBlockingQueueProducer(ArrayBlockingQueue queue) { 9 | super(); 10 | this.queue = queue; 11 | } 12 | private volatile AtomicInteger ai = new AtomicInteger(0); 13 | @Override 14 | public void run() { 15 | while(true){ 16 | try { 17 | queue.put(ai.getAndIncrement()); 18 | System.out.println("Producer: put " + ai.get() + " into queue..."); 19 | Thread.sleep(10); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/ConcurrentLinkQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ConcurrentLinkedQueue; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class ConcurrentLinkQueueProducer implements Runnable{ 7 | private ConcurrentLinkedQueue q; 8 | public ConcurrentLinkQueueProducer(ConcurrentLinkedQueue q) { 9 | super(); 10 | this.q = q; 11 | } 12 | @Override 13 | public void run() { 14 | AtomicInteger al = new AtomicInteger(0); 15 | while(true){ 16 | q.offer(al.get()); 17 | System.out.println("Producer: put " + al.getAndIncrement() + " into queue..."); 18 | try { 19 | Thread.sleep(10); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/ConcurrentLinkedQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ConcurrentLinkedQueue; 4 | 5 | public class ConcurrentLinkedQueueConsumer implements Runnable { 6 | private ConcurrentLinkedQueue q; 7 | public ConcurrentLinkedQueueConsumer(ConcurrentLinkedQueue q) { 8 | super(); 9 | this.q = q; 10 | } 11 | @Override 12 | public void run() { 13 | try { 14 | while(true){ 15 | System.out.println("Consumer: get " + q.poll() + " from queue..."); 16 | Thread.sleep(10); 17 | } 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | public static void main(String[] args) throws InterruptedException { 24 | ConcurrentLinkedQueue q = new ConcurrentLinkedQueue<>(); 25 | Thread producer = new Thread(new ConcurrentLinkQueueProducer(q)); 26 | producer.start(); 27 | producer.join(100); 28 | new Thread(new ConcurrentLinkedQueueConsumer(q)).start(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/DelayMsg.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.Delayed; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class DelayMsg implements Delayed{ 7 | private Long expire; 8 | private Long insertTime; 9 | private V v; 10 | 11 | public V getV() { 12 | return v; 13 | } 14 | public Long getInsertTime() { 15 | return insertTime; 16 | } 17 | public DelayMsg(Long expire, Long insertTime, V v){ 18 | this.expire = expire; 19 | this.insertTime = insertTime; 20 | this.v = v; 21 | } 22 | @Override 23 | public int compareTo(Delayed o) { 24 | @SuppressWarnings("rawtypes") 25 | Long delta = insertTime - ((DelayMsg)o).getInsertTime(); 26 | if(delta < 0) return -1; 27 | else if(delta == 0) return 0; 28 | else 29 | return 1; 30 | } 31 | 32 | /* (non-Javadoc) 33 | * @see java.util.concurrent.Delayed#getDelay(java.util.concurrent.TimeUnit) 34 | * 用于定义延时策略 35 | */ 36 | @Override 37 | public long getDelay(TimeUnit unit) { 38 | return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/DelayQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | import java.util.concurrent.DelayQueue; 7 | 8 | public class DelayQueueConsumer implements Runnable { 9 | private DelayQueue> q; 10 | public DelayQueueConsumer(DelayQueue> q) { 11 | super(); 12 | this.q = q; 13 | } 14 | @Override 15 | public void run() { 16 | DateFormat df = new SimpleDateFormat("HH:mm:ss"); 17 | while (true) { 18 | try { 19 | System.out.println(df.format(new Date(System.currentTimeMillis())) + ": Consumer: take " + ((DelayMsg)q.take()).getV() + " from queue..."); 20 | Thread.sleep(1); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | DelayQueue> q = new DelayQueue<>(); 29 | new Thread(new DelayQueueConsumer(q)).start(); 30 | new Thread(new DelayQueueProducer(q)).start(); 31 | System.out.println("Main finish..."); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/DelayQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | import java.util.concurrent.DelayQueue; 7 | 8 | public class DelayQueueProducer implements Runnable { 9 | private DelayQueue> q; 10 | 11 | public DelayQueueProducer(DelayQueue> q) { 12 | super(); 13 | this.q = q; 14 | } 15 | 16 | @Override 17 | public void run() { 18 | DateFormat df = new SimpleDateFormat("HH:mm:ss"); 19 | for(int i = 0; i < 10; i++){ 20 | q.offer(new DelayMsg(System.currentTimeMillis() + 10000, System.currentTimeMillis(), i)); 21 | System.out.println(df.format(new Date(System.currentTimeMillis())) + ": Producer: put " + i + " into queue..."); 22 | try { 23 | Thread.sleep(1); 24 | } catch (InterruptedException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/LinkedBlockingQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.LinkedBlockingQueue; 4 | 5 | public class LinkedBlockingQueueConsumer implements Runnable { 6 | private LinkedBlockingQueue q; 7 | public LinkedBlockingQueueConsumer(LinkedBlockingQueue q) { 8 | super(); 9 | this.q = q; 10 | } 11 | @Override 12 | public void run() { 13 | try { 14 | while(true){ 15 | System.out.println("Consumer: take " + q.take() + " from queue..."); 16 | Thread.sleep(10); 17 | } 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | public static void main(String[] args) throws InterruptedException { 24 | LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); 25 | new Thread(new LinkedBlockingQueueConsumer(queue)).start(); 26 | new Thread(new LinkedBlockingQueueProducer(queue)).start(); 27 | Thread.currentThread().join(); 28 | System.out.println("Finish..."); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/LinkedBlockingQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.LinkedBlockingQueue; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class LinkedBlockingQueueProducer implements Runnable { 7 | private LinkedBlockingQueue q; 8 | private AtomicInteger ai = new AtomicInteger(); 9 | public LinkedBlockingQueueProducer(LinkedBlockingQueue q) { 10 | super(); 11 | this.q = q; 12 | } 13 | @Override 14 | public void run() { 15 | for(int i = 0; i < 100; i++){ 16 | try { 17 | q.put(ai.get()); 18 | System.out.println("Producer: put " + ai.getAndIncrement() + " into queue..."); 19 | Thread.sleep(10); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/PriorityBlockingQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.PriorityBlockingQueue; 4 | 5 | public class PriorityBlockingQueueConsumer implements Runnable { 6 | 7 | private PriorityBlockingQueue q; 8 | public PriorityBlockingQueueConsumer(PriorityBlockingQueue q) { 9 | super(); 10 | this.q = q; 11 | } 12 | @Override 13 | public void run() { 14 | while(true){ 15 | try { 16 | System.out.println("Consumer: take " + q.take() + " from queue..."); 17 | Thread.sleep(10); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) throws InterruptedException { 25 | PriorityBlockingQueue q = new PriorityBlockingQueue<>(); 26 | Thread producer = new Thread(new PriorityBlockingQueueProducer(q)); 27 | producer.start(); 28 | producer.join(200); 29 | new Thread(new PriorityBlockingQueueConsumer(q)).start(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithm(4th_Edition)/src/ca/mcmaster/queue/arrayblockingqueue/PriorityBlockingQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.PriorityBlockingQueue; 5 | 6 | public class PriorityBlockingQueueProducer implements Runnable { 7 | private PriorityBlockingQueue q; 8 | public PriorityBlockingQueueProducer(PriorityBlockingQueue q) { 9 | super(); 10 | this.q = q; 11 | } 12 | @Override 13 | public void run() { 14 | while(true){ 15 | Random random = new Random(); 16 | int nextInt = random.nextInt(100); 17 | q.put(nextInt); 18 | System.out.println("Producer: put " + nextInt + " into queue..."); 19 | try { 20 | Thread.sleep(10); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DataStructrue/Graph/AbstractCC.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public abstract class AbstractCC implements ConnectionComponent { 4 | protected final Graph g; 5 | public AbstractCC(Graph g){ 6 | this.g = g; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /DataStructrue/Graph/AbstractPath.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public abstract class AbstractPath implements Path { 4 | protected final Graph g; 5 | protected final int s; 6 | public AbstractPath(Graph g, int s) { 7 | super(); 8 | this.g = g; 9 | this.s = s; 10 | }; 11 | } 12 | -------------------------------------------------------------------------------- /DataStructrue/Graph/AbstractSearch.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public abstract class AbstractSearch implements Search { 4 | protected final Graph g; 5 | protected final int s; 6 | public AbstractSearch(Graph g, int s) { 7 | this.g = g; 8 | this.s = s; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /DataStructrue/Graph/ConnectionComponent.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public interface ConnectionComponent { 4 | /** 5 | * @Description: If v and w are connected. 6 | * @param v 7 | * @param w 8 | * @return 9 | */ 10 | public boolean connected(int v, int w); 11 | /** 12 | * @Description: Number of cc in current graph. 13 | * @return 14 | */ 15 | public int count(); 16 | /** 17 | * @Description: Identification of connection component. 18 | * @param v 19 | * @return 20 | */ 21 | public int id(int v); 22 | } 23 | -------------------------------------------------------------------------------- /DataStructrue/Graph/DeepFirstSearch.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | 7 | public class DeepFirstSearch extends AbstractSearch { 8 | private boolean[] marked; 9 | private int count; 10 | public DeepFirstSearch(Graph g, int s) { 11 | super(g, s); 12 | marked = new boolean[g.V()]; 13 | dfs(g, s); 14 | } 15 | private void dfs(Graph g, int v){ 16 | marked[v] = true; //It means current vertex has been accessed. 17 | count++; //update the number of vertex connected to s. 18 | for(int w : g.adj(v)) 19 | if(!marked[w]) dfs(g, w); //Check all point connected to v, if not accessed, access recursively. 20 | } 21 | @Override 22 | public boolean mark(int v) { 23 | return marked[v]; 24 | } 25 | @Override 26 | public int count() { 27 | return this.count; 28 | } 29 | 30 | public static void main(String[] args) throws FileNotFoundException { 31 | Graph g = new UndirectedGraph(new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/tinyG.txt"))); 32 | Search search = new DeepFirstSearch(g, 12); 33 | System.out.println(search.mark(9)); 34 | System.out.println(search.count()); 35 | g.display(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /DataStructrue/Graph/DepthFirstOrder.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | import java.util.Queue; 4 | import java.util.Stack; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | 7 | public class DepthFirstOrder { 8 | private final boolean[] marked; 9 | private final Queue pre; 10 | private final Queue post; 11 | private final Stack reversePost; 12 | public DepthFirstOrder(Digraph g){ 13 | pre = new LinkedBlockingQueue(); 14 | post = new LinkedBlockingQueue<>(); 15 | reversePost = new Stack<>(); 16 | marked = new boolean[g.V()]; 17 | for(int v = 0; v < g.V(); v++) 18 | if(!marked[v]) dfs(g, v); 19 | } 20 | 21 | private void dfs(Digraph g, int v){ 22 | pre.offer(v); 23 | marked[v] = true; 24 | for(int w : g.adj(v)) 25 | if(!marked[w]) dfs(g, w); 26 | post.offer(v); 27 | reversePost.push(v); 28 | } 29 | public Iterable pre(){ 30 | return this.pre; 31 | } 32 | public Iterable post(){ 33 | return this.post(); 34 | } 35 | public Iterable reversePost(){ 36 | return this.reversePost; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /DataStructrue/Graph/Digraph.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public interface Digraph { 4 | /** 5 | * @Description: Number of vertex. 6 | * @return 7 | */ 8 | public int V(); 9 | /** 10 | * @Description: Number of edge. 11 | * @return 12 | */ 13 | public int E(); 14 | /** 15 | * @Description: Add an edge between two vertex. v->w. 16 | * @param v 17 | * @param w 18 | */ 19 | public void addEdge(int v, int w); 20 | /** 21 | * @Description: Return vertex point out from v. 22 | * @param v 23 | * @return 24 | */ 25 | public Iterable adj(int v); 26 | /** 27 | * @Description: Get the reverse graph of current graph. 28 | * @return 29 | */ 30 | public Digraph reverse(); 31 | /** 32 | * @Description: Print current graph. 33 | */ 34 | public void display(); 35 | } 36 | -------------------------------------------------------------------------------- /DataStructrue/Graph/DirectedDFS.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | 7 | import ca.mcmaster.chapter.one.bag.Bag; 8 | import ca.mcmaster.chapter.one.bag.ListBag; 9 | 10 | public class DirectedDFS { 11 | private final boolean[] marked; 12 | public DirectedDFS(Digraph g, int s){ 13 | this.marked = new boolean[g.V()]; 14 | dfs(g, s); 15 | } 16 | public DirectedDFS(Digraph g, Iterable sources){ 17 | marked = new boolean[g.V()]; 18 | for(int s : sources) 19 | if(!marked[s]) dfs(g, s); 20 | } 21 | private void dfs(Digraph g, int s) { 22 | marked[s] = true; 23 | for(int w : g.adj(s)) 24 | if(!marked[w]) dfs(g, w); 25 | } 26 | public boolean mark(int v){ 27 | return marked[v]; 28 | } 29 | public static void main(String[] args) throws FileNotFoundException { 30 | Digraph g = new DigraphImpl(new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/tinyDG.txt"))); 31 | Bag bag = new ListBag(); 32 | bag.add(1); 33 | bag.add(2); 34 | bag.add(6); 35 | DirectedDFS d = new DirectedDFS(g, bag); 36 | StringBuilder sb = new StringBuilder(); 37 | for(int v = 0; v < g.V(); v++){ 38 | if(d.mark(v)) sb.append(v + " "); 39 | } 40 | System.out.println(sb.toString()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /DataStructrue/Graph/DirectedEdge.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.spt; 2 | 3 | public class DirectedEdge { 4 | private final int v; //边的起始点 5 | private final int w; //边的指向 6 | private final double weight; //有向边的权重 7 | public DirectedEdge(int v, int w, double weight){ 8 | this.v = v; 9 | this.w = w; 10 | this.weight = weight; 11 | } 12 | public double weight(){ return weight; } 13 | public int from(){ return this.v; } 14 | public int to(){ return this.w; } 15 | @Override 16 | public String toString() { 17 | return String.format("%d -> %d %.2f", v, w, weight); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /DataStructrue/Graph/Edge.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.mstree; 2 | 3 | public class Edge implements Comparable { 4 | private final int v; 5 | private final int w; 6 | private final double weight; 7 | public Edge(int v, int w, double weight){ 8 | this.v = v; 9 | this.w = w; 10 | this.weight = weight; 11 | } 12 | @Override 13 | public int compareTo(Edge o) { 14 | if(this.weight - o.weight > 0) return 1; 15 | else if(this.weight == o.weight) return 0; 16 | else return -1; 17 | } 18 | public double weight(){ 19 | return this.weight; 20 | } 21 | public int either(){ 22 | return v; 23 | } 24 | public int other(int v){ 25 | if(v == this.v) return w; 26 | else return v; 27 | } 28 | @Override 29 | public String toString() { 30 | return String.format("%d-%d %.2f", v, w, weight); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /DataStructrue/Graph/MST.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.mstree; 2 | 3 | public interface MST { 4 | /** 5 | * @Description: Find the edges on the minimum spanning tree. 6 | * @return 7 | */ 8 | public Iterable edges(); 9 | /** 10 | * @Description: Return the total weight of the tree. 11 | * @return 12 | */ 13 | public double weight(); 14 | } 15 | -------------------------------------------------------------------------------- /DataStructrue/Graph/Path.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public interface Path { 4 | /** 5 | * @Description: If there is a path from s to v 6 | * @param v 7 | * @return 8 | */ 9 | public boolean hasPathTo(int v); 10 | /** 11 | * @Description: Return the path from s to v if it exists and return null if not existing. 12 | * @param v 13 | * @return 14 | */ 15 | Iterable pathTo(int v); 16 | } 17 | -------------------------------------------------------------------------------- /DataStructrue/Graph/PrimMst.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.mstree; 2 | 3 | import edu.princeton.cs.algs4.IndexMinPQ; 4 | 5 | public class PrimMst implements MST { 6 | private Edge[] edgeTo; 7 | private double[] distTo; 8 | private boolean[] marked; 9 | private IndexMinPQ pq; 10 | public PrimMst(EdgeWeightedGraph g) { 11 | edgeTo = new Edge[g.V()]; 12 | distTo = new double[g.V()]; 13 | marked = new boolean[g.V()]; 14 | for(int i = 0; i < g.V(); i++){ 15 | distTo[i] = Double.POSITIVE_INFINITY; 16 | } 17 | pq = new IndexMinPQ(g.V()); 18 | distTo[0] = 0.0d; 19 | while(!pq.isEmpty()) 20 | visit(g, pq.delMin()); 21 | } 22 | private void visit(EdgeWeightedGraph g, int v){ //当前的顶点不在最小树中 23 | marked[v] = true; 24 | for(Edge e : g.adj(v)){ //遍历连接这个顶点的所有边 25 | int w = e.other(v); //找到这些边中除了v的另一个顶点 26 | if(marked[w]) continue; //v-w已经在树中,失效 27 | if(e.weight() < distTo[w]){ //判断是不是可以替代 28 | edgeTo[w] = e; 29 | distTo[w] = e.weight(); 30 | if(pq.contains(w)) pq.change(w, distTo[w]); 31 | else pq.insert(w, distTo[w]); 32 | } 33 | } 34 | } 35 | @Override 36 | public Iterable edges() { 37 | return null; 38 | } 39 | @Override 40 | public double weight() { 41 | return 0; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /DataStructrue/Graph/SCC.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | public interface SCC { 4 | /** 5 | * @Description: Check if v and w are connected. 6 | * @param v 7 | * @param w 8 | * @return 9 | */ 10 | public boolean strongConnected(int v, int w); 11 | /** 12 | * @Description: The number of strong connected component. 13 | * @return 14 | */ 15 | public int count(); 16 | /** 17 | * @Description: Which of the strong component belongs to. 18 | * @param v 19 | * @return 20 | */ 21 | int id(int v); 22 | } 23 | -------------------------------------------------------------------------------- /DataStructrue/Graph/SP.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.spt; 2 | 3 | public interface SP { 4 | /** 5 | * @Description: The distance between w and v, if not connected, dist is infinity. 6 | * @param v 7 | * @return 8 | */ 9 | public double distTo(int v); 10 | /** 11 | * @Description: If there is a path from s to v. 12 | * @param v 13 | * @return 14 | */ 15 | public boolean hasPathTo(int v); 16 | /** 17 | * @Description: Path from s to v. 18 | * @param v 19 | * @return 20 | */ 21 | public Iterable pathTo(int v); 22 | } 23 | -------------------------------------------------------------------------------- /DataStructrue/Graph/Search.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public interface Search { 4 | /** 5 | * @Description: If s and v are connected. 6 | * @param v 7 | * @return 8 | */ 9 | public boolean mark(int v); 10 | /** 11 | * @Description: Number of vertex connected to source. 12 | * @return 13 | */ 14 | public int count(); 15 | } 16 | -------------------------------------------------------------------------------- /DataStructrue/Graph/StrongCircleComponent.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | public class StrongCircleComponent implements SCC { 4 | private boolean[] marked; 5 | private int[] id; 6 | private int count; 7 | public StrongCircleComponent(Digraph g) { 8 | marked = new boolean[g.V()]; 9 | id = new int[g.V()]; 10 | DepthFirstOrder order = new DepthFirstOrder(g.reverse()); 11 | for(int s : order.reversePost()){ //从栈中顺序读取顶点 12 | if(!marked[s]){ 13 | dfs(g, s); count++; 14 | } 15 | } 16 | } 17 | 18 | private void dfs(Digraph g, int v){ 19 | marked[v] = true; 20 | id[v] = count; 21 | for(int w : g.adj(v)) 22 | if(!marked[w]) 23 | dfs(g, w); 24 | } 25 | @Override 26 | public boolean strongConnected(int v, int w) { 27 | return id[v] == id[w]; 28 | } 29 | 30 | @Override 31 | public int count() { 32 | return count; 33 | } 34 | 35 | @Override 36 | public int id(int v) { 37 | return id[v]; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /DataStructrue/Graph/SymbolGraph.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | public interface SymbolGraph { 4 | /** 5 | * @Description: Is key a vertex. 6 | * @param key 7 | * @return 8 | */ 9 | public boolean contains(String key); 10 | /** 11 | * @Description: Index of key. 12 | * @param key 13 | * @return 14 | */ 15 | public int index(String key); 16 | /** 17 | * @Description: name of v in symbol table 18 | * @param v 19 | * @return 20 | */ 21 | public String name(int v); 22 | 23 | /** 24 | * @Description: Get the anonymous graph object. 25 | * @return 26 | */ 27 | public Graph G(); 28 | } 29 | -------------------------------------------------------------------------------- /DataStructrue/Graph/Topological.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph.directed; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileNotFoundException; 6 | 7 | public class Topological { 8 | private Iterable order; 9 | public Topological(Digraph g){ 10 | DirectedCycle dc = new DirectedCycle(g); 11 | if(!dc.hasCycle()){ 12 | DepthFirstOrder dfo = new DepthFirstOrder(g); 13 | order = dfo.reversePost(); 14 | } 15 | } 16 | public Iterable order(){ 17 | return order; 18 | } 19 | public boolean isDAG(){ 20 | return order != null; 21 | } 22 | public static void main(String[] args) throws FileNotFoundException { 23 | Digraph g = new DigraphImpl(new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/tinyDG.txt"))); 24 | Topological topological = new Topological(g); 25 | StringBuilder sb = new StringBuilder(); 26 | for(int i : topological.order()){ 27 | sb.append(i + " "); 28 | } 29 | System.out.println(sb.toString()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /DataStructrue/Graph/UndirectedGraph.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.chapter.four.graph; 2 | 3 | import java.io.FileInputStream; 4 | import java.util.Scanner; 5 | 6 | import ca.mcmaster.chapter.one.bag.Bag; 7 | import ca.mcmaster.chapter.one.bag.ListBag; 8 | 9 | public class UndirectedGraph implements Graph { 10 | private final int V; //vertex 11 | private int E; //edge 12 | private Bag[] adj; //adjacency table. 13 | @SuppressWarnings("unchecked") 14 | public UndirectedGraph(int V) { 15 | this.V = V; 16 | adj = new ListBag[V]; 17 | for(int v = 0; v < V; v++) 18 | adj[v] = new ListBag<>(); 19 | } 20 | @SuppressWarnings("unchecked") 21 | public UndirectedGraph(FileInputStream in){ 22 | Scanner scanner = new Scanner(in); 23 | this.V = scanner.nextInt(); 24 | adj = new ListBag[V]; 25 | for(int v = 0; v < V; v++) 26 | adj[v] = new ListBag<>(); 27 | int E = scanner.nextInt(); 28 | for(int e = 0; e < E; e++){ 29 | int v = scanner.nextInt(); 30 | int w = scanner.nextInt(); 31 | addEdge(v, w); 32 | } 33 | scanner.close(); 34 | } 35 | @Override 36 | public int V() { return V; } 37 | @Override 38 | public int E() { return 0; } 39 | @Override 40 | public void addEdge(int v, int w) { 41 | adj[v].add(w); 42 | adj[w].add(v); 43 | this.E++; 44 | } 45 | 46 | @Override 47 | public Iterable adj(int v) { 48 | return adj[v]; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /DataStructrue/Graph/tinyG.txt: -------------------------------------------------------------------------------- 1 | 13 2 | 13 3 | 0 5 4 | 4 3 5 | 0 1 6 | 9 12 7 | 6 4 8 | 5 4 9 | 0 2 10 | 11 12 11 | 9 10 12 | 0 6 13 | 7 8 14 | 9 11 15 | 5 3 -------------------------------------------------------------------------------- /DataStructrue/Queue/ArrayBlockingQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | 5 | public class ArrayBlockingQueueConsumer implements Runnable { 6 | private ArrayBlockingQueue queue; 7 | public ArrayBlockingQueueConsumer(ArrayBlockingQueue queue) { 8 | super(); 9 | this.queue = queue; 10 | } 11 | @Override 12 | public void run() { 13 | try { 14 | for(int i = 0; i < 100; i++){ 15 | Thread.currentThread().join(10); 16 | System.out.println("Consumer: get " + queue.take() + " from queue..."); 17 | Thread.sleep(10); 18 | } 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | 24 | public static void main(String[] args) throws InterruptedException { 25 | ArrayBlockingQueue queue = new ArrayBlockingQueue<>(10); 26 | new Thread(new ArrayBlockingQueueConsumer(queue)).start(); 27 | new Thread(new ArrayBlockingQueueProducer(queue)).start(); 28 | Thread.currentThread().join(); 29 | System.out.println("Finish..."); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /DataStructrue/Queue/ArrayBlockingQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class ArrayBlockingQueueProducer implements Runnable { 7 | private ArrayBlockingQueue queue; 8 | public ArrayBlockingQueueProducer(ArrayBlockingQueue queue) { 9 | super(); 10 | this.queue = queue; 11 | } 12 | private volatile AtomicInteger ai = new AtomicInteger(0); 13 | @Override 14 | public void run() { 15 | while(true){ 16 | try { 17 | queue.put(ai.getAndIncrement()); 18 | System.out.println("Producer: put " + ai.get() + " into queue..."); 19 | Thread.sleep(10); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /DataStructrue/Queue/ConcurrentLinkQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ConcurrentLinkedQueue; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class ConcurrentLinkQueueProducer implements Runnable{ 7 | private ConcurrentLinkedQueue q; 8 | public ConcurrentLinkQueueProducer(ConcurrentLinkedQueue q) { 9 | super(); 10 | this.q = q; 11 | } 12 | @Override 13 | public void run() { 14 | AtomicInteger al = new AtomicInteger(0); 15 | while(true){ 16 | q.offer(al.get()); 17 | System.out.println("Producer: put " + al.getAndIncrement() + " into queue..."); 18 | try { 19 | Thread.sleep(10); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /DataStructrue/Queue/ConcurrentLinkedQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.ConcurrentLinkedQueue; 4 | 5 | public class ConcurrentLinkedQueueConsumer implements Runnable { 6 | private ConcurrentLinkedQueue q; 7 | public ConcurrentLinkedQueueConsumer(ConcurrentLinkedQueue q) { 8 | super(); 9 | this.q = q; 10 | } 11 | @Override 12 | public void run() { 13 | try { 14 | while(true){ 15 | System.out.println("Consumer: get " + q.poll() + " from queue..."); 16 | Thread.sleep(10); 17 | } 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | public static void main(String[] args) throws InterruptedException { 24 | ConcurrentLinkedQueue q = new ConcurrentLinkedQueue<>(); 25 | Thread producer = new Thread(new ConcurrentLinkQueueProducer(q)); 26 | producer.start(); 27 | producer.join(100); 28 | new Thread(new ConcurrentLinkedQueueConsumer(q)).start(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /DataStructrue/Queue/DelayMsg.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.Delayed; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class DelayMsg implements Delayed{ 7 | private Long expire; 8 | private Long insertTime; 9 | private V v; 10 | 11 | public V getV() { 12 | return v; 13 | } 14 | public Long getInsertTime() { 15 | return insertTime; 16 | } 17 | public DelayMsg(Long expire, Long insertTime, V v){ 18 | this.expire = expire; 19 | this.insertTime = insertTime; 20 | this.v = v; 21 | } 22 | @Override 23 | public int compareTo(Delayed o) { 24 | @SuppressWarnings("rawtypes") 25 | Long delta = insertTime - ((DelayMsg)o).getInsertTime(); 26 | if(delta < 0) return -1; 27 | else if(delta == 0) return 0; 28 | else 29 | return 1; 30 | } 31 | 32 | /* (non-Javadoc) 33 | * @see java.util.concurrent.Delayed#getDelay(java.util.concurrent.TimeUnit) 34 | * 用于定义延时策略 35 | */ 36 | @Override 37 | public long getDelay(TimeUnit unit) { 38 | return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /DataStructrue/Queue/DelayQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | import java.util.concurrent.DelayQueue; 7 | 8 | public class DelayQueueConsumer implements Runnable { 9 | private DelayQueue> q; 10 | public DelayQueueConsumer(DelayQueue> q) { 11 | super(); 12 | this.q = q; 13 | } 14 | @Override 15 | public void run() { 16 | DateFormat df = new SimpleDateFormat("HH:mm:ss"); 17 | while (true) { 18 | try { 19 | System.out.println(df.format(new Date(System.currentTimeMillis())) + ": Consumer: take " + ((DelayMsg)q.take()).getV() + " from queue..."); 20 | Thread.sleep(1); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | DelayQueue> q = new DelayQueue<>(); 29 | new Thread(new DelayQueueConsumer(q)).start(); 30 | new Thread(new DelayQueueProducer(q)).start(); 31 | System.out.println("Main finish..."); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DataStructrue/Queue/DelayQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | import java.util.concurrent.DelayQueue; 7 | 8 | public class DelayQueueProducer implements Runnable { 9 | private DelayQueue> q; 10 | 11 | public DelayQueueProducer(DelayQueue> q) { 12 | super(); 13 | this.q = q; 14 | } 15 | 16 | @Override 17 | public void run() { 18 | DateFormat df = new SimpleDateFormat("HH:mm:ss"); 19 | for(int i = 0; i < 10; i++){ 20 | q.offer(new DelayMsg(System.currentTimeMillis() + 10000, System.currentTimeMillis(), i)); 21 | System.out.println(df.format(new Date(System.currentTimeMillis())) + ": Producer: put " + i + " into queue..."); 22 | try { 23 | Thread.sleep(1); 24 | } catch (InterruptedException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /DataStructrue/Queue/LinkedBlockingQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.LinkedBlockingQueue; 4 | 5 | public class LinkedBlockingQueueConsumer implements Runnable { 6 | private LinkedBlockingQueue q; 7 | public LinkedBlockingQueueConsumer(LinkedBlockingQueue q) { 8 | super(); 9 | this.q = q; 10 | } 11 | @Override 12 | public void run() { 13 | try { 14 | while(true){ 15 | System.out.println("Consumer: take " + q.take() + " from queue..."); 16 | Thread.sleep(10); 17 | } 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | public static void main(String[] args) throws InterruptedException { 24 | LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); 25 | new Thread(new LinkedBlockingQueueConsumer(queue)).start(); 26 | new Thread(new LinkedBlockingQueueProducer(queue)).start(); 27 | Thread.currentThread().join(); 28 | System.out.println("Finish..."); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /DataStructrue/Queue/LinkedBlockingQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.LinkedBlockingQueue; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class LinkedBlockingQueueProducer implements Runnable { 7 | private LinkedBlockingQueue q; 8 | private AtomicInteger ai = new AtomicInteger(); 9 | public LinkedBlockingQueueProducer(LinkedBlockingQueue q) { 10 | super(); 11 | this.q = q; 12 | } 13 | @Override 14 | public void run() { 15 | for(int i = 0; i < 100; i++){ 16 | try { 17 | q.put(ai.get()); 18 | System.out.println("Producer: put " + ai.getAndIncrement() + " into queue..."); 19 | Thread.sleep(10); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /DataStructrue/Queue/PriorityBlockingQueueConsumer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.concurrent.PriorityBlockingQueue; 4 | 5 | public class PriorityBlockingQueueConsumer implements Runnable { 6 | 7 | private PriorityBlockingQueue q; 8 | public PriorityBlockingQueueConsumer(PriorityBlockingQueue q) { 9 | super(); 10 | this.q = q; 11 | } 12 | @Override 13 | public void run() { 14 | while(true){ 15 | try { 16 | System.out.println("Consumer: take " + q.take() + " from queue..."); 17 | Thread.sleep(10); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) throws InterruptedException { 25 | PriorityBlockingQueue q = new PriorityBlockingQueue<>(); 26 | Thread producer = new Thread(new PriorityBlockingQueueProducer(q)); 27 | producer.start(); 28 | producer.join(200); 29 | new Thread(new PriorityBlockingQueueConsumer(q)).start(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /DataStructrue/Queue/PriorityBlockingQueueProducer.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.queue.arrayblockingqueue; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.PriorityBlockingQueue; 5 | 6 | public class PriorityBlockingQueueProducer implements Runnable { 7 | private PriorityBlockingQueue q; 8 | public PriorityBlockingQueueProducer(PriorityBlockingQueue q) { 9 | super(); 10 | this.q = q; 11 | } 12 | @Override 13 | public void run() { 14 | while(true){ 15 | Random random = new Random(); 16 | int nextInt = random.nextInt(100); 17 | q.put(nextInt); 18 | System.out.println("Producer: put " + nextInt + " into queue..."); 19 | try { 20 | Thread.sleep(10); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DataStructrue/Search/BinarySearch.md: -------------------------------------------------------------------------------- 1 | #二分法查找 2 | 3 | ## 原理 4 | * 对于有序数列,我们不断比较所查找值和中间值的关系,然后不断缩小查找范围。 5 | * 最典型的递归调用 6 | 7 | ```Java 8 | public class BinarySearchReview { 9 | public static int binarySearch(int[] nums, int n){ 10 | return binarySearch(nums, n, 0, nums.length - 1); 11 | } 12 | private static int binarySearch(int[] nums, int n, int low, int high){ 13 | if(low > high) return -1; 14 | int mid = (low + high) / 2; 15 | if(nums[mid] == n) return mid; 16 | else if(nums[mid] > n) 17 | return binarySearch(nums, n, low, mid - 1); 18 | else 19 | return binarySearch(nums, n, mid + 1, high); 20 | } 21 | public static void main(String[] args) { 22 | int[] a = {0, 1,2,3,4,5,6,7,8,9}; 23 | System.out.println(binarySearch(a, 5)); 24 | } 25 | } 26 | ``` -------------------------------------------------------------------------------- /DataStructrue/Sort/CountSort.md: -------------------------------------------------------------------------------- 1 | # 计数排序 2 | #### 计数排序方法 3 | 1. 先找出数组的最大值max,我们创建一个最大值max + 1长度的数组用于记录所有的数组出现的次数。 4 | 2. 因为生成的bucket是按序递增的,我们根据bucket重新填满我们的数组。 5 | 6 | #### 技术排序分析 7 | 技术排序可以使用额外的内存空间,所以思考上就会简单很多。总体的效率是Ο(n+k),k是整数的范围。 8 | 1. 举例: 7,6,3,1,3,其中最大值为7,我们建造一个大小为8的数组(即为max + 1)。 9 | 2. 我们遍历需要排序的数组,可以得到: 10 | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | |---|---|---|---|---|---|---|---| 12 | | 0 | 1 | 0 | 2 | 0 | 0 | 1 | 1 | 13 | 3. 其中上排是数字,下排是数字对应出现的次数。 14 | 4. 至此,我们可以遍历这个数组的每一个位置,然后将index填充到新的数组中。实现排序 15 | 16 | #### 代码 17 | ```Java 18 | package ca.mcmaster.chapter.two.Sort; 19 | 20 | public class CountSort { 21 | private static void sort(int[] nums){ 22 | int max = Integer.MIN_VALUE; 23 | for(int num : nums) 24 | max = Math.max(max, num); 25 | int[] bucket = new int[max+1]; 26 | for(int i = 0; i < nums.length; i++) 27 | bucket[nums[i]]++; 28 | for(int i = 0, j = 0; j < bucket.length; j++){ 29 | while(bucket[j]-- > 0) 30 | nums[i++] = j; 31 | } 32 | } 33 | public static void main(String[] args) { 34 | int[] arr = new int[]{1,4,5,3,2,5,7}; 35 | sort(arr); 36 | for(int i : arr) 37 | System.out.print(i + " "); 38 | System.out.println(); 39 | } 40 | } 41 | ``` -------------------------------------------------------------------------------- /DataStructrue/Sort/InsertionSort.md: -------------------------------------------------------------------------------- 1 | # Insert Sort 2 | >算法复杂度仍然是O(n^2) 3 | >内外两次循环,外循环定位,内循环通过比较使外循环定位之前的元素均排序完成。 4 | 5 | ```Java 6 | public class InsertionSort implements Sort { 7 | @Override 8 | public void sort(Comparable[] a) { 9 | int size = a.length; 10 | for(int i = 0; i < size; i ++){ 11 | for(int j = i; j > 0 && Sort.less(a, j, j - 1); j--){ Sort.swap(a, j, j-1); } 12 | } 13 | } 14 | public static void main(String[] args) { 15 | Sort sort = new SelectionSort<>(); 16 | Integer[] a = {1, 2,1,4,2,6,234,65,23,5,2,657,2,546}; 17 | sort.sort(a); 18 | Sort.show(a); 19 | } 20 | } 21 | ``` 22 | * 结果 23 | 657 546 234 65 23 6 5 4 2 2 2 2 1 1 -------------------------------------------------------------------------------- /DataStructrue/Sort/MergeSort.md: -------------------------------------------------------------------------------- 1 | ## 并归排序 2 | #### 并归排序的原理 3 | * 当两个数组本身是有序的,我们通过并归排序后仍然是有序的。 4 | 5 | #### 原地并归 6 | * 在进行并归时,如果我们要为每次递归创建一个新的数组将会是很大的开销,所以我们在一开始初始化一个aux,其长度和我们要排序的数组一致。 7 | 8 | ```Java 9 | private static void merge(int[] nums, int lo, int mid, int hi){ 10 | for(int i = lo; i <= hi; i++) 11 | aux[i] = nums[i]; 12 | int i = lo, j = mid + 1; 13 | for(int k = lo; k <= hi; k++){ 14 | if(i > mid) nums[k] = aux[j++]; 15 | else if(j > hi) nums[k] = aux[i++]; 16 | else if(aux[i] <= aux[j]) nums[k] = aux[i++]; 17 | else nums[k] = aux[j++]; 18 | } 19 | } 20 | ``` 21 | 22 | #### 排序(自顶向下),利用了分治的思想 23 | ```Java 24 | public static void sort(int[] nums, int lo, int hi){ 25 | aux = new int[nums.length]; 26 | if(lo >= hi) return; 27 | int mid = (hi - lo) / 2 + lo; 28 | sort(nums, lo, mid); //将mid左侧的所有元素排序。 29 | sort(nums, mid + 1, hi); //将mid右侧的所有元素排序。 30 | merge(nums, lo, mid, hi); //此时左右已经是有序的了,我们在将左右并归起来。 31 | } 32 | ``` -------------------------------------------------------------------------------- /DataStructrue/Sort/QuickSort.md: -------------------------------------------------------------------------------- 1 | ## QuickSort 快速排序 2 | 快速排序较为稳定,时间复杂度为O(NLogN)。 3 | 4 | ### 实现逻辑 5 | 1. 找到一个pivot(基准点),用来比较大小。 6 | 2. 从左向右遍历,找到第一个大于pivot的元素。 7 | 3. 从右向左遍历,找到第一个小于pivot的元素。 8 | 4. 交换2和3中找到的两个元素。 9 | 4. 交换pivot和index的位置,保证左边的数都小于pivot,右边的数都大于pivot。 10 | 11 | ### 实现代码 12 | ```Java 13 | public void sortColors(int[] nums) { 14 | if(null == nums) return; 15 | quickSort(nums, 0, nums.length - 1); 16 | } 17 | private void quickSort(int[] nums, int low, int high){ 18 | if(low > high) return; 19 | int i = partition(nums, low, high); 20 | quickSort(nums, low, i - 1); //递归调用 21 | quickSort(nums, i + 1, high); 22 | } 23 | private int partition(int[] nums, int low, int high){ 24 | int i = low, j = high + 1; 25 | int cmp = nums[low]; 26 | while(true){ 27 | while(nums[++i] <= cmp) if(i == high) break; //找到第一个大于pivot的元素 28 | while(nums[--j] > cmp) if(j == low) break; //找到第一个小于pivot的元素 29 | if(i >= j) break; 30 | swap(nums, i, j); //交换这两个数字的位置。 31 | } 32 | swap(nums, low, j); //将pivot和index换位置,此时左边的的所有数都小于pivot,右边的数都大于pivot。 33 | return j; //返回当前的index位置。 34 | } 35 | private static void swap(int[] nums, int i, int j){ 36 | int temp = nums[i]; 37 | nums[i] = nums[j]; 38 | nums[j] = temp; 39 | } 40 | ``` 41 | -------------------------------------------------------------------------------- /DataStructrue/Sort/SelectionSort.md: -------------------------------------------------------------------------------- 1 | # Selection Sort(Bubble Sort) 2 | 3 | >非常简单的一种排序方法,算法复杂度为O(n^2). 4 | >第一层遍历确定了某个位置,第二层遍历从其后的元素中找到最大(最小)的元素放在该位置。 5 | ```Java 6 | public class SelectionSort implements Sort { 7 | @Override 8 | public void sort(Comparable[] a) { 9 | int len = a.length; 10 | for(int i = 0; i < len; i++){ 11 | for(int j = i; j < len; j++){ 12 | if(Sort.less(a, i, j)){ Sort.swap(a, i, j); } 13 | } 14 | } 15 | } 16 | public static void main(String[] args) { 17 | Sort sort = new SelectionSort<>(); 18 | Integer[] a = {1, 2,1,4,2,6,234,65,23,5,2,657,2,546}; 19 | sort.sort(a); 20 | Sort.show(a); 21 | } 22 | } 23 | ``` 24 | * 结果 25 | >657 546 234 65 23 6 5 4 2 2 2 2 1 1 26 | -------------------------------------------------------------------------------- /DataStructrue/Sort/Sort.md: -------------------------------------------------------------------------------- 1 | # Sort 排序 2 | >一般排序所用的元素都会实现Comparable进行比较大小以确定先后顺序。 3 | >定义一个排序接口实现了交换元素,显示元素和比较大小等方法。 4 | ```Java 5 | public interface Sort { 6 | /** 7 | * @Description: Sort the array in a descent order. 8 | * @param a: array to sort 9 | */ 10 | public void sort(Comparable[] a); 11 | @SuppressWarnings("unchecked") 12 | static boolean less(Comparable[] a, int i, int j){ 13 | return a[i].compareTo((T)a[j]) < 0; 14 | } 15 | static void swap(Comparable[] a, int i, int j){ 16 | Comparable temp = a[i]; 17 | a[i] = a[j]; 18 | a[j] = temp; 19 | } 20 | static void show(Comparable[] a){ 21 | StringBuilder sb = new StringBuilder(); 22 | for(int i = 0; i < a.length; i++) 23 | sb.append(a[i] + " "); 24 | System.out.println(sb.toString()); 25 | } 26 | } 27 | ``` -------------------------------------------------------------------------------- /DataStructrue/String/kmp.md: -------------------------------------------------------------------------------- 1 | # KMP 2 | 3 | ### Introduction 4 | KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是实现一个next()函数,函数本身包含了模式串的局部匹配信息。时间复杂度O(m+n)。 5 | 6 | ### 理解 7 | 1. next数组的含义:表示了匹配串的最长前缀的位置 8 | * abcjkdabc的最长相同前后缀是abc,这意味着在最后一个字符处出现了不匹配可以直接从j处开始新的匹配。 9 | * 这样就能避免很多的重复匹配。 10 | 11 | ### 实现 12 | ```Java 13 | package ca.mcmaster.chapter.five.string; 14 | 15 | public class Kmp { 16 | private static int[] getNext(String pattern){ 17 | char[] arr = pattern.toCharArray(); 18 | int len = pattern.length(); 19 | int[] next = new int[len]; 20 | next[0] = -1; 21 | for(int i = 1, j = -1; i < len; i++){ 22 | while(j > -1 && arr[j + 1] != arr[i]){ 23 | j = next[j]; 24 | } 25 | if(arr[i] == arr[j + 1]) j++; 26 | next[i] = j; 27 | } 28 | return next; 29 | } 30 | public static int kmp(String text, String pattern){ 31 | int[] next = getNext(pattern); 32 | char[] tArr = text.toCharArray(); 33 | char[] pArr = pattern.toCharArray(); 34 | int tLen = text.length(); 35 | int pLen = pattern.length(); 36 | int j = -1; 37 | for(int i = 0; i < tLen; i++){ 38 | while(j > -1 && tArr[i] != pArr[j + 1]){ 39 | j = next[j]; 40 | } 41 | if(tArr[i] == pArr[j + 1]) j++; 42 | if(j == pLen - 1) return i - pLen + 1; 43 | } 44 | return -1; 45 | } 46 | public static void main(String[] args) { 47 | String a = "ababaca"; 48 | System.out.println(kmp("bacbababadababacambabacaddababacasdsd", a)); 49 | } 50 | } 51 | ``` -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/MyQueue.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.Stack; 4 | 5 | public class MyQueue { 6 | private Stack stack1; 7 | private Stack stack2; 8 | public MyQueue() { 9 | stack1 = new Stack<>(); 10 | stack2 = new Stack<>(); 11 | } 12 | public void offer(E e){ 13 | stack1.add(e); 14 | } 15 | public E poll(){ 16 | while(!stack1.isEmpty()){ 17 | stack2.push(stack1.pop()); 18 | } 19 | E result = stack2.pop(); 20 | while(!stack2.isEmpty()){ 21 | stack1.push(stack2.pop()); 22 | } 23 | return result; 24 | } 25 | public static void main(String[] args) { 26 | MyQueue queue = new MyQueue<>(); 27 | for(int i = 0; i < 10; i++) 28 | queue.offer(i); 29 | for (int i = 0; i < 10; i++) 30 | System.out.println(queue.poll()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question1_1.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class Question1_1 { 7 | public static boolean isDuplicateString(String str){ 8 | int length = str.length(); 9 | Set set = new HashSet(); 10 | for(int i=0; i < length; i++){ 11 | char c = str.charAt(i); 12 | if(!set.contains(c)) 13 | set.add(c); 14 | else 15 | return false; 16 | } 17 | return true; 18 | } 19 | public static void main(String[] args) { 20 | System.out.println(isDuplicateString("12142fsafdhsajkfhldsa")); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question1_2.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question1_2 { 4 | public static String reverseString(String str){ 5 | char[] arr = str.toCharArray(); 6 | int len = str.length(); 7 | int low = 0; 8 | int high = len - 1; 9 | while(low < high){ 10 | char temp = arr[low]; 11 | arr[low] = arr[high]; 12 | arr[high] = temp; 13 | low++; high--; 14 | } 15 | return new String(arr); 16 | } 17 | 18 | public static void main(String[] args) { 19 | System.out.println(reverseString("12345")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question1_3.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Question1_3 { 6 | public static boolean canBecome(String a, String b){ 7 | char[] aArr = a.toCharArray(); 8 | char[] bArr = b.toCharArray(); 9 | Arrays.sort(aArr); 10 | Arrays.sort(bArr); 11 | return new String(aArr).equals(new String(bArr)); 12 | } 13 | public static void main(String[] args) { 14 | System.out.println(canBecome("apple", "plaep")); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question1_4.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question1_4 { 4 | public static String replaceWhiteSpace(char[] s, int length){ 5 | StringBuilder sb = new StringBuilder(); 6 | for(int i = 0; i < length; i++){ 7 | if(s[i] == ' ') 8 | sb.append("%20"); 9 | else 10 | sb.append(s[i]); 11 | } 12 | return sb.toString(); 13 | } 14 | public static void main(String[] args) { 15 | String test = " adf sdf123 24"; 16 | System.out.println(replaceWhiteSpace(test.toCharArray(), test.length())); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question1_5.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question1_5 { 4 | public static String compress(String str){ 5 | int len = str.length(); 6 | char prev = str.charAt(0); 7 | int count = 1; 8 | StringBuilder sb = new StringBuilder(); 9 | sb.append(prev); 10 | for(int i = 1; i < len; i++){ 11 | if(str.charAt(i) != prev){ 12 | sb.append(count); 13 | prev = str.charAt(i); 14 | sb.append(prev); 15 | count = 1; 16 | }else 17 | count++; 18 | } 19 | sb.append(count); 20 | return sb.toString(); 21 | } 22 | public static void main(String[] args) { 23 | System.out.println(compress("aaaaadfsssscssd")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question1_6.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question1_6 { 4 | public static int[][] rotate(int m[][], int n){ 5 | for(int layer = 0; layer < n/2; layer++){ 6 | int first = layer; 7 | int last = n - 1 - layer; 8 | for(int i = first; i < last; i++){ 9 | int offset = i - first; 10 | int top = m[first][i]; 11 | m[first][i] = m[last-offset][first]; 12 | m[last-offset][first] = m[last][last-offset]; 13 | m[last][last-offset] = m[i][last]; 14 | m[i][last] = top; 15 | } 16 | } 17 | return m; 18 | } 19 | public static void main(String[] args) { 20 | int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 21 | a = rotate(a, 3); 22 | for(int i = 0; i < 3; i++){ 23 | for(int j = 0; j <3; j++) 24 | System.out.print(a[i][j] + " "); 25 | System.out.println(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question1_8.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question1_8 { 4 | public static boolean isSubstring(String s1, String s2){ 5 | if(s1.contains(s2)) 6 | return true; 7 | return false; 8 | } 9 | public static boolean isRotation(String s1, String s2){ 10 | if(s1.length() != s2.length()) 11 | return false; 12 | String doubleString = s1 + s1; 13 | if(isSubstring(doubleString, s2)) 14 | return true; 15 | return false; 16 | } 17 | public static void main(String[] args) { 18 | System.out.println(isRotation("waterbottle", "terbottlewa")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question2_6.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question2_6 { 4 | public static OfferList.ListNode isBegining(OfferList.ListNode dummy){ 5 | OfferList.ListNode slow = dummy.next.next; 6 | OfferList.ListNode fast = dummy.next.next; 7 | while(slow != fast){ 8 | slow = slow.next; 9 | fast = fast.next.next; 10 | } 11 | if(fast == null) 12 | return null; 13 | OfferList.ListNode beginning = dummy.next; 14 | while(beginning != fast){ 15 | beginning = beginning.next; 16 | fast = fast.next; 17 | } 18 | return beginning; 19 | } 20 | public static void main(String[] args) { 21 | OfferList.ListNode dummy = new OfferList().new ListNode(null); 22 | OfferList.ListNode head = dummy; 23 | OfferList.ListNode begin = null; 24 | for(int i = 0; i < 20; i++){ 25 | OfferList.ListNode temp = new OfferList().new ListNode(i); 26 | begin = temp; 27 | dummy.next = temp; 28 | dummy = dummy.next; 29 | } 30 | System.out.println(begin.value); 31 | for(int i = 20; i <40; i++){ 32 | OfferList.ListNode temp = new OfferList().new ListNode(i); 33 | dummy.next = temp; 34 | dummy = dummy.next; 35 | } 36 | dummy.next = begin; 37 | System.out.println(isBegining(head).value); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question3_4.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.Stack; 4 | 5 | public class Question3_4 { 6 | private static class Tower{ 7 | private Stack disks; 8 | private int index; 9 | public Tower(int index){ 10 | this.index = index; 11 | disks = new Stack<>(); 12 | } 13 | public int getIndex(){ 14 | return this.index; 15 | } 16 | public void add(int v){ 17 | if(!disks.isEmpty() && disks.peek() < v) throw new RuntimeException("Error putting disk!"); 18 | else { 19 | disks.push(v); 20 | } 21 | } 22 | public void moveTopTo(Tower t){ 23 | int top = disks.pop(); 24 | t.add(top); 25 | } 26 | public void moveDisks(int n, Tower destination, Tower buffer){ 27 | if(n > 0){ 28 | moveDisks(n - 1, buffer, destination); 29 | moveTopTo(destination); 30 | buffer.moveDisks(n - 1, destination, this); 31 | } 32 | } 33 | } 34 | public static void main(String[] args) { 35 | Tower[] towers = new Tower[3]; 36 | for(int i = 0; i < 3; i++) 37 | towers[i] = new Tower(i); 38 | for(int i = 10; i >= 0; i--) 39 | towers[0].add(i); 40 | towers[0].moveDisks(11, towers[2], towers[1]); 41 | for(int i = 0; i < 11; i++){ 42 | System.out.println(towers[2].disks.pop()); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question3_6.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.Stack; 4 | 5 | public class Question3_6 { 6 | public static Stack sortStack(Stack stack){ 7 | Stack result = new Stack<>(); 8 | Integer tmp = null; 9 | while(!stack.isEmpty()){ 10 | tmp = stack.pop(); 11 | while(!result.isEmpty() && result.peek() > tmp) 12 | stack.push(result.pop()); 13 | result.push(tmp); 14 | } 15 | return result; 16 | } 17 | 18 | public static void main(String[] args) { 19 | Stack stack = new Stack(); 20 | stack.push(2); 21 | stack.push(3); 22 | stack.push(1); 23 | stack.push(3); 24 | stack.push(2); 25 | stack.push(6); 26 | stack.push(7); 27 | stack.push(4); 28 | stack.push(3); 29 | stack.push(2); 30 | Stack sortStack = sortStack(stack); 31 | while(!sortStack.isEmpty()){ 32 | System.out.println(sortStack.pop()); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_2.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class Question4_2 { 6 | public static void main(String[] args) { 7 | OfferGraph graph = new OfferGraph(); 8 | OfferGraph.GraphVertex v1 = graph.new GraphVertex(1, new LinkedList()); 9 | OfferGraph.GraphVertex v2 = graph.new GraphVertex(2, new LinkedList()); 10 | OfferGraph.GraphVertex v3 = graph.new GraphVertex(3, new LinkedList()); 11 | OfferGraph.GraphVertex v4 = graph.new GraphVertex(4, new LinkedList()); 12 | OfferGraph.GraphVertex v5 = graph.new GraphVertex(5, new LinkedList()); 13 | OfferGraph.GraphVertex v6 = graph.new GraphVertex(6, new LinkedList()); 14 | OfferGraph.GraphVertex v7 = graph.new GraphVertex(7, new LinkedList()); 15 | OfferGraph.GraphVertex v8 = graph.new GraphVertex(8, new LinkedList()); 16 | OfferGraph.connect(v1, v6); 17 | OfferGraph.connect(v1, v5); 18 | OfferGraph.connect(v5, v7); 19 | OfferGraph.connect(v7, v6); 20 | OfferGraph.connect(v8, v6); 21 | OfferGraph.connect(v8, v3); 22 | OfferGraph.connect(v2, v8); 23 | OfferGraph.connect(v3, v2); 24 | OfferGraph.connect(v8, v4); 25 | OfferGraph.connect(v2, v4); 26 | System.out.println(v4.isConnectBFS(v8)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_3.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import ca.mcmaster.offer.OfferTree.TreeNode; 4 | 5 | public class Question4_3 { 6 | public static void main(String[] args) { 7 | Integer[] arr = new Integer[100]; 8 | for(int i = 0; i < 100; i++) 9 | arr[i] = i; 10 | TreeNode root = OfferTree.arrToTree(arr, 0, arr.length - 1); 11 | System.out.println(root.v); 12 | System.out.println(root.left.v); 13 | System.out.println(root.right.v); 14 | System.out.println(root.left.left.v); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_4.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import ca.mcmaster.offer.OfferTree.TreeNode; 7 | 8 | public class Question4_4 { 9 | public static void main(String[] args) { 10 | Integer[] arr = new Integer[100]; 11 | for(int i = 0; i < 100; i++) 12 | arr[i] = i; 13 | TreeNode root = OfferTree.arrToTree(arr, 0, arr.length - 1); 14 | List> lists = OfferTree.createLevelList(root); 15 | for(LinkedList list : lists){ 16 | for(TreeNode n : list){ 17 | System.out.print(n.v + " "); 18 | } 19 | System.out.println(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_5.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import ca.mcmaster.offer.OfferTree.TreeNode; 4 | 5 | public class Question4_5 { 6 | public static void main(String[] args) { 7 | TreeNode root = new TreeNode(5); 8 | TreeNode node1 = new TreeNode(3); 9 | TreeNode node2 = new TreeNode(1); 10 | TreeNode node3 = new TreeNode(10); 11 | TreeNode node4 = new TreeNode(7); 12 | TreeNode node5 = new TreeNode(12); 13 | TreeNode node6 = new TreeNode(11); 14 | root.left = node1; 15 | root.right = node3; 16 | node1.left = node2; 17 | node3.left = node4; 18 | node3.right = node5; 19 | // node5.right = node6; 20 | System.out.println(OfferTree.checkBSTDFS(root)); 21 | System.out.println(OfferTree.checkBSTBFS(root)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_6.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import ca.mcmaster.offer.OfferTree.TreeNode; 4 | 5 | public class Question4_6 { 6 | public static void main(String[] args) { 7 | TreeNode node50 = new TreeNode(50); 8 | TreeNode node40 = new TreeNode(40); 9 | TreeNode node30 = new TreeNode(30); 10 | TreeNode node45 = new TreeNode(45); 11 | TreeNode node44 = new TreeNode(44); 12 | TreeNode node46 = new TreeNode(46); 13 | TreeNode node60 = new TreeNode(60); 14 | TreeNode node55 = new TreeNode(55); 15 | TreeNode node65 = new TreeNode(65); 16 | node50.addLeftChild(node40); 17 | node40.addLeftChild(node30); 18 | node40.addRightChild(node45); 19 | node45.addLeftChild(node44); 20 | node45.addRightChild(node46); 21 | node50.addRightChild(node60); 22 | node60.addLeftChild(node55); 23 | node60.addRightChild(node65); 24 | System.out.println(OfferTree.getNextBST(node60).v); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_7.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import ca.mcmaster.offer.OfferTree.TreeNode; 4 | 5 | public class Question4_7 { 6 | public static void main(String[] args) { 7 | TreeNode node50 = new TreeNode(50); 8 | TreeNode node40 = new TreeNode(40); 9 | TreeNode node30 = new TreeNode(30); 10 | TreeNode node45 = new TreeNode(45); 11 | TreeNode node44 = new TreeNode(44); 12 | TreeNode node46 = new TreeNode(46); 13 | TreeNode node60 = new TreeNode(60); 14 | TreeNode node55 = new TreeNode(55); 15 | TreeNode node65 = new TreeNode(65); 16 | TreeNode node68 = new TreeNode(65); 17 | node50.addLeftChild(node40); 18 | node40.addLeftChild(node30); 19 | node40.addRightChild(node45); 20 | node45.addLeftChild(node44); 21 | node45.addRightChild(node46); 22 | node50.addRightChild(node60); 23 | node60.addLeftChild(node55); 24 | node60.addRightChild(node65); 25 | System.out.println(OfferTree.commonAncester(node50, node50, node65).v); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_8.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import ca.mcmaster.offer.OfferTree.TreeNode; 4 | 5 | public class Question4_8 { 6 | public static void main(String[] args) { 7 | TreeNode node50 = new TreeNode(50); 8 | TreeNode node40 = new TreeNode(40); 9 | TreeNode node30 = new TreeNode(30); 10 | TreeNode node45 = new TreeNode(45); 11 | TreeNode node44 = new TreeNode(44); 12 | TreeNode node46 = new TreeNode(46); 13 | TreeNode node60 = new TreeNode(60); 14 | TreeNode node55 = new TreeNode(55); 15 | TreeNode node65 = new TreeNode(65); 16 | node50.addLeftChild(node40); 17 | node40.addLeftChild(node30); 18 | node40.addRightChild(node45); 19 | node45.addLeftChild(node44); 20 | node45.addRightChild(node46); 21 | node50.addRightChild(node60); 22 | node60.addLeftChild(node55); 23 | node60.addRightChild(node65); 24 | System.out.println(OfferTree.isSubTree(node50, node60)); 25 | System.out.println(OfferTree.matchTree(node50, node50)); 26 | System.out.println(OfferTree.checkSubtree(node40, node45)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question4_9.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.List; 4 | 5 | import ca.mcmaster.offer.OfferTree.TreeNode; 6 | 7 | public class Question4_9 { 8 | public static void main(String[] args) throws CloneNotSupportedException { 9 | TreeNode node50 = new TreeNode(50); 10 | TreeNode node40 = new TreeNode(40); 11 | TreeNode node30 = new TreeNode(30); 12 | TreeNode node45 = new TreeNode(45); 13 | TreeNode node44 = new TreeNode(44); 14 | TreeNode node46 = new TreeNode(46); 15 | TreeNode node60 = new TreeNode(60); 16 | TreeNode node55 = new TreeNode(55); 17 | TreeNode node65 = new TreeNode(65); 18 | TreeNode node68 = new TreeNode(65); 19 | node50.addLeftChild(node40); 20 | node40.addLeftChild(node30); 21 | node40.addRightChild(node45); 22 | node45.addLeftChild(node44); 23 | node45.addRightChild(node46); 24 | node50.addRightChild(node60); 25 | node60.addLeftChild(node55); 26 | node60.addRightChild(node65); 27 | List result = OfferTree.getPathWithCount(node50, 120); 28 | for(PathResult pr : result){ 29 | for(TreeNode n : pr.path) 30 | System.out.print(n.v + " "); 31 | System.out.println(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question5_1.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question5_1 { 4 | public static int update(int m, int n, int j, int i){ 5 | int allOnes = ~0; 6 | int left = allOnes << (j + 1); 7 | int right = ~(allOnes << i); 8 | int mask = left | right; 9 | int clearM = m & mask; 10 | int movedN = n << i; 11 | return clearM | movedN; 12 | } 13 | public static void main(String[] args) { 14 | System.out.println(Integer.toBinaryString(update(0B10000000000, 0B10011, 6, 2))); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question5_2.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question5_2 { 4 | public static String doubleToString(double d){ 5 | if(d <= 0 || d >= 1) return "ERROR"; 6 | StringBuilder binary = new StringBuilder(); 7 | int counter = 0; 8 | binary.append('.'); 9 | while(d != 0){ 10 | counter++; 11 | if(counter > 32) return "ERROR"; 12 | int append = d * 2 >= 1 ? 1:0; 13 | binary.append(append); 14 | d = d * 2 - append; 15 | } 16 | return binary.toString(); 17 | } 18 | public static void main(String[] args) { 19 | System.out.println(doubleToString(0.525d)); 20 | System.out.println(Float.toHexString(0.25f)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question5_3.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question5_3 { 4 | public static int getClosestBigger(int n){ 5 | int c = n; 6 | int p = 0; 7 | int q = 0; 8 | while(c != 0 && ((c & 1) == 0)){ 9 | q++; 10 | c >>= 1; 11 | } 12 | p = q; 13 | while((c & 1) == 1){ 14 | p ++; 15 | c >>= 1; 16 | } 17 | if(p >= 31) return -1; 18 | n |= (1 << p); 19 | n &= ~((1 << p) - 1); 20 | n |= (1 << (p - q - 1)) - 1; 21 | return n; 22 | } 23 | public static int getClosestSmall(int n){ 24 | int c = n; 25 | int p = 0; 26 | int q = 0; 27 | while((c & 1) == 1){ 28 | q ++; 29 | c >>= 1; 30 | } 31 | p = q; 32 | while(c != 0 && (c & 1) == 0){ 33 | p ++; 34 | c >>= 1; 35 | } 36 | n &= ~((1 << (p + 1)) - 1); 37 | System.out.println(Integer.toBinaryString(~((1 << (p - q)) - 1))); 38 | int mask = ((1 << p) - 1) & ~((1 << (p - q - 1)) - 1); 39 | n |= mask; 40 | return n; 41 | } 42 | public static void main(String[] args) { 43 | // System.out.println(getClosestBigger(Integer.MAX_VALUE)); 44 | System.out.println(getClosestSmall(11)); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question5_5.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question5_5 { 4 | public static int bitNeedSwap(int a, int b){ 5 | int c = a ^ b; 6 | int count = 0; 7 | while(c != 0){ 8 | count = (c & 1) == 1 ? count+1:count; 9 | c >>= 1; 10 | } 11 | return count; 12 | } 13 | public static int bitNeedSwap1(int a, int b){ 14 | int count = 0; 15 | int c = a ^ b; 16 | while(c != 0){ 17 | c &= (c - 1); 18 | count ++; 19 | } 20 | return count; 21 | } 22 | public static void main(String[] args) { 23 | System.out.println(bitNeedSwap1(0b1001101011, 0b1010100111)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question5_6.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question5_6 { 4 | public static int swapEvenOdd(int n){ 5 | return (((n & 0xAAAAAAAA) << 1) | ((n & 0x55555555) >> 1)); 6 | } 7 | public static void main(String[] args) { 8 | System.out.println(Integer.toBinaryString(swapEvenOdd(0B101010101010101))); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_1.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question9_1 { 4 | public static int countWays(int n){ 5 | if(n < 0) 6 | return 0; 7 | else if (n == 0) 8 | return 1; 9 | else{ 10 | return countWays(n - 1) + countWays(n - 2) + countWays(n - 3); 11 | } 12 | } 13 | public static int countWaysDP(int n){ 14 | int[] dp = new int[n + 1]; 15 | for(int i = 0; i < n + 1; i++) 16 | dp[i] = -1; 17 | return countWaysDP(n, dp); 18 | } 19 | public static int countWaysDP(int n, int[] dp){ 20 | if(n < 0) 21 | return 0; 22 | else if(n == 0){ 23 | return 1; 24 | }else if(dp[n] != -1){ 25 | return dp[n]; 26 | }else{ 27 | dp[n] = countWaysDP(n - 1, dp) + countWaysDP(n - 2, dp) + countWaysDP(n - 3, dp); 28 | return dp[n]; 29 | } 30 | } 31 | public static void main(String[] args) { 32 | System.out.println(countWaysDP(3)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_10.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Question9_10 { 7 | public static class Box{ 8 | int w; 9 | int h; 10 | int d; 11 | public Box(int w, int h, int d){ 12 | this.w = w; 13 | this.h = h; 14 | this.d = d; 15 | } 16 | } 17 | public static void getPossibleOrders(Box[] box, Box bottom, ArrayList order, boolean[] used, List> result){ 18 | if(order.size() == box.length){ 19 | result.add(order); 20 | return; 21 | } 22 | for(int i = 0; i < used.length; i++){ 23 | if(!used[i]){ 24 | boolean[] cloneUsed = used.clone(); 25 | cloneUsed[i] = true; 26 | ArrayList copyBoxs = new ArrayList<>(); 27 | for(Box b : order) 28 | copyBoxs.add(b); 29 | if(copyBoxs.size() == 0 || canPutAbove(bottom, box[i])){ 30 | copyBoxs.add(box[i]); 31 | getPossibleOrders(box, box[i], copyBoxs, cloneUsed, result); 32 | }else{ 33 | result.add(order); 34 | return; 35 | } 36 | } 37 | } 38 | } 39 | private static boolean canPutAbove(Box b1, Box b2){ 40 | if(b1.w > b2.w && b1.h > b2.h && b1.d > b2.d) 41 | return true; 42 | return false; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_2.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Question9_2 { 7 | public static class Point{ 8 | int x; 9 | int y; 10 | public Point(int x, int y){ 11 | this.x = x; 12 | this.y = y; 13 | } 14 | public void print(){ 15 | System.out.println(x + " " + y); 16 | } 17 | } 18 | public static boolean getPath(int x, int y, List path){ 19 | Point p = new Point(x, y); 20 | path.add(p); 21 | if(x == 0 && y == 0) //已经在原点 22 | return true; 23 | boolean success = false; 24 | if(x > 0 && isFree(x - 1, y)){ //尝试向上移动 25 | success = getPath(x - 1, y, path); 26 | } 27 | if(!success && y > 0 && isFree(x, y - 1)){ 28 | success = getPath(x, y - 1, path); 29 | } 30 | if(!success) 31 | path.add(p); 32 | return success; 33 | } 34 | public static boolean isFree(int x, int y){ 35 | if(x == 2 && y == 3) 36 | return false; 37 | return true; 38 | } 39 | public static void main(String[] args) { 40 | List path = new ArrayList<>(); 41 | System.out.println(getPath(2, 3, path)); 42 | for(Point p : path) 43 | p.print(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_3.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question9_3 { 4 | public static int getMagic(int[] nums){ 5 | return getMagic(nums, 0, nums.length - 1); 6 | } 7 | public static int getMagic(int[] nums, int low, int high){ 8 | int mid = (high - low) / 2 + low; 9 | int midNum = nums[mid]; 10 | if(mid == midNum) 11 | return mid; 12 | if(midNum < mid){ 13 | return getMagic(nums, mid, high); 14 | }else{ 15 | return getMagic(nums, low, mid); 16 | } 17 | } 18 | public static void main(String[] args) { 19 | System.out.println(getMagic(new int[]{-10, -5, -1, 1, 2, 3, 4, 7, 9, 12, 13})); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_4.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | public class Question9_4 { 8 | public static List> getSubset(List set){ 9 | List> result = new ArrayList>(); 10 | getSubset(set, set.size(), result); 11 | return result; 12 | } 13 | public static void getSubset(List set, int index, List> result){ 14 | if(index < 0) return; 15 | if(index == 0){ 16 | ArrayList single = new ArrayList<>(); 17 | result.add(single); 18 | return; 19 | }else{ 20 | getSubset(set, index - 1, result); 21 | Integer current = set.get(index - 1); 22 | List> more = new ArrayList>(); 23 | for(ArrayList l : result){ 24 | ArrayList list = new ArrayList<>(); 25 | list.add(current); 26 | for(Integer i : l) 27 | list.add(i); 28 | more.add(list); 29 | } 30 | result.addAll(more); 31 | } 32 | } 33 | public static void main(String[] args) { 34 | List set = new LinkedList(); 35 | for(int i = 0; i < 3; i++){ 36 | set.add(i); 37 | } 38 | List> subset = getSubset(set); 39 | for(ArrayList list : subset){ 40 | for(Integer i : list) 41 | System.out.print(i + " "); 42 | System.out.println(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_5.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Question9_5 { 7 | public static List getPerm(String s){ 8 | List result = new ArrayList<>(); 9 | if(null == s) return result; 10 | getPerm(s, s.length(), result); 11 | return result; 12 | } 13 | public static void getPerm(String s, int index, List result){ 14 | if(index == 1){ 15 | result.add(s.substring(0, 1)); 16 | return; 17 | } 18 | else{ 19 | getPerm(s, index - 1, result); 20 | Character c = s.charAt(index - 1); 21 | List temp = new ArrayList<>(); 22 | for(String string : result){ 23 | temp.addAll(insertCharacter(string, c)); 24 | } 25 | result.clear(); 26 | result.addAll(temp); 27 | } 28 | } 29 | private static List insertCharacter(String s, Character c){ 30 | List result = new ArrayList<>(); 31 | int len = s.length(); 32 | for(int i = 0; i <= len; i++){ 33 | String first = s.substring(0, i); 34 | String second = s.substring(i, len); 35 | result.add(first + c + second); 36 | } 37 | return result; 38 | } 39 | public static void main(String[] args) { 40 | List perm = getPerm("abcd"); 41 | for(String s : perm) 42 | System.out.println(perm); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_7.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question9_7 { 4 | public enum Color{ 5 | RED, 6 | GREEN, 7 | BLUE 8 | } 9 | public static void fillColor(Color[][] screen, int x, int y, Color ncolor){ 10 | fillColor(screen, x, y, screen[x][y], ncolor); 11 | } 12 | public static void fillColor(Color[][] screen, int x, int y, Color ocolor, Color ncolor){ 13 | if(x < 0 || y < 0 || x >= screen[0].length || y >= screen.length){ 14 | return; 15 | }else{ 16 | if(ocolor == screen[y][x]){ 17 | screen[y][x] = ncolor; 18 | fillColor(screen, x - 1, y, ocolor, ncolor); //left 19 | fillColor(screen, x, y - 1, ocolor, ncolor); //up 20 | fillColor(screen, x + 1, y, ocolor, ncolor); //right 21 | fillColor(screen, x, y + 1, ocolor, ncolor); //down 22 | } 23 | } 24 | } 25 | public static void main(String[] args) { 26 | Color[][] screen = new Color[10][10]; 27 | // for(int i = 0; i < 10; i++){ 28 | // screen[3][i] = Color.BLUE; 29 | // } 30 | fillColor(screen, 8, 8, Color.GREEN); 31 | for(int i = 0; i < screen.length; i++){ 32 | for (int j = 0; j < screen[0].length; j++) { 33 | System.out.print(screen[i][j]); 34 | } 35 | System.out.println(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_8.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question9_8 { 4 | public static int getCountDP(int n, int[] dp){ 5 | if(n < 0) 6 | return 0; 7 | else if(n == 0) 8 | return 1; 9 | else if(dp[n] != 0){ 10 | return dp[n]; 11 | }else{ 12 | dp[n] = getCountDP(n - 25, dp) + getCountDP(n - 10, dp) + getCountDP(n - 5, dp) + getCountDP(n - 1, dp); 13 | return dp[n]; 14 | } 15 | } 16 | public static int getCountDP(int n){ 17 | int[] dp = new int[n + 1]; 18 | dp[0] = 0; 19 | return getCountDP(n, dp); 20 | } 21 | public static void main(String[] args) { 22 | System.out.println(getCountDP(5)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Offer/ca/mcmaster/offer/Question9_9.java: -------------------------------------------------------------------------------- 1 | package ca.mcmaster.offer; 2 | 3 | public class Question9_9 { 4 | public static int count = 0; 5 | public static void eightQueue(int[][] dp, int row){ //dp[]: index: row; value = column 6 | if(row == 8){ 7 | System.out.println("Number: " + ++count); 8 | for(int i = 0; i < 8; i++){ 9 | for(int j = 0; j < 8; j++){ 10 | System.out.print(dp[i][j] + " "); 11 | } 12 | System.out.println(); 13 | } 14 | return; 15 | } 16 | int [][] clone = dp.clone(); 17 | for(int i = 0 ; i < 8; i++){ 18 | clone[row][i] = 1; 19 | if(isSafe(clone, row, i)) 20 | eightQueue(clone, row + 1); 21 | clone[row][i] = 0; 22 | } 23 | } 24 | private static boolean isSafe(int[][] dp, int row, int column){ 25 | if(row >= 1){ 26 | for(int i = row - 1; i >=0; i--) 27 | if(dp[i][column] == 1) return false; 28 | } 29 | int tempRow = row; 30 | int tempColumn = column; 31 | while(tempRow > 0 && tempColumn > 0){ //left up 32 | if(dp[--tempRow][--tempColumn] == 1) return false; 33 | } 34 | tempRow = row; 35 | tempColumn = column; 36 | while(tempRow > 0 && tempColumn < 7){ 37 | if(dp[--tempRow][++tempColumn] == 1) return false; 38 | } 39 | return true; 40 | } 41 | public static void main(String[] args) { 42 | int[][] dp = new int[8][8]; 43 | eightQueue(dp, 0); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /leetcode/1.Two Sum.md: -------------------------------------------------------------------------------- 1 | ## 1.Two Sum 2 | ### Thinking: 3 | * Method1: Search 4 | We need to find if (target - current) is in the set, if not, add current to a hashSet for checking. 5 | Since to need to return the index according to value, so the key is value of number and value is index of number in array. 6 | ```Java 7 | class Solution { 8 | public int[] twoSum(int[] nums, int target) { 9 | Map map = new HashMap<>(); 10 | int numLength = nums.length; 11 | for(int i = 0; i < numLength; i++){ 12 | if(!map.containsKey(target - nums[i])){ 13 | map.put(nums[i], i); 14 | }else{ 15 | return new int[]{i, map.get(target - nums[i])}; 16 | } 17 | } 18 | return null; 19 | } 20 | } 21 | ``` 22 | 23 | ### 二刷 24 | 1. 二刷的时候仍然想到用hash表解决该问题。键存的是数字的值,值存的是index。 25 | 2. 在遍历的时候,我们同时检查target - nums[i]是否存在。 26 | * 如果不存在,我们将数值加入哈希表。 27 | * 如果存在,我们直接返回index。 28 | 29 | ```Java 30 | class Solution { 31 | public int[] twoSum(int[] nums, int target) { 32 | Map map = new HashMap<>(); 33 | for(int i = 0; i < nums.length; i++){ 34 | if(!map.containsKey(target - nums[i])) 35 | map.put(nums[i], i); 36 | else 37 | return new int[]{i, map.get(target - nums[i])}; 38 | } 39 | return null; 40 | } 41 | } 42 | ``` -------------------------------------------------------------------------------- /leetcode/125. Valid Palindrome.md: -------------------------------------------------------------------------------- 1 | ## 125. Valid Palindrome 2 | 3 | ### Question: 4 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | 6 | Note: For the purpose of this problem, we define empty string as valid palindrome. 7 | 8 | ``` 9 | Example 1: 10 | 11 | Input: "A man, a plan, a canal: Panama" 12 | Output: true 13 | 14 | Example 2: 15 | 16 | Input: "race a car" 17 | Output: false 18 | ``` 19 | 20 | ### 二刷 21 | ```Java 22 | class Solution { 23 | public boolean isPalindrome(String s) { 24 | if(s == null) return false; 25 | s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); 26 | int len = s.length(); 27 | if(len == 0) return true; 28 | int head = 0, end = s.length() - 1; 29 | char[] arr = s.toCharArray(); 30 | while(head < end){ 31 | while(!isAlphanumeric(arr[head])){ 32 | if(head + 1 >= len) return true; 33 | head++; 34 | } 35 | while(!isAlphanumeric(arr[end])){ 36 | if(end - 1 < 0) return true; 37 | end--; 38 | } 39 | if(head > end) return true; 40 | if(arr[head++] != arr[end--]) return false; 41 | } 42 | return true; 43 | } 44 | public boolean isAlphanumeric(char c) { 45 | if ((c >=48 && c <=57) || (c >= 97 && c <= 122)) return true; 46 | return false; 47 | } 48 | } 49 | ``` 50 | -------------------------------------------------------------------------------- /leetcode/13. Roman to Integer.md: -------------------------------------------------------------------------------- 1 | ## 13. Roman to Integer 2 | ### Thinking: 3 | * Method1: 4 | 1. If not exceed the length of string, check if two characters are included in the map, if so, add its represented integer value. Otherwise add the value of one character. 5 | ```Java 6 | class Solution { 7 | public int romanToInt(String s) { 8 | int result = 0; 9 | String[] roman = {"M", "CM","D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 10 | int[] n = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 11 | Map m = new HashMap<>(); 12 | for(int i = 0; i < n.length; i++){ 13 | m.put(roman[i], n[i]); 14 | } 15 | int len = s.length(); 16 | int i = 0; 17 | while(i < len){ 18 | Integer temp = null; 19 | if(i+2 <= len){ 20 | temp = m.get(s.substring(i, i+2)); 21 | if(null != temp){ 22 | result += temp; 23 | i += 2; 24 | continue; 25 | }else{ 26 | result += m.get(s.substring(i, i+1)); 27 | i++; 28 | continue; 29 | } 30 | }else{ 31 | result += m.get(s.substring(i, i+1)); 32 | i ++; 33 | continue; 34 | } 35 | } 36 | return result; 37 | } 38 | } 39 | ``` -------------------------------------------------------------------------------- /leetcode/137. Single Number II.md: -------------------------------------------------------------------------------- 1 | ## 137. Single Number II 2 | 3 | ### Question 4 | Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 5 | 6 | Note: 7 | 8 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 9 | 10 | ```Java 11 | Example 1: 12 | 13 | Input: [2,2,3,2] 14 | Output: 3 15 | 16 | Example 2: 17 | 18 | Input: [0,1,0,1,0,1,99] 19 | Output: 99 20 | ``` 21 | 22 | ### Thinking: 23 | * Method 1:sort 24 | 25 | ```Java 26 | class Solution { 27 | public int singleNumber(int[] nums) { 28 | Arrays.sort(nums); 29 | if(nums.length > 1) 30 | if(nums[0] != nums[1]) return nums[0]; 31 | for(int i = 1; i < nums.length - 1; i++){ 32 | if(nums[i] != nums[i - 1] && nums[i] != nums[i + 1]) 33 | return nums[i]; 34 | } 35 | return nums[nums.length - 1]; 36 | } 37 | } 38 | ``` 39 | 40 | ### 二刷 41 | 1. 排序 42 | ```Java 43 | class Solution { 44 | public int singleNumber(int[] nums) { 45 | Arrays.sort(nums); 46 | if(nums.length > 1){ 47 | if(nums[0] != nums[1]) 48 | return nums[0]; 49 | } 50 | for(int i = 1; i < nums.length - 1; i++){ 51 | if(nums[i] != nums[i - 1] && nums[i] != nums[i + 1]) 52 | return nums[i]; 53 | } 54 | return nums[nums.length - 1]; 55 | } 56 | } 57 | ``` 58 | -------------------------------------------------------------------------------- /leetcode/151. Reverse Words in a String.md: -------------------------------------------------------------------------------- 1 | ## 151. Reverse Words in a String 2 | 3 | ### Question 4 | Given an input string, reverse the string word by word. 5 | 6 | ``` 7 | Example: 8 | 9 | Input: "the sky is blue", 10 | Output: "blue is sky the". 11 | 12 | ``` 13 | 14 | 15 | ### Thinking: 16 | * Method 17 | 18 | ```Java 19 | public class Solution { 20 | public String reverseWords(String s) { 21 | String[] tokens = s.trim().split(" +"); 22 | Collections.reverse(Arrays.asList(tokens)); 23 | return String.join(" ", tokens); 24 | } 25 | } 26 | ``` 27 | 28 | ### 二刷 29 | 1. 想到通过split函数实现。 30 | 2. 有很多corner case需要考虑,个人觉得有一些corner case存在的价值不大。 31 | 3. 相比一刷通过正则和String的reverse,这次的方法快了很多。 32 | ```Java 33 | public class Solution { 34 | public String reverseWords(String s) { 35 | if(s == null || s.length() == 0) return s; 36 | String[] arr = s.split(" "); 37 | int len = arr.length; 38 | if(len == 0) return ""; 39 | StringBuilder sb = new StringBuilder(); 40 | sb.append(arr[len - 1]); 41 | for(int i = len - 2; i >= 0; i--) 42 | if(arr[i].length() > 0) 43 | sb.append(" " + arr[i]); 44 | return sb.toString(); 45 | } 46 | } 47 | ``` -------------------------------------------------------------------------------- /leetcode/168. Excel Sheet Column Title.md: -------------------------------------------------------------------------------- 1 | ## 168. Excel Sheet Column Title 2 | 3 | ### Question 4 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 5 | 6 | ``` 7 | For example: 8 | 9 | 1 -> A 10 | 2 -> B 11 | 3 -> C 12 | ... 13 | 26 -> Z 14 | 27 -> AA 15 | 28 -> AB 16 | ... 17 | 18 | Example 1: 19 | 20 | Input: 1 21 | Output: "A" 22 | 23 | Example 2: 24 | 25 | Input: 28 26 | Output: "AB" 27 | 28 | Example 3: 29 | 30 | Input: 701 31 | Output: "ZY" 32 | ``` 33 | 34 | ### Thinking: 35 | ```Java 36 | class Solution { 37 | public String convertToTitle(int n) { 38 | if(n == 0) return ""; 39 | StringBuilder sb = new StringBuilder(); 40 | String map = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 41 | while(n != 0){ 42 | sb.append(map.charAt((n - 1) % 26)); 43 | n --; 44 | n /= 26; 45 | } 46 | return sb.reverse().toString(); 47 | } 48 | } 49 | ``` 50 | 51 | ### 二刷 52 | 1. 唯一恶心的就是都是从1开始计数,所以每次计算之前需要-1. 53 | ```Java 54 | class Solution { 55 | public String convertToTitle(int n) { 56 | StringBuilder sb = new StringBuilder(); 57 | while(n != 0){ 58 | n--; 59 | int remain = n % 26; 60 | sb.insert(0, (char)(remain + 'A')); 61 | n /= 26; 62 | } 63 | return sb.toString(); 64 | } 65 | } 66 | ``` -------------------------------------------------------------------------------- /leetcode/172. Factorial Trailing Zeroes.md: -------------------------------------------------------------------------------- 1 | ## 172. Factorial Trailing Zeroes 2 | 3 | ### Question 4 | Given an integer n, return the number of trailing zeroes in n!. 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: 3 10 | Output: 0 11 | Explanation: 3! = 6, no trailing zero. 12 | 13 | Example 2: 14 | 15 | Input: 5 16 | Output: 1 17 | Explanation: 5! = 120, one trailing zero. 18 | ``` 19 | 20 | ### Thinking: 21 | * Method: 22 | * n为5的倍数会出现0; 23 | * n为25的倍数会出现额外的0; 24 | * ... 25 | 26 | ```Java 27 | class Solution { 28 | public int trailingZeroes(int n) { 29 | int count = 0; 30 | while(n > 0){ 31 | count += n / 5; 32 | n /= 5; 33 | } 34 | return count; 35 | } 36 | } 37 | ``` 38 | 39 | ### 二刷 40 | ![Imgur](https://i.imgur.com/IBejjyd.jpg) 41 | ```Java 42 | class Solution { 43 | public int trailingZeroes(int n) { 44 | int result = 0; 45 | while(n > 4){ 46 | result += n / 5; 47 | n /= 5; 48 | } 49 | return result; 50 | } 51 | } 52 | ``` -------------------------------------------------------------------------------- /leetcode/178. Rank Scores.md: -------------------------------------------------------------------------------- 1 | ## 178. Rank Scores 2 | 3 | ### Question 4 | Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks. 5 | 6 | ``` 7 | +----+-------+ 8 | | Id | Score | 9 | +----+-------+ 10 | | 1 | 3.50 | 11 | | 2 | 3.65 | 12 | | 3 | 4.00 | 13 | | 4 | 3.85 | 14 | | 5 | 4.00 | 15 | | 6 | 3.65 | 16 | +----+-------+ 17 | ``` 18 | 19 | For example, given the above Scores table, your query should generate the following report (order by highest score): 20 | ``` 21 | +-------+------+ 22 | | Score | Rank | 23 | +-------+------+ 24 | | 4.00 | 1 | 25 | | 4.00 | 1 | 26 | | 3.85 | 2 | 27 | | 3.65 | 3 | 28 | | 3.65 | 3 | 29 | | 3.50 | 4 | 30 | +-------+------+ 31 | ``` 32 | 33 | ### 二刷: 34 | 1. 这道题的核心在于自己创建新的变量。 35 | 2. 这道题的还牵扯到SQL的优先级问题,我们单独拎出来@pre <> (@pre := Score)进行分析。 36 | 3. 实际上这行的执行顺序是从左往右,并没有将括号内的优先拉出来运算。 37 | ```SQL 38 | # Write your MySQL query statement below 39 | SELECT s.Score as Score, 40 | (@i:=@i+ (@pre <> (@pre := Score))) as Rank 41 | FROM Scores s, (select @i:=0, @pre:=-1) AS init 42 | ORDER BY s.Score DESC; 43 | ``` 44 | 45 | ### 引用 46 | 1. [MySQL中变量的用法——LeetCode 178. Rank Scores](http://www.cnblogs.com/rever/p/7149995.html) -------------------------------------------------------------------------------- /leetcode/180. Consecutive Numbers.md: -------------------------------------------------------------------------------- 1 | ## 180. Consecutive Numbers 2 | 3 | ### Question 4 | Write a SQL query to find all numbers that appear at least three times consecutively. 5 | 6 | ``` 7 | +----+-----+ 8 | | Id | Num | 9 | +----+-----+ 10 | | 1 | 1 | 11 | | 2 | 1 | 12 | | 3 | 1 | 13 | | 4 | 2 | 14 | | 5 | 1 | 15 | | 6 | 2 | 16 | | 7 | 2 | 17 | +----+-----+ 18 | 19 | For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times. 20 | 21 | +-----------------+ 22 | | ConsecutiveNums | 23 | +-----------------+ 24 | | 1 | 25 | +-----------------+ 26 | ``` 27 | 28 | ### 二刷 29 | 1. 实际上一张表完全可以和自身进行匹配。 30 | 2. 我们可以使用该表和自身进行匹配。 31 | ```SQL 32 | # Write your MySQL query statement below 33 | SELECT DISTINCT l1.Num as ConsecutiveNums 34 | FROM Logs l1, Logs l2, Logs l3 35 | WHERE l2.Id = l1.Id - 1 and l3.Id = l1.Id - 2 and l1.Num = l2.Num and l3.Num = l1.Num; 36 | ``` 37 | 38 | 1. 使用变量 39 | 2. 记得FROM以后一定是接着一张表, 所以即使是我们查找出来的表结构,我们也要使用AS字段将查找结果变成一张新的表结构。 40 | ```SQL 41 | # Write your MySQL query statement below 42 | SELECT DISTINCT Num AS ConsecutiveNums 43 | FROM ( 44 | SELECT Num, @count := IF(Num = @pre, @count + 1, 1) AS cc, @pre := Num 45 | FROM Logs, (SELECT @count := 0, @pre := -1) AS init 46 | ) AS t 47 | WHERE t.cc > 2; 48 | ``` 49 | 50 | ### 引用 51 | 1. [leetcode 180. Consecutive Numbers](https://blog.csdn.net/yuxin6866/article/details/52151962) -------------------------------------------------------------------------------- /leetcode/182. Duplicate Emails.md: -------------------------------------------------------------------------------- 1 | ## 181. Employees Earning More Than Their Managers 2 | 3 | ### Question 4 | Write a SQL query to find all duplicate emails in a table named Person. 5 | ``` 6 | +----+---------+ 7 | | Id | Email | 8 | +----+---------+ 9 | | 1 | a@b.com | 10 | | 2 | c@d.com | 11 | | 3 | a@b.com | 12 | +----+---------+ 13 | ``` 14 | 15 | For example, your query should return the following for the above table: 16 | ``` 17 | +---------+ 18 | | Email | 19 | +---------+ 20 | | a@b.com | 21 | +---------+ 22 | ``` 23 | 24 | Note: All emails are in lowercase. 25 | 26 | ### Thinking: 27 | * Method 28 | 29 | ```SQL 30 | # Write your MySQL query statement below 31 | select 32 | Email 33 | from 34 | Person 35 | group by 36 | Email 37 | having 38 | count(*) > 1 39 | ``` 40 | 41 | ### 二刷 42 | 1. 使用Email字段作为分组的类别,将count()作为聚合函数。 43 | ```SQL 44 | # Write your MySQL query statement below 45 | SELECT Email 46 | FROM Person 47 | GROUP BY Email 48 | HAVING count(*) > 1; 49 | ``` -------------------------------------------------------------------------------- /leetcode/183. Customers Who Never Order.md: -------------------------------------------------------------------------------- 1 | ## 183. Customers Who Never Order 2 | 3 | ### Question 4 | Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything. 5 | 6 | Table: Customers. 7 | 8 | +----+-------+ 9 | | Id | Name | 10 | +----+-------+ 11 | | 1 | Joe | 12 | | 2 | Henry | 13 | | 3 | Sam | 14 | | 4 | Max | 15 | +----+-------+ 16 | 17 | Table: Orders. 18 | 19 | +----+------------+ 20 | | Id | CustomerId | 21 | +----+------------+ 22 | | 1 | 3 | 23 | | 2 | 1 | 24 | +----+------------+ 25 | 26 | Using the above tables as example, return the following: 27 | 28 | +-----------+ 29 | | Customers | 30 | +-----------+ 31 | | Henry | 32 | | Max | 33 | +-----------+ 34 | 35 | ### Thinking: 36 | * Method 37 | 38 | ```SQL 39 | # Write your MySQL query statement below 40 | select 41 | Name as Customers 42 | from 43 | Customers 44 | where 45 | Id 46 | not in( 47 | select CustomerId from Orders 48 | ); 49 | ``` 50 | 51 | ### 二刷 52 | 1. 还是想到使用not in连接多次查询。 53 | ```MySQL 54 | # Write your MySQL query statement below 55 | SELECT c.Name as Customers 56 | FROM Customers c 57 | WHERE c.id not in ( 58 | SELECT o.CustomerId FROM Orders o 59 | ); 60 | ``` 61 | -------------------------------------------------------------------------------- /leetcode/186. Reverse Words in a String II.md: -------------------------------------------------------------------------------- 1 | ## 186. Reverse Words in a String II 2 | 3 | ### Question 4 | Given an input string , reverse the string word by word. 5 | 6 | ``` 7 | Example: 8 | 9 | Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] 10 | Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] 11 | ``` 12 | 13 | Note: 14 | * A word is defined as a sequence of non-space characters. 15 | * The input string does not contain leading or trailing spaces. 16 | * The words are always separated by a single space. 17 | 18 | Follow up: Could you do it in-place without allocating extra space? 19 | 20 | 21 | ### Solution 22 | * Method 1: String operation 23 | ```Java 24 | class Solution { 25 | public void reverseWords(char[] str) { 26 | String s = new String(str); 27 | String[] tokens = s.split(" "); 28 | int count = 0; 29 | for(int i = tokens.length - 1; i >= 0; i--){ 30 | for(char c : tokens[i].toCharArray()){ 31 | str[count++] = c; 32 | } 33 | if(count < str.length) 34 | str[count++] = ' '; 35 | } 36 | } 37 | } 38 | ``` 39 | -------------------------------------------------------------------------------- /leetcode/191. Number of 1 Bits.md: -------------------------------------------------------------------------------- 1 | ## 191. Number of 1 Bits 2 | 3 | ### Question 4 | Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: 11 10 | Output: 3 11 | Explanation: Integer 11 has binary representation 00000000000000000000000000001011 12 | 13 | Example 2: 14 | 15 | Input: 128 16 | Output: 1 17 | Explanation: Integer 128 has binary representation 00000000000000000000000010000000 18 | ``` 19 | 20 | ### Thinking: 21 | * Method: 22 | 23 | ```Java 24 | public class Solution { 25 | // you need to treat n as an unsigned value 26 | public int hammingWeight(int n) { 27 | int count = 0; 28 | for(int i = 0; i <= 31; i++){ 29 | count = ((n & 1) == 1)? count + 1: count; 30 | n >>>= 1; 31 | } 32 | return count; 33 | } 34 | } 35 | ``` 36 | 37 | ### 二刷 38 | ```Java 39 | public class Solution { 40 | // you need to treat n as an unsigned value 41 | public int hammingWeight(int n) { 42 | int count = 0; 43 | int cur = 1; 44 | for(int i = 0; i < 32; i++){ 45 | if((n & (1 << i)) != 0) 46 | count ++; 47 | } 48 | return count; 49 | } 50 | } 51 | ``` 52 | -------------------------------------------------------------------------------- /leetcode/201. Bitwise AND of Numbers Range.md: -------------------------------------------------------------------------------- 1 | ## 201. Bitwise AND of Numbers Range 2 | 3 | ### Question 4 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: [5,7] 10 | Output: 4 11 | 12 | Example 2: 13 | 14 | Input: [0,1] 15 | Output: 0 16 | ``` 17 | 18 | ### Thinking: 19 | * Method:这道题是求所有位的与,其中某一位出现过0则都为0 20 | * 11010  11011  11100  11101  11110 21 | * 实际上就是取最高位相同的位数。 22 | 23 | ```Java 24 | class Solution { 25 | public int rangeBitwiseAnd(int m, int n) { 26 | int mask = ~0; 27 | while(m != n){ 28 | mask <<= 1; 29 | m &= mask; 30 | n &= mask; 31 | } 32 | return m; 33 | } 34 | } 35 | ``` 36 | 37 | ### 二刷 38 | ```Java 39 | class Solution { 40 | public int rangeBitwiseAnd(int m, int n) { 41 | int mask = ~0; 42 | while(m != n){ 43 | m &= mask; 44 | n &= mask; 45 | mask <<= 1; 46 | } 47 | return m; 48 | } 49 | } 50 | ``` 51 | 52 | ### Reference 53 | 1.[[LeetCode] Bitwise AND of Numbers Range 数字范围位相与](https://www.cnblogs.com/grandyang/p/4431646.html) -------------------------------------------------------------------------------- /leetcode/217. Contains Duplicate.md: -------------------------------------------------------------------------------- 1 | ## 217. Contains Duplicate 2 | 3 | ### Question 4 | Given an array of integers, find if the array contains any duplicates. 5 | 6 | Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 7 | 8 | ``` 9 | Example 1: 10 | 11 | Input: [1,2,3,1] 12 | Output: true 13 | ``` 14 | 15 | ### Thinking: 16 | * Method: 17 | * 使用hashset.O(n) 18 | 19 | ```Java 20 | class Solution { 21 | public boolean containsDuplicate(int[] nums) { 22 | Set set = new HashSet<>(); 23 | for(int n : nums){ 24 | if(set.contains(n)) return true; 25 | set.add(n); 26 | } 27 | return false; 28 | } 29 | } 30 | ``` 31 | 32 | ### 二刷 33 | 1. Sort the array first and traverse the array from the second index. 34 | 2. check if current number equals the previous one, if equal, return true, else false; 35 | ```Java 36 | class Solution { 37 | public boolean containsDuplicate(int[] nums) { 38 | Arrays.sort(nums); 39 | for(int i = 1; i < nums.length; i++){ 40 | if(nums[i] == nums[i - 1]) return true; 41 | } 42 | return false; 43 | } 44 | } 45 | ``` -------------------------------------------------------------------------------- /leetcode/22. Generate Parentheses.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Seanforfun/Algorithm-and-Leetcode/4ea49415a05d1c6ed54a384841fa46f86c2810e2/leetcode/22. Generate Parentheses.md -------------------------------------------------------------------------------- /leetcode/223. Rectangle Area.md: -------------------------------------------------------------------------------- 1 | ## 223. Rectangle Area 2 | 3 | ### Question 4 | Find the total area covered by two rectilinear rectangles in a 2D plane. 5 | 6 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 7 | ![question](https://leetcode.com/static/images/problemset/rectangle_area.png) 8 | ``` 9 | Example: 10 | 11 | Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 12 | Output: 45 13 | 14 | ``` 15 | 16 | ### Thinking: 17 | * Method 1:两个长方形的面积和 - 交集的面积 18 | 19 | ```Java 20 | class Solution { 21 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 22 | int total = (C - A) * (D - B) + (G - E) * (H - F); 23 | if(E > C || G < A || F > D || H < B) return total; 24 | else{ 25 | int height = Math.min(H, D) - Math.max(B, F); 26 | int width = Math.min(G, C) - Math.max(A, E); 27 | return total - height * width; 28 | } 29 | } 30 | } 31 | ``` 32 | 33 | ### 二刷 34 | 1. 和一刷的想法一样,但是出了一个问题,两个长方形的相对位置是不确定的,所以我们要使用最大值,最小值来解决这个问题。 35 | ```Java 36 | class Solution { 37 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 38 | int total = (D - B) * (C - A) + (H - F) * (G - E); 39 | if(E >= C || G <= A || H <= B || F >= D) return total; 40 | return total - (Math.min(C, G) - Math.max(A, E)) * (Math.min(D, H) - Math.max(F, B)); 41 | } 42 | } 43 | ``` -------------------------------------------------------------------------------- /leetcode/258. Add Digits.md: -------------------------------------------------------------------------------- 1 | ## 258. Add Digits 2 | 3 | ### Question 4 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 5 | 6 | ``` 7 | Example: 8 | 9 | Input: 38 10 | Output: 2 11 | Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 12 | Since 2 has only one digit, return it. 13 | ``` 14 | 15 | ### Thinking: 16 | * Method 1:递归 17 | 18 | ```Java 19 | class Solution { 20 | public int addDigits(int num) { 21 | if(num < 10) return num; 22 | int sum = 0; 23 | while(num != 0){ 24 | sum += num % 10; 25 | num /= 10; 26 | } 27 | return addDigits(sum); 28 | } 29 | } 30 | ``` 31 | 32 | * Method 2: 33 | * 除了0以外,从0-9循环。 34 | 35 | ```Java 36 | class Solution { 37 | public int addDigits(int num) { 38 | return (num - 1)%9 + 1; 39 | } 40 | } 41 | ``` 42 | 43 | ### Second time 44 | 1. Recursion 45 | ```Java 46 | class Solution { 47 | public int addDigits(int num) { 48 | if(num <= 9) return num; 49 | int sum = 0; 50 | while(num > 0){ 51 | sum += num % 10; 52 | num /= 10; 53 | } 54 | return addDigits(sum); 55 | } 56 | } 57 | ``` 58 | -------------------------------------------------------------------------------- /leetcode/263. Ugly Number.md: -------------------------------------------------------------------------------- 1 | ## 263. Ugly Number 2 | 3 | ### Question 4 | Write a program to check whether a given number is an ugly number. 5 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 6 | 7 | ``` 8 | Example 1: 9 | 10 | Input: 6 11 | Output: true 12 | Explanation: 6 = 2 × 3 13 | 14 | Example 2: 15 | 16 | Input: 8 17 | Output: true 18 | Explanation: 8 = 2 × 2 × 2 19 | 20 | Example 3: 21 | 22 | Input: 14 23 | Output: false 24 | Explanation: 14 is not ugly since it includes another prime factor 7. 25 | ``` 26 | 27 | ### Thinking: 28 | * Method 1:递归 29 | 30 | ```Java 31 | class Solution { 32 | public boolean isUgly(int num) { 33 | if(num == 1) return true; 34 | if(num <= 0) return false; 35 | if(num == 2 || num == 5 || num == 3) return true; 36 | if(num % 2 == 0) return isUgly(num / 2); 37 | if(num % 3 == 0) return isUgly(num / 3); 38 | if(num % 5 == 0) return isUgly(num / 5); 39 | return false; 40 | } 41 | } 42 | ``` 43 | 44 | ### Second time 45 | 1. I still used the method of Recursion. 46 | ```Java 47 | class Solution { 48 | public boolean isUgly(int num) { 49 | if(num == 1) return true; 50 | if(num <= 0) return false; 51 | if(num % 2 == 0) return isUgly(num / 2); 52 | else if(num % 3 == 0) return isUgly(num / 3); 53 | else if(num % 5 == 0) return isUgly(num / 5); 54 | else return false; 55 | } 56 | } 57 | ``` -------------------------------------------------------------------------------- /leetcode/276. Paint Fence.md: -------------------------------------------------------------------------------- 1 | ## 276. Paint Fence 2 | 3 | ### Question: 4 | There is a fence with n posts, each post can be painted with one of the k colors. 5 | You have to paint all the posts such that no more than two adjacent 6 | fence posts have the same color. 7 | Return the total number of ways you can paint the fence. 8 | Note: n and k are non-negative integers. 9 | 10 | ### Thinking: 11 | * Method 1: 12 | * 动态规划。 13 | * 当n为0时,结果为0。 14 | * 当n为1时结果为K。 15 | * 当n > 1时 16 | * 与前一个不同 dp[i - 1] * (k - 1) 17 | * 与前一个相同(则与前前一个不同) dp[i - 1] - dp[i - 2] 18 | * 综上所述结果为 dp[i - 1] * k - dp[i - 2] 19 | 20 | ```Java 21 | private static int paintFence(int n, int k){ 22 | int[] dp = new int[n + 1]; 23 | dp[0] = 0; dp[1] = k; 24 | for(int i = 2; i <= n; i++){ 25 | dp[i] = dp[i - 1] * k - dp[i - 2]; 26 | } 27 | return dp[n]; 28 | } 29 | ``` 30 | 31 | ### Second time 32 | 1. Original values: 33 | * 0: 0 and 1: K 34 | * for each index, there are two terms 35 | * dp[i - 1] * (k - 1) (Not consider previous two are the same) 36 | * dp[i - 2] (Previous two are the same) 37 | * dp[i] = dp[i - 1] * (k - 1) - dp[i - 2] 38 | ```Java 39 | private static int paintFence(int n, int k){ 40 | int[] dp = new int[n + 1]; 41 | dp[0] = 0; dp[1] = k; 42 | for(int i = 2; i <= n; i++){ 43 | dp[i] = dp[i - 1] * k - dp[i - 2]; 44 | } 45 | return dp[n]; 46 | } 47 | ``` -------------------------------------------------------------------------------- /leetcode/283. Move Zeroes.md: -------------------------------------------------------------------------------- 1 | ## 283. Move Zeroes 2 | 3 | ### Question 4 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 5 | 6 | ``` 7 | Example: 8 | 9 | Input: [0,1,0,3,12] 10 | Output: [1,3,12,0,0] 11 | ``` 12 | 13 | ### Thinking: 14 | * Method 1: 15 | 16 | ```Java 17 | class Solution { 18 | public void moveZeroes(int[] nums) { 19 | int len = nums.length; 20 | int index = 0; 21 | int count = 0; 22 | for(int i = 0; i < len; i++){ 23 | if(nums[i] != 0){ 24 | nums[index++] = nums[i]; 25 | }else{ 26 | count++; 27 | } 28 | } 29 | for(int i = len - count; i < len; i++) 30 | nums[i] = 0; 31 | } 32 | } 33 | ``` 34 | 35 | ### Second time 36 | ```Java 37 | class Solution { 38 | public void moveZeroes(int[] nums) { 39 | int cur = 0; 40 | for(int i = 0; i < nums.length; i++){ 41 | if(nums[i] != 0){ 42 | nums[cur++] = nums[i]; 43 | } 44 | } 45 | for(int i = cur; i < nums.length; i++) 46 | nums[i] = 0; 47 | } 48 | } 49 | ``` 50 | -------------------------------------------------------------------------------- /leetcode/29. Divide Two Integers.md: -------------------------------------------------------------------------------- 1 | ## 29. Divide Two Integers 2 | ### Thinking: 3 | * Method1: Search 4 | We need to find if (target - current) is in the set, if not, add current to a hashSet for checking. 5 | Since to need to return the index according to value, so the key is value of number and value is index of number in array. 6 | ```Java 7 | class Solution { 8 | public int divide(int dividend, int divisor) { 9 | int sign = 1; 10 | if((dividend > 0 && divisor< 0) || (dividend < 0 && divisor > 0)) sign = -1; 11 | Long ldividend = Math.abs((long)dividend); 12 | Long ldivisor = Math.abs((long)divisor); 13 | if(ldividend < ldivisor) return 0; 14 | long result = divide(ldividend, ldivisor); 15 | if(result > Integer.MAX_VALUE) return (sign == 1)?Integer.MAX_VALUE:Integer.MIN_VALUE; 16 | return (int)((sign == 1)?result:-result); 17 | } 18 | 19 | private long divide(long ldividend, long ldivisor){ 20 | if(ldividend < ldivisor) return 0; 21 | long sum = ldivisor; 22 | long result = 1; 23 | while((sum + sum) < ldividend){ 24 | sum += sum; 25 | result += result; 26 | } 27 | return result + divide(ldividend - sum , ldivisor); 28 | } 29 | } 30 | ``` -------------------------------------------------------------------------------- /leetcode/292. Nim Game.md: -------------------------------------------------------------------------------- 1 | ## 292. Nim Game 2 | 3 | ### Question 4 | 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. 5 | 6 | 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. 7 | 8 | ``` 9 | Example: 10 | 11 | Input: 4 12 | Output: false 13 | Explanation: If there are 4 stones in the heap, then you will never win the game; 14 | No matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 15 | ``` 16 | 17 | ### Thinking: 18 | * Method 1: 19 | * 4的倍数无法获胜。 20 | 21 | ```Java 22 | class Solution { 23 | public boolean canWinNim(int n) { 24 | return n % 4 != 0; 25 | } 26 | } 27 | ``` 28 | 29 | ### Second time 30 | ```Java 31 | class Solution { 32 | public boolean canWinNim(int n) { 33 | return n % 4 != 0; 34 | } 35 | } 36 | ``` -------------------------------------------------------------------------------- /leetcode/319. Bulb Switcher.md: -------------------------------------------------------------------------------- 1 | ## 319. Bulb Switcher 2 | 3 | ### Question 4 | 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. 5 | 6 | ``` 7 | Example: 8 | 9 | Input: 3 10 | Output: 1 11 | Explanation: 12 | At first, the three bulbs are [off, off, off]. 13 | After first round, the three bulbs are [on, on, on]. 14 | After second round, the three bulbs are [on, off, on]. 15 | After third round, the three bulbs are [on, off, off]. 16 | 17 | So you should return 1, because there is only one bulb is on. 18 | ``` 19 | 20 | ### Thinking: 21 | * Method 1: 22 | * [LeetCode 319. Bulb Switcher 解题报告](https://blog.csdn.net/camellhf/article/details/52819154) 23 | 24 | ```Java 25 | class Solution { 26 | public int bulbSwitch(int n) { 27 | return (int)Math.sqrt(n); 28 | } 29 | } 30 | ``` -------------------------------------------------------------------------------- /leetcode/324. Wiggle Sort II.md: -------------------------------------------------------------------------------- 1 | ## 324. Wiggle Sort II 2 | 3 | ### Question 4 | Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: nums = [1, 5, 1, 1, 6, 4] 10 | Output: One possible answer is [1, 4, 1, 5, 1, 6]. 11 | 12 | Example 2: 13 | 14 | Input: nums = [1, 3, 2, 2, 3, 1] 15 | Output: One possible answer is [2, 3, 1, 3, 1, 2]. 16 | ``` 17 | 18 | ### Thinking: 19 | * Method 1:O(NlgN) 20 | * 排序后找到中位数,右侧的数字均大于等于左侧。 21 | * 依次从尾到头添加入原数组中,从尾到头避免了重复的数字被排在一起。 22 | 23 | ```Java 24 | class Solution { 25 | public void wiggleSort(int[] nums) { 26 | Arrays.sort(nums); 27 | int len = nums.length; 28 | int index = (len % 2 == 0) ? len / 2: len / 2 + 1; 29 | int[] arr = new int[index]; 30 | int i = 0; 31 | for(; i < index; i++) 32 | arr[i] = nums[i]; 33 | int[] sec = new int[len - index]; 34 | for(; i < len; i++) 35 | sec[i - index] = nums[i]; 36 | for(i = 0; i < index; i++){ 37 | nums[2 * i] = arr[index - i - 1]; 38 | if(2 * i + 1 < len) 39 | nums[2 * i + 1] = sec[sec.length - i - 1]; 40 | } 41 | } 42 | } 43 | ``` -------------------------------------------------------------------------------- /leetcode/342. Power of Four.md: -------------------------------------------------------------------------------- 1 | ## 342. Power of Four 2 | 3 | ### Question 4 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: 16 10 | Output: true 11 | 12 | Example 2: 13 | 14 | Input: 5 15 | Output: false 16 | ``` 17 | 18 | ### Thinking: 19 | * Method 1:位操作 20 | 21 | ```Java 22 | class Solution { 23 | public boolean isPowerOfFour(int num) { 24 | if(num < 0) return false; 25 | int count = 0; 26 | for(int i = 0; i < 32; i++){ 27 | if((num & 1) != 0){ 28 | if(++count > 1) return false; 29 | if(i % 2 != 0){ 30 | return false; 31 | } 32 | } 33 | num >>>= 1; 34 | } 35 | return count == 1; 36 | } 37 | } 38 | ``` -------------------------------------------------------------------------------- /leetcode/343. Integer Break.md: -------------------------------------------------------------------------------- 1 | ## 343. Integer Break 2 | 3 | ### Question 4 | Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: 2 10 | Output: 1 11 | Explanation: 2 = 1 + 1, 1 × 1 = 1. 12 | 13 | Example 2: 14 | 15 | Input: 10 16 | Output: 36 17 | Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. 18 | ``` 19 | 20 | ### Thinking: 21 | * Method 1: dp 22 | 23 | ```Java 24 | class Solution { 25 | public int integerBreak(int n) { 26 | int[] dp = new int[n + 1]; 27 | dp[0] = 1; 28 | dp[1] = 1; 29 | for(int i = 2; i <= n; i++){ 30 | int max = 0; 31 | for(int j = 1; j <= i / 2; j++){ 32 | max = Math.max(max, Math.max(j * (i - j), dp[j] * dp[i - j])); 33 | max = Math.max(max, Math.max(j * dp[i - j], dp[j] * (i - j))); 34 | } 35 | dp[i] = max; 36 | } 37 | return dp[n]; 38 | } 39 | } 40 | ``` -------------------------------------------------------------------------------- /leetcode/345. Reverse Vowels of a String.md: -------------------------------------------------------------------------------- 1 | ## 345. Reverse Vowels of a String 2 | 3 | ### Question 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: "hello" 10 | Output: "holle" 11 | 12 | Example 2: 13 | 14 | Input: "leetcode" 15 | Output: "leotcede" 16 | ``` 17 | 18 | ### Thinking: 19 | * Method 1: 20 | * 参考快排的寻找数字的方法。 21 | * 双指针。 22 | 23 | ```Java 24 | class Solution { 25 | public String reverseVowels(String s) { 26 | if(s == null || s.trim().length() == 0) return s; 27 | Set set = new HashSet<>(); 28 | set.addAll(Arrays.asList('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U')); 29 | char[] arr = s.toCharArray(); 30 | int low = 0, high = arr.length - 1; 31 | int len = arr.length; 32 | while(true){ 33 | while(!set.contains(arr[low])) if(++low >= len) break; 34 | while(!set.contains(arr[high])) if(--high < 0) break; 35 | if(low >= high) break; 36 | swap(arr, low++, high--); 37 | } 38 | return new String(arr); 39 | } 40 | private void swap(char[] arr, int i, int j){ 41 | char temp = arr[i]; 42 | arr[i] = arr[j]; 43 | arr[j] = temp; 44 | } 45 | } 46 | ``` -------------------------------------------------------------------------------- /leetcode/357. Count Numbers with Unique Digits.md: -------------------------------------------------------------------------------- 1 | ## 357. Count Numbers with Unique Digits 2 | 3 | ### Question 4 | Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n. 5 | 6 | ``` 7 | Example: 8 | 9 | Input: 2 10 | Output: 91 11 | Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 12 | ``` 13 | 14 | ### Thinking: 15 | * Method 1: 16 | * 通项公式: f(k) = 9 * 9 * 8 * ... (9 - k + 2) 17 | 18 | ```Java 19 | class Solution { 20 | public int countNumbersWithUniqueDigits(int n) { 21 | if(n == 0) return 1; 22 | int res = 10, cnt = 9; 23 | for(int i = 2; i <= n; i++){ 24 | cnt *= 11 - i; 25 | res += cnt; 26 | } 27 | return res; 28 | } 29 | } 30 | ``` -------------------------------------------------------------------------------- /leetcode/360. Sort Transfromed Array.md: -------------------------------------------------------------------------------- 1 | ## 360. Sort Transfromed Array 2 | 3 | ### Question 4 | Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array. 5 | 6 | The returned array must be in sorted order. 7 | 8 | Expected time complexity: O(n) 9 | ``` 10 | Example: 11 | 12 | nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5, 13 | 14 | Result: [3, 9, 15, 33] 15 | 16 | nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5 17 | 18 | Result: [-23, -5, 1, 7] 19 | 20 | ``` 21 | 22 | ### Thinking: 23 | * Method: Priority Queue 24 | 25 | ```Java 26 | public class SortTransformedArray { 27 | public static void sort(int[] nums, int a, int b, int c){ 28 | PriorityQueue queue = new PriorityQueue<>(); 29 | for(int n : nums) 30 | queue.add(a * n * n + b * n + c); 31 | int index = -1; 32 | while(!queue.isEmpty()){ 33 | nums[++index] = queue.poll(); 34 | } 35 | } 36 | public static void main(String[] args) { 37 | int[] nums = new int[]{-1, 2, 3,-2, 5}; 38 | sort(nums, 1, 2, 3); 39 | for(int n : nums) 40 | System.out.println(n); 41 | } 42 | } 43 | ``` -------------------------------------------------------------------------------- /leetcode/387. First Unique Character in a String.md: -------------------------------------------------------------------------------- 1 | ## 387. First Unique Character in a String 2 | 3 | ### Question 4 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 5 | 6 | ``` 7 | Examples: 8 | 9 | s = "leetcode" 10 | return 0. 11 | 12 | s = "loveleetcode", 13 | return 2. 14 | ``` 15 | 16 | Note: You may assume the string contain only lowercase letters. 17 | 18 | ### Solution 19 | * Method 1: array(or hashMap) 20 | ```Java 21 | class Solution { 22 | public int firstUniqChar(String s) { 23 | int[] dic = new int[26]; 24 | char[] arr = s.toCharArray(); 25 | for(char c : arr){ 26 | dic[c - 'a']++; 27 | } 28 | for(int i = 0; i < arr.length; i++){ 29 | if(dic[arr[i] - 'a'] == 1) return i; 30 | } 31 | return -1; 32 | } 33 | } 34 | ``` 35 | -------------------------------------------------------------------------------- /leetcode/412. Fizz Buzz.md: -------------------------------------------------------------------------------- 1 | ## 412. Fizz Buzz 2 | 3 | ### Question 4 | Write a program that outputs the string representation of numbers from 1 to n. 5 | 6 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 7 | 8 | ``` 9 | Example: 10 | 11 | n = 15, 12 | 13 | Return: 14 | [ 15 | "1", 16 | "2", 17 | "Fizz", 18 | "4", 19 | "Buzz", 20 | "Fizz", 21 | "7", 22 | "8", 23 | "Fizz", 24 | "Buzz", 25 | "11", 26 | "Fizz", 27 | "13", 28 | "14", 29 | "FizzBuzz" 30 | ] 31 | ``` 32 | 33 | ### Thinking: 34 | * Method 1: 35 | ```Java 36 | class Solution { 37 | public List fizzBuzz(int n) { 38 | List result = new ArrayList<>(); 39 | for(int i = 1; i <= n; i++){ 40 | if(i % 15 == 0){ 41 | result.add("FizzBuzz"); 42 | }else if(i % 3 == 0){ 43 | result.add("Fizz"); 44 | }else if(i % 5 == 0){ 45 | result.add("Buzz"); 46 | }else{result.add("" + i);} 47 | } 48 | return result; 49 | } 50 | } 51 | ``` -------------------------------------------------------------------------------- /leetcode/509. Fibonacci Number.md: -------------------------------------------------------------------------------- 1 | ## 509. Fibonacci Number 2 | 3 | ### Question 4 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 5 | 6 | F(0) = 0, F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), for N > 1. 8 | 9 | Given N, calculate F(N). 10 | 11 | ``` 12 | Example 1: 13 | 14 | Input: 2 15 | Output: 1 16 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 17 | 18 | Example 2: 19 | 20 | Input: 3 21 | Output: 2 22 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 23 | 24 | Example 3: 25 | 26 | Input: 4 27 | Output: 3 28 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 29 | ``` 30 | 31 | Note: 32 | * 0 ≤ N ≤ 30. 33 | 34 | 35 | ### Solutions 36 | * Method 1: DP 37 | ```Java 38 | class Solution { 39 | public int fib(int N) { 40 | if(N < 2) return N; 41 | int[] dp = new int[N + 1]; 42 | dp[0] = 0; dp[1] = 1; 43 | for(int i = 2; i <= N; i++){ 44 | dp[i] = dp[i - 1] + dp[i - 2]; 45 | } 46 | return dp[N]; 47 | } 48 | } 49 | ``` -------------------------------------------------------------------------------- /leetcode/58. Length of Last Word.md: -------------------------------------------------------------------------------- 1 | ## 58. Length of Last Word 2 | 3 | ### Question: 4 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 5 | 6 | If the last word does not exist, return 0. 7 | 8 | Note: A word is defined as a character sequence consists of non-space characters only. 9 | 10 | ``` 11 | Example: 12 | 13 | Input: "Hello World" 14 | Output: 5 15 | ``` 16 | 17 | ### Thinking: 18 | 19 | ```Java 20 | class Solution { 21 | public int lengthOfLastWord(String s) { 22 | String[] ss = s.trim().split(" "); 23 | return ss[ss.length - 1].length(); 24 | } 25 | } 26 | ``` 27 | 28 | ### 二刷 29 | 总是觉得这道题目应该有些问题,例如我输入" Hello 12", 答案和获得的结果是不一样的但是还是可以AC 30 | ```Java 31 | class Solution { 32 | public int lengthOfLastWord(String s) { 33 | if(s == null || s.trim().length() == 0) return 0; 34 | String[] arr = s.trim().split(" "); 35 | if(arr.length == 1) return s.trim().length(); 36 | return arr[arr.length - 1].length(); 37 | } 38 | } 39 | ``` 40 | -------------------------------------------------------------------------------- /leetcode/621. Task Scheduler.md: -------------------------------------------------------------------------------- 1 | ## 621. Task Scheduler 2 | 3 | ### Question 4 | Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. 5 | 6 | However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. 7 | 8 | You need to return the least number of intervals the CPU will take to finish all the given tasks. 9 | 10 | ``` 11 | Example: 12 | 13 | Input: tasks = ["A","A","A","B","B","B"], n = 2 14 | Output: 8 15 | Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. 16 | ``` 17 | 18 | Note: 19 | * The number of tasks is in the range [1, 10000]. 20 | * The integer n is in the range [0, 100]. 21 | 22 | ### Thinking: 23 | * Method 1: Greedy 24 | ```Java 25 | class Solution { 26 | public int leastInterval(char[] tasks, int n) { 27 | int[] freq = new int[26]; 28 | for(char c : tasks){ 29 | freq[c - 'A']++; 30 | } 31 | Arrays.sort(freq); 32 | int i = 25; 33 | while(i >= 0 && freq[i] == freq[25]){i--;} 34 | return Math.max((n + 1) * (freq[25] - 1) + (25 - i), tasks.length); 35 | } 36 | } 37 | ``` -------------------------------------------------------------------------------- /leetcode/65. Valid Number.md: -------------------------------------------------------------------------------- 1 | ## 65. Valid Number 2 | 3 | ### Question: 4 | Validate if a given string can be interpreted as a decimal number. 5 | 6 | Some examples: 7 | "0" => true 8 | " 0.1 " => true 9 | "abc" => false 10 | "1 a" => false 11 | "2e10" => true 12 | " -90e3 " => true 13 | " 1e" => false 14 | "e3" => false 15 | " 6e-1" => true 16 | " 99e2.5 " => false 17 | "53.5e93" => true 18 | " --6 " => false 19 | "-+3" => false 20 | "95a54e53" => false 21 | 22 | Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: 23 | * Numbers 0-9 24 | * Exponent - "e" 25 | * Positive/negative sign - "+"/"-" 26 | * Decimal point - "." 27 | 28 | Of course, the context of these characters also matters in the input. 29 | 30 | ### Thinking: 31 | * Method: 32 | * 这道题是参考别人的答案才写出来的,用的方法是正则表达式匹配。 33 | 34 | ```Java 35 | import java.util.regex.Matcher; 36 | import java.util.regex.Pattern; 37 | 38 | class Solution { 39 | public boolean isNumber(String s) { 40 | s = s.trim(); 41 | if(s.equals("")) return false; 42 | Pattern p = Pattern.compile("^[+-]?((\\d+(\\.\\d*)?)|(\\.\\d+))([eE][+-]?\\d+)?"); 43 | Matcher m = p.matcher(s); 44 | return m.matches(); 45 | } 46 | } 47 | ``` 48 | -------------------------------------------------------------------------------- /leetcode/700. Search in a Binary Search Tree.md: -------------------------------------------------------------------------------- 1 | ## 700. Search in a Binary Search Tree 2 | 3 | ### Question: 4 | Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 5 | 6 | ``` 7 | For example, 8 | 9 | Given the tree: 10 | 4 11 | / \ 12 | 2 7 13 | / \ 14 | 1 3 15 | 16 | And the value to search: 2 17 | 18 | You should return this subtree: 19 | 20 | 2 21 | / \ 22 | 1 3 23 | 24 | In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL. 25 | ``` 26 | 27 | Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null. 28 | 29 | ### Solution: 30 | * Method 1: BST 31 | ```Java 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 | class Solution { 42 | public TreeNode searchBST(TreeNode root, int val) { 43 | if(root == null) return null; 44 | if(root.val == val) return root; 45 | return searchBST(val < root.val ? root.left: root.right, val); 46 | } 47 | } 48 | ``` -------------------------------------------------------------------------------- /leetcode/704. Binary Search.md: -------------------------------------------------------------------------------- 1 | ## 704. Binary Search 2 | 3 | ### Question: 4 | Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: nums = [-1,0,3,5,9,12], target = 9 10 | Output: 4 11 | Explanation: 9 exists in nums and its index is 4 12 | 13 | Example 2: 14 | 15 | Input: nums = [-1,0,3,5,9,12], target = 2 16 | Output: -1 17 | Explanation: 2 does not exist in nums so return -1 18 | ``` 19 | 20 | Note: 21 | 1. You may assume that all elements in nums are unique. 22 | 2. n will be in the range [1, 10000]. 23 | 3. The value of each element in nums will be in the range [-9999, 9999]. 24 | 25 | 26 | ### Solution: 27 | * Method 1: binary search 28 | ```Java 29 | class Solution { 30 | public int search(int[] nums, int target) { 31 | if(nums == null || nums.length == 0) return -1; 32 | return bs(nums, 0, nums.length - 1, target); 33 | } 34 | private int bs(int[] nums, int low, int high, int target){ 35 | if(low > high) return -1; 36 | int mid = low + (high - low) / 2; 37 | if(nums[mid] == target) return mid; 38 | else if(nums[mid] > target) return bs(nums, low, mid - 1, target); 39 | else return bs(nums, mid + 1, high, target); 40 | } 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /leetcode/717. 1-bit and 2-bit Characters.md: -------------------------------------------------------------------------------- 1 | ## 717. 1-bit and 2-bit Characters 2 | 3 | ### Question 4 | We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). 5 | 6 | Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. 7 | 8 | ``` 9 | Example 1: 10 | 11 | Input: 12 | bits = [1, 0, 0] 13 | Output: True 14 | Explanation: 15 | The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. 16 | 17 | Example 2: 18 | 19 | Input: 20 | bits = [1, 1, 1, 0] 21 | Output: False 22 | Explanation: 23 | The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. 24 | ``` 25 | 26 | Note: 27 | 1. 1 <= len(bits) <= 1000. 28 | 2. bits[i] is always 0 or 1. 29 | 30 | ### Solutions: 31 | * Method 1: Array 7m50s 32 | ```Java 33 | class Solution { 34 | public boolean isOneBitCharacter(int[] bits) { 35 | int index = 0; 36 | while(index < bits.length){ 37 | if(index == bits.length - 1) return true; 38 | if(bits[index] == 0) index++; 39 | else index += 2; 40 | } 41 | return false; 42 | } 43 | } 44 | ``` -------------------------------------------------------------------------------- /leetcode/771. Jewels and Stones.md: -------------------------------------------------------------------------------- 1 | ## 771. Jewels and Stones 2 | 3 | ### Question 4 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 5 | 6 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 7 | 8 | ``` 9 | Example 1: 10 | 11 | Input: J = "aA", S = "aAAbbbb" 12 | Output: 3 13 | Example 2: 14 | 15 | Input: J = "z", S = "ZZ" 16 | Output: 0 17 | ``` 18 | 19 | Note: 20 | * S and J will consist of letters and have length at most 50. 21 | * The characters in J are distinct. 22 | 23 | ### Solution 24 | * Method 1: HashSet 25 | ```Java 26 | class Solution { 27 | public int numJewelsInStones(String J, String S) { 28 | Set set = new HashSet<>(); 29 | for(char c : J.toCharArray()){ 30 | set.add(c); 31 | } 32 | int res = 0; 33 | for(char c : S.toCharArray()){ 34 | if(set.contains(c)) res++; 35 | } 36 | return res; 37 | } 38 | } 39 | ``` 40 | -------------------------------------------------------------------------------- /leetcode/787. Cheapest Flights Within K Stops.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Seanforfun/Algorithm-and-Leetcode/4ea49415a05d1c6ed54a384841fa46f86c2810e2/leetcode/787. Cheapest Flights Within K Stops.md -------------------------------------------------------------------------------- /leetcode/829. Consecutive Numbers Sum.md: -------------------------------------------------------------------------------- 1 | ## 829. Consecutive Numbers Sum 2 | 3 | ### Question 4 | Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers? 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: 5 10 | Output: 2 11 | Explanation: 5 = 5 = 2 + 3 12 | Example 2: 13 | 14 | Input: 9 15 | Output: 3 16 | Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4 17 | Example 3: 18 | 19 | Input: 15 20 | Output: 4 21 | Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 22 | Note: 1 <= N <= 10 ^ 9. 23 | ``` 24 | 25 | ### Solution: 26 | * Method 1: Math 27 | * We assume the first term is x and totally m terms. 28 | * 2xm + m(m - 1) = 2N => we try all possible m and find if there is a valid x. 29 | ```Java 30 | class Solution { 31 | public int consecutiveNumbersSum(int N) { 32 | int res = 0; 33 | for(int m = 1;;m++){ 34 | int mx = 2 * N - m *(m - 1); 35 | if(mx <= 0) break; 36 | else if(mx % (2 * m) == 0) res++; 37 | } 38 | return res; 39 | } 40 | } 41 | ``` 42 | -------------------------------------------------------------------------------- /leetcode/836. Rectangle Overlap.md: -------------------------------------------------------------------------------- 1 | ## 836. Rectangle Overlap 2 | 3 | ### Question 4 | A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner. 5 | 6 | Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. 7 | 8 | Given two (axis-aligned) rectangles, return whether they overlap. 9 | 10 | ``` 11 | Example 1: 12 | 13 | Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] 14 | Output: true 15 | Example 2: 16 | 17 | Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] 18 | Output: false 19 | ``` 20 | 21 | Notes: 22 | * Both rectangles rec1 and rec2 are lists of 4 integers. 23 | * All coordinates in rectangles will be between -10^9 and 10^9. 24 | 25 | ### Solution 26 | * Method 1: 27 | ```Java 28 | class Solution { 29 | public boolean isRectangleOverlap(int[] rec1, int[] rec2) { 30 | return !(rec1[0] >= rec2[2] || rec1[1] >= rec2[3] || 31 | rec1[2] <= rec2[0] || rec1[3] <= rec2[1]); 32 | } 33 | } 34 | ``` 35 | -------------------------------------------------------------------------------- /leetcode/844. Backspace String Compare.md: -------------------------------------------------------------------------------- 1 | ## 844. Backspace String Compare 2 | ### Thinking: 3 | * Method 1: 4 | * 使用栈。 5 | ```Java 6 | class Solution { 7 | public boolean backspaceCompare(String S, String T) { 8 | int sLen = S.length(); 9 | int tLen = T.length(); 10 | Stack st1 = new Stack<>(); 11 | Stack st2 = new Stack<>(); 12 | for(int i = 0; i < sLen; i++){ 13 | if(st1.size() == 0 && S.charAt(i) == '#') continue; 14 | if(S.charAt(i) == '#') st1.pop(); 15 | else st1.push(S.charAt(i)); 16 | } 17 | for(int i = 0; i < tLen; i++){ 18 | if(st2.size() == 0 && T.charAt(i) == '#') continue; 19 | if(T.charAt(i) == '#') st2.pop(); 20 | else st2.push(T.charAt(i)); 21 | } 22 | if(st1.size() != st2.size()) return false; 23 | while(!st1.isEmpty()){ 24 | if(st1.pop() != st2.pop()) return false; 25 | } 26 | return true; 27 | } 28 | } 29 | ``` -------------------------------------------------------------------------------- /leetcode/852. Peak Index in a Mountain Array.md: -------------------------------------------------------------------------------- 1 | ## 852. Peak Index in a Mountain Array 2 | 3 | ### Question: 4 | Let's call an array A a mountain if the following properties hold: 5 | * A.length >= 3 6 | * 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] 7 | 8 | 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]. 9 | 10 | ``` 11 | Example 1: 12 | 13 | Input: [0,1,0] 14 | Output: 1 15 | 16 | Example 2: 17 | 18 | Input: [0,2,1,0] 19 | Output: 1 20 | ``` 21 | 22 | Note: 23 | 1. 3 <= A.length <= 10000 24 | 2. 0 <= A[i] <= 10^6 25 | 3. A is a mountain, as defined above. 26 | 27 | 28 | ### Solution: 29 | * Method 1: Binary search 30 | ```Java 31 | class Solution { 32 | public int peakIndexInMountainArray(int[] A) { 33 | int low = 0, high = A.length - 1; 34 | while(low < high){ 35 | int mid = low + (high - low) / 2; 36 | if(A[mid] < A[mid + 1]) low = mid + 1; 37 | else high = mid; 38 | } 39 | return low; 40 | } 41 | } 42 | ``` 43 | 44 | -------------------------------------------------------------------------------- /leetcode/91. Decode Ways.md: -------------------------------------------------------------------------------- 1 | ## 91. Decode Ways 2 | ### Thinking: 3 | * Method: 4 | * 通过动态规划实现。 5 | * 分析: 6 | * 通过一个长度为len + 1的数组装载每个位的结果。 7 | * dp[0]的值为1。 8 | * 每个当前值都是由dp[i - 1]和dp[i - 2]决定的。 9 | * 当前值在1-9之间,我们当前值加上dp[i - 1]。 10 | * 当这两位的值在10 - 26之间,就要加上dp[i - 2]。 11 | 12 | ```Java 13 | class Solution { 14 | public int numDecodings(String s) { 15 | if(s == null) return 1; 16 | int len = s.length(); 17 | int[] dp = new int[len + 1]; 18 | dp[0] = 1; 19 | for(int i = 0; i < len; i++){ 20 | char c = s.charAt(i); 21 | if(c > '0' && c <= '9') dp[i + 1] += dp[i]; 22 | if(i > 0 && c >= '0' && c <= '6' && s.charAt(i - 1) == '2') dp[i + 1] += dp[i - 1]; 23 | if(i > 0 && s.charAt(i - 1) == '1') dp[i + 1] += dp[i - 1]; 24 | } 25 | return dp[len]; 26 | } 27 | } 28 | ``` -------------------------------------------------------------------------------- /leetcode/935. Knight Dialer.md: -------------------------------------------------------------------------------- 1 | ## 935. Knight Dialer 2 | 3 | ### Question: 4 | A chess knight can move as indicated in the chess diagram below: 5 | ![Imgur](https://i.imgur.com/PyYrxUv.png) 6 | 7 | This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1 hops. Each hop must be from one key to another numbered key. 8 | 9 | Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, pressing N digits total. 10 | 11 | How many distinct numbers can you dial in this manner? 12 | 13 | Since the answer may be large, output the answer modulo 10^9 + 7. 14 | 15 | ``` 16 | Example 1: 17 | 18 | Input: 1 19 | Output: 10 20 | 21 | Example 2: 22 | 23 | Input: 2 24 | Output: 20 25 | 26 | Example 3: 27 | 28 | Input: 3 29 | Output: 46 30 | ``` 31 | 32 | Note: 33 | * 1 <= N <= 5000 34 | 35 | 36 | 37 | ### Solution: 38 | * Method 1: DP O(10 * n^3) AC 1136ms 39 | ![Imgur](https://i.imgur.com/tea63Ay.png) 40 | 41 | * Method 2: dp AC 18ms 93.43% 42 | 1. use a rotate array to save temp result so we can reduce Memory space from O(12 * N) to O(12 * 2) 43 | 2. If we can change the way we calculate for the knight moving, we just can use a 1-D array and we don't need to to any validation process. 44 | ![Imgur](https://i.imgur.com/Uz06asU.png) 45 | 46 | ### Reference 47 | 1. [花花酱 LeetCode 935. Knight Dialer](https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-935-knight-dialer/) -------------------------------------------------------------------------------- /leetcode/965. Univalued Binary Tree.md: -------------------------------------------------------------------------------- 1 | ## 965. Univalued Binary Tree 2 | 3 | ### Question: 4 | A binary tree is univalued if every node in the tree has the same value. 5 | 6 | Return true if and only if the given tree is univalued. 7 | 8 | ``` 9 | Example 1: 10 | 11 | Input: [1,1,1,1,1,null,1] 12 | Output: true 13 | 14 | Example 2: 15 | 16 | Input: [2,2,2,5,2] 17 | Output: false 18 | ``` 19 | 20 | 21 | Note: 22 | 1. The number of nodes in the given tree will be in the range [1, 100]. 23 | 2. Each node's value will be an integer in the range [0, 99]. 24 | 25 | ### Solution: 26 | * Method 1: dfs 27 | ```Java 28 | /** 29 | * Definition for a binary tree node. 30 | * public class TreeNode { 31 | * int val; 32 | * TreeNode left; 33 | * TreeNode right; 34 | * TreeNode(int x) { val = x; } 35 | * } 36 | */ 37 | class Solution { 38 | private int pre; 39 | public boolean isUnivalTree(TreeNode root) { 40 | pre = root.val; 41 | return check(root.left) && check(root.right); 42 | } 43 | private boolean check(TreeNode node){ 44 | if(node == null) return true; 45 | else if(pre != node.val) return false; 46 | else{ 47 | return check(node.left) && check(node.right); 48 | } 49 | } 50 | } 51 | ``` 52 | -------------------------------------------------------------------------------- /leetcode/Offer/Question1_1.md: -------------------------------------------------------------------------------- 1 | # Question1_1 2 | 3 | #### Solution 4 | ```Java 5 | public class Question1_1 { 6 | public static boolean isDuplicateString(String str){ 7 | int length = str.length(); 8 | Set set = new HashSet(); 9 | for(int i=0; i < length; i++){ //int,Integer等类型变量没有实现Iterable方法,所以不能用forEach进行遍历。 10 | char c = str.charAt(i); //是CharAt,不是indexAt 11 | if(!set.contains(c)) 12 | set.add(c); //java中的set添加是add方法添加,remove方法删除 13 | else 14 | return false; 15 | } 16 | return true; 17 | } 18 | public static void main(String[] args) { 19 | System.out.println(isDuplicateString("12142fsafdhsajkfhldsa")); 20 | } 21 | } 22 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question1_2.md: -------------------------------------------------------------------------------- 1 | # Question1_2 2 | 3 | #### Solution 4 | ```Java 5 | public class Question1_2 { 6 | public static String reverseString(String str){ 7 | char[] arr = str.toCharArray(); //要记住将String转换成charArray的方法。 8 | int len = str.length(); 9 | int low = 0; 10 | int high = len - 1; 11 | while(low < high){ 12 | char temp = arr[low]; 13 | arr[low] = arr[high]; 14 | arr[high] = temp; 15 | low++; high--; 16 | } 17 | return new String(arr); //将charArray转换成字符串的方法。 18 | } 19 | public static void main(String[] args) { 20 | System.out.println(reverseString("12345")); 21 | } 22 | } 23 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question1_3.md: -------------------------------------------------------------------------------- 1 | # Question1_3 2 | 3 | #### Solution 4 | * 我原来是想要通过map去存储a和b中的字符种类和次数,但是这样要做3次遍历,最后一次是遍历两个map。 5 | * 参考书上的做法,是将a和b分别排序,再比较字符串是否相等。这样就减少了遍历的次数。 6 | 7 | ```Java 8 | public class Question1_3 { 9 | public static boolean canBecome(String a, String b){ 10 | char[] aArr = a.toCharArray(); 11 | char[] bArr = b.toCharArray(); 12 | Arrays.sort(aArr); 13 | Arrays.sort(bArr); 14 | return new String(aArr).equals(new String(bArr)); 15 | } 16 | public static void main(String[] args) { 17 | System.out.println(canBecome("apple", "plaep")); 18 | } 19 | } 20 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question1_4.md: -------------------------------------------------------------------------------- 1 | # Question1_4 2 | 3 | #### Solution 4 | ```Java 5 | public class Question1_4 { 6 | public static String replaceWhiteSpace(char[] s, int length){ 7 | StringBuilder sb = new StringBuilder(); //要注意StringBuilder是非线程安全的! 8 | for(int i = 0; i < length; i++){ 9 | if(s[i] == ' ') //要注意是双等号! 10 | sb.append("%20"); 11 | else 12 | sb.append(s[i]); //StringBuilder可以append char型变量,不需要转化成String类型。 13 | } 14 | return sb.toString(); 15 | } 16 | public static void main(String[] args) { 17 | String test = " adf sdf123 24"; 18 | System.out.println(replaceWhiteSpace(test.toCharArray(), test.length())); 19 | } 20 | } 21 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question1_5.md: -------------------------------------------------------------------------------- 1 | # Question1_5 2 | 3 | #### Solution 4 | ```Java 5 | public class Question1_5 { 6 | public static String compress(String str){ 7 | int len = str.length(); 8 | char prev = str.charAt(0); //因为第一个字符无法和别的字符进行比较,所以我们拉在循环外面做。 9 | int count = 1; 10 | StringBuilder sb = new StringBuilder(); 11 | sb.append(prev); 12 | for(int i = 1; i < len; i++){ 13 | if(str.charAt(i) != prev){ 14 | sb.append(count); 15 | prev = str.charAt(i); 16 | sb.append(prev); 17 | count = 1; 18 | }else 19 | count++; 20 | } 21 | sb.append(count); //最后一个字符没有后面的字符进行比较,所以无法写入count,所以应该在循环外写入count。 22 | return sb.toString(); 23 | } 24 | public static void main(String[] args) { 25 | System.out.println(compress("aaaaadfsssscssd")); 26 | } 27 | } 28 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question1_6.md: -------------------------------------------------------------------------------- 1 | # Question1_6 2 | 3 | #### Solution 4 | ```Java 5 | public class Question1_6 { 6 | public static int[][] rotate(int m[][], int n){ 7 | for(int layer = 0; layer < n/2; layer++){ 8 | int first = layer; 9 | int last = n - 1 - layer; 10 | for(int i = first; i < last; i++){ 11 | int offset = i - first; 12 | int top = m[first][i]; 13 | m[first][i] = m[last-offset][first]; 14 | m[last-offset][first] = m[last][last-offset]; 15 | m[last][last-offset] = m[i][last]; 16 | m[i][last] = top; 17 | } 18 | } 19 | return m; 20 | } 21 | public static void main(String[] args) { 22 | int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 23 | a = rotate(a, 3); 24 | for(int i = 0; i < 3; i++){ 25 | for(int j = 0; j <3; j++) 26 | System.out.print(a[i][j] + " "); 27 | System.out.println(); 28 | } 29 | } 30 | } 31 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question1_8.md: -------------------------------------------------------------------------------- 1 | # Question1_8 2 | 3 | #### Solution 4 | * 这道题只能使用isSubstring一次,所以我们不能单纯的通过遍历一次次判断,通过研究可以发现,无论s1,s2如何旋转,只要答案应该是true,我们可以得知s1一定是s2s2的子集。 5 | * 这道题的思路大于编程技巧,在测试之前我们一定要认真的研究题目的方法。 6 | 7 | ```Java 8 | public class Question1_8 { 9 | public static boolean isSubstring(String s1, String s2){ 10 | if(s1.contains(s2)) 11 | return true; 12 | return false; 13 | } 14 | public static boolean isRotation(String s1, String s2){ 15 | if(s1.length() != s2.length()) 16 | return false; 17 | String doubleString = s1 + s1; 18 | if(isSubstring(doubleString, s2)) 19 | return true; 20 | return false; 21 | } 22 | public static void main(String[] args) { 23 | System.out.println(isRotation("waterbottle", "terbottlewa")); 24 | } 25 | } 26 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question2_1.md: -------------------------------------------------------------------------------- 1 | # Question2_1 2 | 3 | #### Solution 4 | * 可以使用额外内存 5 | 6 | ```Java 7 | public void removeDuplicate(){ 8 | Set set = new HashSet<>(); 9 | ListNode curr = dummy; 10 | while(curr.next != null){ 11 | if(!set.contains(curr.next.value)){ 12 | set.add(curr.next.value); 13 | curr = curr.next; //写代码中一定要注意只有当不存在的时候才会将node后移,不然继续对当前的结点的后继节点进行检查。 14 | }else{ 15 | curr.next = curr.next.next; 16 | length--; 17 | } 18 | } 19 | } 20 | ``` 21 | 22 | * 不使用额外内存,使用两个指针,第一个指针用于遍历,第二个指针用于删除后继结点中的相同元素。 23 | 24 | ```Java 25 | public void removeDuplicateTwoPointer(){ 26 | ListNode curr = dummy; 27 | ListNode check; 28 | while(curr.next != null){ 29 | T t = curr.next.value; 30 | check = curr.next; 31 | while(check.next != null){ 32 | if(check.next.value == t){ 33 | check.next = check.next.next; 34 | }else 35 | check = check.next; 36 | } 37 | curr = curr.next; 38 | } 39 | } 40 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question2_2.md: -------------------------------------------------------------------------------- 1 | # Question2_2 2 | 3 | #### Solution 4 | * 使用双指针的方法,第一个指针遍历链表,第二个指针指向其后的K个元素,如果正好是null则说明第一个指针是倒数第K个元素。 5 | 6 | ```Java 7 | public T lastK(int k){ 8 | ListNode curr = dummy; 9 | ListNode last; 10 | while(curr.next != null){ 11 | int step = k; 12 | last = curr.next; 13 | while(step > 0){ 14 | last = last.next; 15 | step--; 16 | if(step > 0 && last == null){ 17 | throw new ArrayIndexOutOfBoundsException(); 18 | } 19 | } 20 | if(last == null) 21 | return curr.next.value; 22 | curr = curr.next; 23 | } 24 | return null; 25 | } 26 | ``` -------------------------------------------------------------------------------- /leetcode/Offer/Question2_3.md: -------------------------------------------------------------------------------- 1 | # Question2_3 2 | 3 | #### Solution 4 | * 删除单向链表的某个结点,并且没有给出头指针,只给了这个结点。 5 | * 将这个结点后面的所有结点的值向前复制,并删除最后一个结点。 6 | ```Java 7 | public void removeWithNodeStupid(ListNode node){ 8 | ListNode curr = node; 9 | while(curr.next != null && curr.next.next != null){ 10 | curr.value = curr.next.value; 11 | curr = curr.next; 12 | } 13 | curr.value = curr.next.value; 14 | curr.next = null; 15 | } 16 | ``` 17 | * 将要删除的结点的后一个结点的值向前复制,只删除后一个节点。 18 | ```Java 19 | public void removeWithNode(ListNode node){ 20 | ListNode curr = node; 21 | if(curr.next == null){ 22 | curr = null; 23 | return; 24 | } 25 | curr.value = curr.next.value; 26 | curr.next = curr.next.next; 27 | } 28 | ``` 29 | -------------------------------------------------------------------------------- /leetcode/Offer/Question2_4.md: -------------------------------------------------------------------------------- 1 | # Question2_4 2 | 3 | #### Solution 4 | ```Java 5 | public ListNode partition(Integer k, ListNode dummy){ 6 | ListNode dummySmall = new ListNode(null); 7 | ListNode currSmall = dummySmall; 8 | ListNode dummyOther = new ListNode(null); 9 | ListNode currOther = dummyOther; 10 | while(dummy.next != null){ 11 | Integer value = dummy.next.value; 12 | if(value < k){ 13 | currSmall.next = dummy.next; 14 | currSmall = currSmall.next; 15 | }else{ 16 | currOther.next = dummy.next; 17 | currOther = currOther.next; 18 | } 19 | dummy = dummy.next; 20 | } 21 | currSmall.next = dummyOther.next; 22 | return dummySmall.next; 23 | } 24 | ``` 25 | -------------------------------------------------------------------------------- /leetcode/Offer/Question2_5.md: -------------------------------------------------------------------------------- 1 | # Question2_5 2 | 3 | #### Solution 4 | ```Java 5 | public OfferList addition(ListNode node1, ListNode node2){ 6 | OfferList result = new OfferList(); 7 | int carry = 0; 8 | while(node1.next != null || node2.next != null){ 9 | if(node1.next != null && node2.next != null){ 10 | result.add((node1.next.value + node2.next.value + carry) % 10); 11 | carry = (node1.next.value + node2.next.value + carry) / 10; 12 | node1 = node1.next; 13 | node2 = node2.next; 14 | }else if(node1.next.value != null && node2.next == null){ 15 | result.add((node1.next.value + carry) % 10); 16 | carry = (node1.next.value + carry) / 10; 17 | node1 = node1.next; 18 | }else if (node1.next == null && node2.next != null) { 19 | result.add((node2.next.value + carry) % 10); 20 | carry = (node2.next.value + carry) / 10; 21 | node2 = node2.next; 22 | } 23 | } 24 | if(carry == 1){ //不能忘记处理最后的Carry问题! 25 | result.add(1); 26 | } 27 | return result; 28 | } 29 | ``` 30 | -------------------------------------------------------------------------------- /leetcode/Offer/Question2_6.md: -------------------------------------------------------------------------------- 1 | # Question2_6 2 | 3 | #### Solution 4 | ```Java 5 | public class Question2_6 { 6 | public static OfferList.ListNode isBegining(OfferList.ListNode dummy){ 7 | OfferList.ListNode slow = dummy.next.next; 8 | OfferList.ListNode fast = dummy.next.next; 9 | while(slow != fast){ 10 | slow = slow.next; 11 | fast = fast.next.next; 12 | } 13 | if(fast == null) 14 | return null; 15 | OfferList.ListNode beginning = dummy.next; 16 | while(beginning != fast){ 17 | beginning = beginning.next; 18 | fast = fast.next; 19 | } 20 | return beginning; 21 | } 22 | public static void main(String[] args) { 23 | OfferList.ListNode dummy = new OfferList().new ListNode(null); 24 | OfferList.ListNode head = dummy; 25 | OfferList.ListNode begin = null; 26 | for(int i = 0; i < 20; i++){ 27 | OfferList.ListNode temp = new OfferList().new ListNode(i); 28 | begin = temp; 29 | dummy.next = temp; 30 | dummy = dummy.next; 31 | } 32 | System.out.println(begin.value); 33 | for(int i = 20; i <40; i++){ 34 | OfferList.ListNode temp = new OfferList().new ListNode(i); 35 | dummy.next = temp; 36 | dummy = dummy.next; 37 | } 38 | dummy.next = begin; 39 | System.out.println(isBegining(head).value); 40 | } 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /leetcode/Offer/Question3_4.md: -------------------------------------------------------------------------------- 1 | # Question3_4 2 | 3 | #### Solution 4 | * 使用递归的方法,每次将最底部的碟移动到destination上,而将剩余的碟子存在缓存区中。 5 | ```Java 6 | public class Question3_4 { 7 | private static class Tower{ 8 | private Stack disks; 9 | private int index; 10 | public Tower(int index){ 11 | this.index = index; 12 | disks = new Stack<>(); 13 | } 14 | public int getIndex(){ 15 | return this.index; 16 | } 17 | public void add(int v){ 18 | if(!disks.isEmpty() && disks.peek() < v) throw new RuntimeException("Error putting disk!"); 19 | else { 20 | disks.push(v); 21 | } 22 | } 23 | public void moveTopTo(Tower t){ 24 | int top = disks.pop(); 25 | t.add(top); 26 | } 27 | public void moveDisks(int n, Tower destination, Tower buffer){ 28 | if(n > 0){ 29 | moveDisks(n - 1, buffer, destination); 30 | moveTopTo(destination); //至此为止的两步将最底部的碟移动到了destination。 31 | buffer.moveDisks(n - 1, destination, this);//这一步递归调用将剩余的碟从缓存区中移动到destination. 32 | } 33 | } 34 | } 35 | public static void main(String[] args) { 36 | Tower[] towers = new Tower[3]; 37 | for(int i = 0; i < 3; i++) 38 | towers[i] = new Tower(i); 39 | for(int i = 10; i >= 0; i--) 40 | towers[0].add(i); 41 | towers[0].moveDisks(11, towers[2], towers[1]); 42 | for(int i = 0; i < 11; i++){ 43 | System.out.println(towers[2].disks.pop()); 44 | } 45 | } 46 | } 47 | ``` 48 | -------------------------------------------------------------------------------- /leetcode/Offer/Question3_5.md: -------------------------------------------------------------------------------- 1 | # Question3_5 2 | 3 | #### Solution 4 | ```Java 5 | public class MyQueue { 6 | private Stack stack1; 7 | private Stack stack2; 8 | public MyQueue() { 9 | stack1 = new Stack<>(); 10 | stack2 = new Stack<>(); 11 | } 12 | public void offer(E e){ 13 | stack1.add(e); 14 | } 15 | public E poll(){ 16 | while(!stack1.isEmpty()){ 17 | stack2.push(stack1.pop()); 18 | } 19 | E result = stack2.pop(); 20 | while(!stack2.isEmpty()){ 21 | stack1.push(stack2.pop()); 22 | } 23 | return result; 24 | } 25 | public static void main(String[] args) { 26 | MyQueue queue = new MyQueue<>(); 27 | for(int i = 0; i < 10; i++) 28 | queue.offer(i); 29 | for (int i = 0; i < 10; i++) 30 | System.out.println(queue.poll()); 31 | } 32 | } 33 | ``` 34 | -------------------------------------------------------------------------------- /leetcode/Offer/Question3_6.md: -------------------------------------------------------------------------------- 1 | # Question3_6 2 | 3 | #### Solution 4 | ![flowchart](https://i.imgur.com/vgfAJFo.png) 5 | ```Java 6 | public class Question3_6 { 7 | public static Stack sortStack(Stack stack){ 8 | Stack result = new Stack<>(); 9 | Integer tmp = null; 10 | while(!stack.isEmpty()){ 11 | tmp = stack.pop(); 12 | while(!result.isEmpty() && result.peek() > tmp) 13 | stack.push(result.pop()); 14 | result.push(tmp); 15 | } 16 | return result; 17 | } 18 | public static void main(String[] args) { 19 | Stack stack = new Stack(); 20 | stack.push(2); 21 | stack.push(3); 22 | stack.push(1); 23 | stack.push(3); 24 | stack.push(2); 25 | stack.push(6); 26 | stack.push(7); 27 | stack.push(4); 28 | stack.push(3); 29 | stack.push(2); 30 | Stack sortStack = sortStack(stack); 31 | while(!sortStack.isEmpty()){ 32 | System.out.println(sortStack.pop()); 33 | } 34 | } 35 | } 36 | ``` 37 | -------------------------------------------------------------------------------- /leetcode/Offer/Question4_2.md: -------------------------------------------------------------------------------- 1 | # Question4_2 2 | 3 | #### Solution 4 | * 图的定义 5 | ```Java 6 | public class OfferGraph { 7 | public class GraphVertex{ 8 | int value; 9 | List connections; 10 | public GraphVertex(int value, List connections){ 11 | this.value = value; 12 | this.connections = connections; 13 | } 14 | public boolean isConnectDFS(GraphVertex vertex){ 15 | Set set = new HashSet<>(); 16 | for(GraphVertex v : this.connections){ 17 | System.out.println(v.value); 18 | if(v == vertex){ 19 | return true; 20 | } 21 | if(!set.contains(v)){ 22 | set.add(v); 23 | return v.isConnect(vertex); //递归调用,我们判断当前的顶点是否与所期待的顶点相连。必须在递归中进行return,不然在底层返回了结果对上层并,并没有影响。 24 | }else 25 | continue; 26 | } 27 | return false; 28 | } 29 | public boolean isConnectBFS(GraphVertex vertex){ 30 | if(null == vertex) return false; 31 | Set set = new HashSet<>(); 32 | Queue queue = new Queue<>(); 33 | queue.enqueue(this); 34 | while(!queue.isEmpty()){ 35 | GraphVertex ver = queue.dequeue(); 36 | for(GraphVertex v:ver.connections){ 37 | if(!set.contains(v)){ 38 | if(vertex == v) return true; 39 | set.add(v); 40 | queue.enqueue(v); //将顶点加入队列,按照入队列的顺序处理。 41 | } 42 | } 43 | } 44 | return false; 45 | } 46 | } 47 | public static void connect(GraphVertex v1, GraphVertex v2){ 48 | v1.connections.add(v2); 49 | } 50 | } 51 | ``` 52 | -------------------------------------------------------------------------------- /leetcode/Offer/Question4_3.md: -------------------------------------------------------------------------------- 1 | # Question4_3 2 | 3 | #### Solution 4 | * 使用递归插入,每次选中中间的变量作为root 5 | ```Java 6 | public static TreeNode arrToTree(Integer[] arr, int low, int high){ 7 | if(low > high) return null; //测试终止的条件 8 | int mid = (high - low) / 2 + low; //选作root的结点 9 | TreeNode root = new TreeNode(arr[mid]); 10 | root.left = arrToTree(arr, low, mid - 1); //递归获得左右子结点。 11 | root.right = arrToTree(arr, mid + 1, high); 12 | return root; 13 | } 14 | public class Question4_3 { 15 | public static void main(String[] args) { 16 | Integer[] arr = new Integer[100]; 17 | for(int i = 0; i < 100; i++) 18 | arr[i] = i; 19 | TreeNode root = OfferTree.arrToTree(arr, 0, arr.length - 1); 20 | System.out.println(root.v); 21 | System.out.println(root.left.v); 22 | System.out.println(root.right.v); 23 | System.out.println(root.left.left.v); 24 | } 25 | } 26 | ``` 27 | -------------------------------------------------------------------------------- /leetcode/Offer/Question4_5.md: -------------------------------------------------------------------------------- 1 | # Question4_5 2 | 3 | #### Solution 4 | ```Java 5 | public static boolean checkBSTDFS(TreeNode root){ 6 | if(root == null) return true; 7 | boolean lresult = true; //此处必须要初始化!不然编译不过!而且必须要初始化成true,不然要加更多的判断条件。 8 | boolean rresult = true; 9 | if(root.left != null){ 10 | if(root.left.v > root.v) 11 | return false; 12 | lresult = checkBSTDFS(root.left); 13 | } 14 | if(root.right != null){ 15 | if(root.right.v <= root.v) 16 | return false; 17 | rresult = checkBSTDFS(root.right); 18 | } 19 | return lresult && rresult; //逻辑判断的与&&,同时要注意当使用两个布尔型进行判断时最好初始化成true。 20 | } 21 | public static boolean checkBSTBFS(TreeNode root){ 22 | if(root == null) return true; 23 | Queue queue = new Queue<>(); 24 | queue.enqueue(root); 25 | while(!queue.isEmpty()){ 26 | TreeNode node = queue.dequeue(); 27 | if(node.left != null){ 28 | if(node.left.v > node.v) return false; 29 | queue.enqueue(node.left); 30 | } 31 | if(node.right != null){ 32 | if(node.right.v <= node.v) return false; 33 | queue.enqueue(node.right); 34 | } 35 | } 36 | return true; 37 | } 38 | ``` 39 | -------------------------------------------------------------------------------- /leetcode/Offer/Question4_6.md: -------------------------------------------------------------------------------- 1 | # Question4_6 2 | 3 | #### Solution 4 | ```Java 5 | public static boolean hasChild(TreeNode root, TreeNode node){ 6 | if(root == null) return false; 7 | if(root == node) return true; 8 | return hasChild(root.left, node) || hasChild(root.right, node); 9 | } 10 | private static TreeNode closestSameNode(TreeNode root, TreeNode p, TreeNode q){ 11 | if(root == null) return null; 12 | boolean findp = hasChild(root, p); 13 | boolean findq = hasChild(root, q); 14 | if(findp && findq){ 15 | TreeNode resultLeft = closestSameNode(root.left, p, q); 16 | TreeNode resultRight = closestSameNode(root.right, p, q); 17 | if(resultLeft == null && resultRight == null) 18 | return root; 19 | else if (resultLeft == null && resultRight != null) 20 | return resultRight; 21 | else{ 22 | return resultLeft; 23 | } 24 | }else { 25 | return null; 26 | } 27 | } 28 | public static TreeNode commonAncester(TreeNode root, TreeNode p, TreeNode q){ 29 | if(!hasChild(root, p) && hasChild(root, q)) return null; //确定两个节点均在树中。 30 | return closestSameNode(root, p, q); 31 | } 32 | ``` 33 | -------------------------------------------------------------------------------- /leetcode/Offer/Question4_7.md: -------------------------------------------------------------------------------- 1 | # Question4_7 2 | 3 | #### Solution 4 | ```Java 5 | public static boolean hasChild(TreeNode root, TreeNode node){ 6 | if(root == null) return false; 7 | if(root == node) return true; 8 | return hasChild(root.left, node) || hasChild(root.right, node); 9 | } 10 | //从根节点往下找,之前的一定都是能找到的,只是在缩小范围。 11 | public static TreeNode closestSameNode(TreeNode root, TreeNode p, TreeNode q){ 12 | if(root == null) return null; 13 | boolean findp = hasChild(root, p); 14 | boolean findq = hasChild(root, q); 15 | if(findp && findq){ 16 | TreeNode resultLeft = closestSameNode(root.left, p, q); 17 | TreeNode resultRight = closestSameNode(root.right, p, q); 18 | if(resultLeft == null && resultRight == null) 19 | return root; 20 | else if (resultLeft == null && resultRight != null) 21 | return resultRight; 22 | else{ 23 | return resultLeft; 24 | } 25 | }else { 26 | return null; 27 | } 28 | } 29 | ``` 30 | -------------------------------------------------------------------------------- /leetcode/Offer/Question4_8.md: -------------------------------------------------------------------------------- 1 | # Question4_8 2 | 3 | #### Solution 4 | * 使用SubString 5 | ```Java 6 | public static void preOrder(TreeNode node, StringBuilder sb){ 7 | if(node == null) return; 8 | sb.append(node.v); 9 | preOrder(node.left, sb); 10 | preOrder(node.right, sb); 11 | } 12 | public static boolean isSubTree(TreeNode root, TreeNode node){ 13 | StringBuilder sbRoot = new StringBuilder(); 14 | preOrder(root, sbRoot); 15 | StringBuilder sbNode = new StringBuilder(); 16 | preOrder(node, sbNode); 17 | return sbRoot.toString().contains(sbNode.toString()); 18 | } 19 | ``` 20 | 21 | * 传统的递归调用检查 22 | ```Java 23 | public static boolean matchTree(TreeNode node1, TreeNode node2){ 24 | boolean result = true; 25 | if(node1 == null && node2 == null) return true; 26 | if(node1 != node2) 27 | result = false; 28 | return result && matchTree(node1.left, node2.left) && 29 | matchTree(node1.right, node2.right); 30 | } 31 | public static boolean checkSubtree(TreeNode root, TreeNode node){ 32 | if(root == null || node == null) return false; 33 | boolean mid = matchTree(root, node); 34 | boolean left = checkSubtree(root.left, node); 35 | boolean right = checkSubtree(root.right, node); 36 | return mid || left || right; 37 | } 38 | ``` 39 | -------------------------------------------------------------------------------- /leetcode/Offer/Question5_1.md: -------------------------------------------------------------------------------- 1 | # Question5_1 2 | 3 | #### Solution 4 | ```Java 5 | public class Question5_1 { 6 | public static int update(int m, int n, int j, int i){ 7 | int allOnes = ~0; 8 | int left = allOnes << (j + 1); 9 | int right = ~(allOnes << i); 10 | int mask = left | right; 11 | int clearM = m & mask; 12 | int movedN = n << i; 13 | return clearM | movedN; 14 | } 15 | public static void main(String[] args) { 16 | System.out.println(Integer.toBinaryString(update(0B10000000000, 0B10011, 6, 2))); 17 | } 18 | } 19 | ``` 20 | -------------------------------------------------------------------------------- /leetcode/Offer/Question5_2.md: -------------------------------------------------------------------------------- 1 | # Question5_2 2 | 3 | #### Solution 4 | ```Java 5 | public class Question5_2 { 6 | public static String doubleToString(double d){ 7 | if(d <= 0 || d >= 1) return "ERROR"; 8 | StringBuilder binary = new StringBuilder(); 9 | int counter = 0; 10 | binary.append('.'); 11 | while(d != 0){ 12 | counter++; 13 | if(counter > 32) return "ERROR"; 14 | int append = d * 2 >= 1 ? 1:0; 15 | binary.append(append); 16 | d = d * 2 - append; 17 | } 18 | return binary.toString(); 19 | } 20 | public static void main(String[] args) { 21 | System.out.println(doubleToString(0.525d)); 22 | System.out.println(Float.toHexString(0.25f)); 23 | } 24 | } 25 | ``` 26 | -------------------------------------------------------------------------------- /leetcode/Offer/Question5_3.md: -------------------------------------------------------------------------------- 1 | # Question5_3 2 | 3 | #### Solution 4 | ```Java 5 | public class Question5_3 { 6 | public static int getClosestBigger(int n){ 7 | int c = n; 8 | int p = 0; 9 | int q = 0; 10 | while(c != 0 && ((c & 1) == 0)){ 11 | q++; 12 | c >>= 1; 13 | } 14 | p = q; 15 | while((c & 1) == 1){ 16 | p ++; 17 | c >>= 1; 18 | } 19 | if(p >= 31) return -1; 20 | n |= (1 << p); 21 | n &= ~((1 << p) - 1); 22 | n |= (1 << (p - q - 1)) - 1; 23 | return n; 24 | } 25 | public static int getClosestSmall(int n){ 26 | int c = n; 27 | int p = 0; 28 | int q = 0; 29 | while((c & 1) == 1){ 30 | q ++; 31 | c >>= 1; 32 | } 33 | p = q; 34 | while(c != 0 && (c & 1) == 0){ 35 | p ++; 36 | c >>= 1; 37 | } 38 | n &= ~((1 << (p + 1)) - 1); 39 | System.out.println(Integer.toBinaryString(~((1 << (p - q)) - 1))); 40 | int mask = ((1 << p) - 1) & ~((1 << (p - q - 1)) - 1); 41 | n |= mask; 42 | return n; 43 | } 44 | public static void main(String[] args) { 45 | // System.out.println(getClosestBigger(Integer.MAX_VALUE)); 46 | System.out.println(getClosestSmall(11)); 47 | } 48 | } 49 | ``` 50 | -------------------------------------------------------------------------------- /leetcode/Offer/Question5_5.md: -------------------------------------------------------------------------------- 1 | # Question5_5 2 | 3 | #### Solution 4 | ```Java 5 | public class Question5_5 { 6 | public static int bitNeedSwap(int a, int b){ 7 | int c = a ^ b; 8 | int count = 0; 9 | while(c != 0){ 10 | count = (c & 1) == 1 ? count+1:count; 11 | c >>= 1; 12 | } 13 | return count; 14 | } 15 | public static int bitNeedSwap1(int a, int b){ 16 | int count = 0; 17 | int c = a ^ b; 18 | while(c != 0){ 19 | c &= (c - 1); //用于将最后一位1转换成0. 20 | count ++; 21 | } 22 | return count; 23 | } 24 | public static void main(String[] args) { 25 | System.out.println(bitNeedSwap1(0b1001101011, 0b1010100111)); 26 | } 27 | } 28 | ``` 29 | -------------------------------------------------------------------------------- /leetcode/Offer/Question5_6.md: -------------------------------------------------------------------------------- 1 | # Question5_6 2 | 3 | #### Solution 4 | ```Java 5 | public class Question5_6 { 6 | public static int swapEvenOdd(int n){ 7 | return (((n & 0xAAAAAAAA) << 1) | ((n & 0x55555555) >> 1)); 8 | } 9 | public static void main(String[] args) { 10 | System.out.println(Integer.toBinaryString(swapEvenOdd(0B101010101010101))); 11 | } 12 | } 13 | ``` 14 | -------------------------------------------------------------------------------- /leetcode/Offer/Question9_1.md: -------------------------------------------------------------------------------- 1 | # Question9_1 2 | 3 | #### Solution 4 | ```Java 5 | public class Question9_1 { 6 | public static int countWays(int n){ //从结束向开头递归,对于n,都有三种可能,即最后一步是通过+3, +2, +1到达的,在此处进入递归。 7 | if(n < 0) 8 | return 0; 9 | else if (n == 0) 10 | return 1; 11 | else{ 12 | return countWays(n - 1) + countWays(n - 2) + countWays(n - 3); 13 | } 14 | } 15 | public static int countWaysDP(int n){ //通过动态规划,将已经计算过的值缓存起来,而后的一些结果是基于原来的一些结果,所以将这些值缓存起来加加快速度。 16 | //尤其考虑到一些值,每次都通过递归进行计算,所以缓存起来减少了递归的次数。 17 | int[] dp = new int[n + 1]; 18 | for(int i = 0; i < n + 1; i++) 19 | dp[i] = -1; 20 | return countWaysDP(n, dp); 21 | } 22 | public static int countWaysDP(int n, int[] dp){ 23 | if(n < 0) 24 | return 0; 25 | else if(n == 0){ 26 | return 1; 27 | }else if(dp[n] != -1){ 28 | return dp[n]; 29 | }else{ 30 | dp[n] = countWaysDP(n - 1, dp) + countWaysDP(n - 2, dp) + countWaysDP(n - 3, dp); 31 | return dp[n]; 32 | } 33 | } 34 | public static void main(String[] args) { 35 | System.out.println(countWaysDP(3)); 36 | } 37 | } 38 | ``` 39 | -------------------------------------------------------------------------------- /leetcode/Offer/Question9_10.md: -------------------------------------------------------------------------------- 1 | # Question9_10 2 | 3 | #### Solution 4 | * 放箱子问题, 未经过测试 5 | ```Java 6 | package ca.mcmaster.offer; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | public class Question9_10 { 12 | public static class Box{ 13 | int w; 14 | int h; 15 | int d; 16 | public Box(int w, int h, int d){ 17 | this.w = w; 18 | this.h = h; 19 | this.d = d; 20 | } 21 | } 22 | public static void getPossibleOrders(Box[] box, Box bottom, ArrayList order, boolean[] used, List> result){ 23 | if(order.size() == box.length){ 24 | result.add(order); 25 | return; 26 | } 27 | for(int i = 0; i < used.length; i++){ 28 | if(!used[i]){ 29 | boolean[] cloneUsed = used.clone(); 30 | cloneUsed[i] = true; 31 | ArrayList copyBoxs = new ArrayList<>(); 32 | for(Box b : order) 33 | copyBoxs.add(b); 34 | if(copyBoxs.size() == 0 || canPutAbove(bottom, box[i])){ 35 | copyBoxs.add(box[i]); 36 | getPossibleOrders(box, box[i], copyBoxs, cloneUsed, result); 37 | }else{ 38 | result.add(order); 39 | return; 40 | } 41 | } 42 | } 43 | } 44 | private static boolean canPutAbove(Box b1, Box b2){ 45 | if(b1.w > b2.w && b1.h > b2.h && b1.d > b2.d) 46 | return true; 47 | return false; 48 | } 49 | } 50 | 51 | ``` 52 | -------------------------------------------------------------------------------- /leetcode/Offer/Question9_2.md: -------------------------------------------------------------------------------- 1 | # Question9_2 2 | 3 | #### Solution 4 | ```Java 5 | public class Question9_2 { 6 | public static class Point{ 7 | int x; 8 | int y; 9 | public Point(int x, int y){ 10 | this.x = x; 11 | this.y = y; 12 | } 13 | public void print(){ 14 | System.out.println(x + " " + y); 15 | } 16 | } 17 | public static boolean getPath(int x, int y, List path){ 18 | Point p = new Point(x, y); 19 | path.add(p); 20 | if(x == 0 && y == 0) //已经在原点 21 | return true; 22 | boolean success = false; 23 | if(x > 0 && isFree(x - 1, y)){ //尝试向上移动 24 | success = getPath(x - 1, y, path); 25 | } 26 | if(!success && y > 0 && isFree(x, y - 1)){ 27 | success = getPath(x, y - 1, path); 28 | } 29 | if(!success) 30 | path.add(p); 31 | return success; 32 | } 33 | public static boolean isFree(int x, int y){ 34 | if(x == 2 && y == 3) 35 | return false; 36 | return true; 37 | } 38 | public static void main(String[] args) { 39 | List path = new ArrayList<>(); 40 | System.out.println(getPath(2, 3, path)); 41 | for(Point p : path) 42 | p.print(); 43 | } 44 | } 45 | ``` 46 | -------------------------------------------------------------------------------- /leetcode/Offer/Question9_3.md: -------------------------------------------------------------------------------- 1 | # Question9_3 2 | 3 | #### Solution 4 | * 这一题借鉴了二分法。 5 | ```Java 6 | public class Question9_3 { 7 | public static int getMagic(int[] nums){ 8 | return getMagic(nums, 0, nums.length - 1); 9 | } 10 | public static int getMagic(int[] nums, int low, int high){ 11 | int mid = (high - low) / 2 + low; 12 | int midNum = nums[mid]; 13 | if(mid == midNum) 14 | return mid; 15 | if(midNum < mid){ 16 | return getMagic(nums, mid, high); 17 | }else{ 18 | return getMagic(nums, low, mid); 19 | } 20 | } 21 | public static void main(String[] args) { 22 | System.out.println(getMagic(new int[]{-10, -5, -1, 1, 2, 3, 4, 7, 9, 12, 13})); 23 | } 24 | } 25 | ``` 26 | -------------------------------------------------------------------------------- /leetcode/Offer/Question9_7.md: -------------------------------------------------------------------------------- 1 | # Question9_7 2 | 3 | #### Solution 4 | * 对于当前的像素,如果颜色和ocolor相同,就尝试将其上下左右全部填充。 5 | * 如果当前的像素和ocolor不同,则在此处停止回归(即不再继续填充颜色)。 6 | ```Java 7 | public class Question9_7 { 8 | public enum Color{ 9 | RED, 10 | GREEN, 11 | BLUE 12 | } 13 | public static void fillColor(Color[][] screen, int x, int y, Color ncolor){ 14 | fillColor(screen, x, y, screen[x][y], ncolor); 15 | } 16 | public static void fillColor(Color[][] screen, int x, int y, Color ocolor, Color ncolor){ 17 | if(x < 0 || y < 0 || x >= screen[0].length || y >= screen.length){ 18 | return; 19 | }else{ 20 | if(ocolor == screen[y][x]){ 21 | screen[y][x] = ncolor; 22 | fillColor(screen, x - 1, y, ocolor, ncolor); //left 23 | fillColor(screen, x, y - 1, ocolor, ncolor); //up 24 | fillColor(screen, x + 1, y, ocolor, ncolor); //right 25 | fillColor(screen, x, y + 1, ocolor, ncolor); //down 26 | } 27 | } 28 | } 29 | public static void main(String[] args) { 30 | Color[][] screen = new Color[10][10]; 31 | // for(int i = 0; i < 10; i++){ 32 | // screen[3][i] = Color.BLUE; 33 | // } 34 | fillColor(screen, 8, 8, Color.GREEN); 35 | for(int i = 0; i < screen.length; i++){ 36 | for (int j = 0; j < screen[0].length; j++) { 37 | System.out.print(screen[i][j]); 38 | } 39 | System.out.println(); 40 | } 41 | } 42 | } 43 | ``` 44 | -------------------------------------------------------------------------------- /leetcode/Offer/Question9_8.md: -------------------------------------------------------------------------------- 1 | # Question9_8 2 | 3 | #### Solution 4 | * 参考9_1 5 | ```Java 6 | public class Question9_8 { 7 | public static int getCountDP(int n, int[] dp){ 8 | if(n < 0) 9 | return 0; 10 | else if(n == 0) 11 | return 1; 12 | else if(dp[n] != 0){ 13 | return dp[n]; 14 | }else{ 15 | dp[n] = getCountDP(n - 25, dp) + getCountDP(n - 10, dp) + getCountDP(n - 5, dp) + getCountDP(n - 1, dp); 16 | return dp[n]; 17 | } 18 | } 19 | public static int getCountDP(int n){ 20 | int[] dp = new int[n + 1]; 21 | dp[0] = 0; 22 | return getCountDP(n, dp); 23 | } 24 | public static void main(String[] args) { 25 | System.out.println(getCountDP(5)); 26 | } 27 | } 28 | ``` 29 | -------------------------------------------------------------------------------- /leetcode/Offer/Question9_9.md: -------------------------------------------------------------------------------- 1 | # Question9_9 2 | 3 | #### Solution 4 | * 八皇后问题,在8*8的棋盘上放置八个皇后,要使得所有的皇后均不在同一行,同一列,同一对角线。 5 | * 从第一行开始,慢慢向下将所有的棋盘填满,检查所有的可能性,对于每一行进行递归放置调用。 6 | ```Java 7 | public class Question9_9 { 8 | public static int count = 0; 9 | public static void eightQueue(int[][] dp, int row){ //dp[]: index: row; value = column 10 | if(row == 8){ 11 | System.out.println("Number: " + ++count); 12 | for(int i = 0; i < 8; i++){ 13 | for(int j = 0; j < 8; j++){ 14 | System.out.print(dp[i][j] + " "); 15 | } 16 | System.out.println(); 17 | } 18 | return; 19 | } 20 | int [][] clone = dp.clone(); 21 | for(int i = 0 ; i < 8; i++){ 22 | clone[row][i] = 1; 23 | if(isSafe(clone, row, i)) 24 | eightQueue(clone, row + 1); 25 | clone[row][i] = 0; 26 | } 27 | } 28 | private static boolean isSafe(int[][] dp, int row, int column){ 29 | if(row >= 1){ 30 | for(int i = row - 1; i >=0; i--) 31 | if(dp[i][column] == 1) return false; 32 | } 33 | int tempRow = row; 34 | int tempColumn = column; 35 | while(tempRow > 0 && tempColumn > 0){ //left up 36 | if(dp[--tempRow][--tempColumn] == 1) return false; 37 | } 38 | tempRow = row; 39 | tempColumn = column; 40 | while(tempRow > 0 && tempColumn < 7){ 41 | if(dp[--tempRow][++tempColumn] == 1) return false; 42 | } 43 | return true; 44 | } 45 | public static void main(String[] args) { 46 | int[][] dp = new int[8][8]; 47 | eightQueue(dp, 0); 48 | } 49 | } 50 | ``` 51 | -------------------------------------------------------------------------------- /leetcode/Offer/程序员面试金典 第5版.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Seanforfun/Algorithm-and-Leetcode/4ea49415a05d1c6ed54a384841fa46f86c2810e2/leetcode/Offer/程序员面试金典 第5版.pdf --------------------------------------------------------------------------------