├── README.md ├── SUMMARY.md ├── chapter_Arrays&Strings ├── README.md └── leetcode │ ├── 2Keyboards.java │ ├── LRUCache.java │ ├── StrobogrammaticNumber.java │ ├── StrobogrammaticNumberTwo.java │ ├── addAndSearchWord.java │ ├── addBinary.java │ ├── addTwoNumber.java │ ├── basicCalculatorTwo.java │ ├── beautifulArrangementTwo.java │ ├── bulbSwitcher.java │ ├── canAttendMeetings.java │ ├── canAttendMeetingsTwo.java │ ├── cloneGraph.java │ ├── combinationSum.java │ ├── combinationSumTwo.java │ ├── containDuplicates.java │ ├── containDuplicatesThree.java │ ├── containDuplicatesTwo.java │ ├── countAndSay.java │ ├── countNodes.java │ ├── countSmallerNumbers.java │ ├── createMaximumNumber.java │ ├── decodedWays.java │ ├── encodeTinyUrl.java │ ├── excelSheet.java │ ├── expressionAddOperators.java │ ├── findAllDuplicates.java │ ├── findDisappearedNumbers.java │ ├── findKPairsSmallestSum.java │ ├── findMedianSortedArrays.java │ ├── findMinimunInRotation.java │ ├── findTheDuplicateNumber.java │ ├── firstUnique.java │ ├── flattenNestedList.java │ ├── fourSum.java │ ├── fourSumTwo.java │ ├── friendCircle.java │ ├── gasStation.java │ ├── generateParenthesis.java │ ├── groupAnagrams.java │ ├── guessNumber.java │ ├── happyNumber.java │ ├── imageSmoother.java │ ├── increasingTripletSubsequence.java │ ├── intToEnglish.java │ ├── intersectionOfTwoArrays.java │ ├── intersectionOfTwoArraysTwo.java │ ├── isPalindrome.java │ ├── islandPerimeter.java │ ├── kthLargestElement.java │ ├── kthSmallestElementInMatrix.java │ ├── largestIncreasingPath.java │ ├── largestReactrangeArea.java │ ├── lengthOfLongestSubstring.java │ ├── lengthOfLongestSubstringTwo.java │ ├── letterCombination.java │ ├── linkedListCycle.java │ ├── longestConsecutive.java │ ├── longestPalindrome.java │ ├── longestValidParentheses.java │ ├── majorityElement.java │ ├── maxAreaContainer.java │ ├── maxProductSubArray.java │ ├── maxProductThreeNumber.java │ ├── maxProfit.java │ ├── maxProfitTwo.java │ ├── maxSubArrayLen.java │ ├── maximalReactangle.java │ ├── maximumSubarray.java │ ├── mergeIntervals.java │ ├── mergeKSortedLists.java │ ├── mergeSortedArray.java │ ├── mergeSortedList.java │ ├── miniStack.java │ ├── minimumWindowSubstring.java │ ├── missingNumber.java │ ├── missingRanges.java │ ├── moveZeros.java │ ├── multipleStrings.java │ ├── nextGreaterElementThree.java │ ├── numberOfDigitOne.java │ ├── numberOfIsland.java │ ├── oddEvenLinkedList.java │ ├── oneEditDistance.java │ ├── palindromeLinkedList.java │ ├── palindromePartitioning.java │ ├── pascalTriangle.java │ ├── pascalTriangleTwo.java │ ├── permutation.java │ ├── permutationTwo.java │ ├── plusOne.java │ ├── powerOfThree.java │ ├── powerOfTwo.java │ ├── productExceptSelf.java │ ├── readNCharactersGivenRead4.java │ ├── readNCharactersGivenRead4Two.java │ ├── remove9.java │ ├── removeDuplicatedFromSortedArray.java │ ├── removeElement.java │ ├── removeInvalidParentheses.java │ ├── reverseInt.java │ ├── reverseString.java │ ├── reverseVowel.java │ ├── reverseWords.java │ ├── reverseWordsTwo.java │ ├── romanToInt.java │ ├── rotateImage.java │ ├── scrambleString.java │ ├── shuffleArray.java │ ├── skyline.java │ ├── slidingWindowMaximum.java │ ├── sortColors.java │ ├── sortedArrayToBST.java │ ├── sparseMatrix.java │ ├── spiralMatrix.java │ ├── sqrt.java │ ├── strStr.java │ ├── stringToInt.java │ ├── subarraySumEqualsK.java │ ├── subsets.java │ ├── subsetsTwo.java │ ├── summaryRanges.java │ ├── surroundedRegions.java │ ├── targetSum.java │ ├── threeSum.java │ ├── topKFrequent.java │ ├── trapWater.java │ ├── trie.java │ ├── twoSum.java │ ├── twoSumThree.java │ ├── twoSumTwo.java │ ├── uglyNumberTwo.java │ ├── uniquePath.java │ ├── uniquePathTwo.java │ ├── validAnagram.java │ ├── validNumber.java │ ├── validPalindrome.java │ ├── validParentheses.java │ ├── wordBreak.java │ ├── wordBreakTwo.java │ ├── wordSearch.java │ └── wordSearchTwo.java ├── chapter_Bit_Manipulation ├── README.md ├── cc150 │ ├── binaryToString.java │ └── insertion.java └── leetcode │ ├── singleNumber.java │ ├── singleNumberThree.java │ ├── singleNumberTwo.java │ └── sumOfTwo.java ├── chapter_DP ├── README.md ├── images │ ├── image1.jpeg │ ├── image10ruby.jpeg │ ├── image11java.jpeg │ ├── image12java.jpeg │ ├── image13java.png │ ├── image14ruby.jpeg │ ├── image2.jpeg │ ├── image3.jpeg │ ├── image4.jpeg │ ├── image5.jpeg │ ├── image6ruby.jpeg │ ├── image7ruby.jpeg │ ├── image8ruby.jpeg │ └── image9ruby.jpeg └── leetcode │ ├── .perfectSquares.java.swp │ ├── burstBallons.java │ ├── climbStairs.java │ ├── countingBits.java │ ├── houseRobber.java │ ├── maxProductSubArray.java │ ├── maxSubArray.java │ ├── onesAndZeros.java │ ├── perfectSquares.java │ ├── regularExpressionMatching.java │ ├── uniquePath.java │ └── uniquePathTwo.java ├── chapter_Graph └── README.md ├── chapter_Sort ├── 242. Valid Anagram.java └── README.md ├── chapter_Tree ├── .README.md.swp ├── README.md ├── images │ └── bst.jpg └── leetcode │ ├── .bstMaxPathSum.java.swp │ ├── balancedBinaryTree.java │ ├── bstIterator.java │ ├── bstLevelOrderTraversal.java │ ├── bstMaxPathSum.java │ ├── bstPaths.java │ ├── closestValue.java │ ├── closestValueTwo.java │ ├── countNodes.java │ ├── countUnivalSubtrees.java │ ├── deleteNode.java │ ├── findBottomLeftValue.java │ ├── findKthSmallest.java │ ├── flattenTree.java │ ├── implementTrie.java │ ├── inorder.java │ ├── inorderSuccessor.java │ ├── invertTree.java │ ├── isSameTree.java │ ├── kthLargestElement.java │ ├── largestValues.java │ ├── longestConsecutive.java │ ├── lowestCommonAncestor.java │ ├── lowestCommonAncestorBinary.java │ ├── maxDepth.java │ ├── minDepth.java │ ├── orderBuildTree.java │ ├── pathSum.java │ ├── pathSumThree.java │ ├── pathSumTwo.java │ ├── populatingNextRight.java │ ├── postorder.java │ ├── preorder.java │ ├── recoverBST.java │ ├── rightSideView.java │ ├── serializeTree.java │ ├── sortedArrayToBST.java │ ├── sortedListToBST.java │ ├── sumOfLeftLeaves.java │ ├── sumRootToLeafNums.java │ ├── symmetricTree.java │ ├── uniqueBST.java │ ├── uniqueBSTTwo.java │ ├── upsideDownBinaryTree.java │ ├── validBST.java │ ├── verifyPreorder.java │ ├── verticalOrder.java │ └── zigZagTraversal.java ├── chapter_linkedList ├── README.md └── leetcode │ ├── addTwoNumber.java │ ├── copyRandomPointer.java │ ├── mergeKSorted.java │ ├── mergeTwoSortedList.java │ └── swapPairs.java └── chapters └── .git_keeper /README.md: -------------------------------------------------------------------------------- 1 | # Practice an algorithm question every day 2 | 3 | 书籍:《每天练习一道算法题》 4 | 5 | ## 这是什么 6 | 7 | ## 8 | 9 | 10 | ## 目录 11 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | * [前言](README.md) 4 | 5 | ## 基础数据结构 6 | ### 数组 7 | ### 链表 8 | ### 堆栈 9 | ### 队列 10 | ### 树 11 | ### 图 12 | ### HashTable 13 | ### 字符串 14 | 15 | ## 算法思想 16 | ### 贪心算法 17 | ### 动态规划 18 | ### 二分法 19 | ### 分治算法 20 | ### 双指针 21 | ### 滑动窗口 22 | 23 | ## 其他主题 24 | ### 位运算 25 | ### 大数据 26 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/README.md: -------------------------------------------------------------------------------- 1 | ## 数列&字串符 2 | ## 基本定义 3 | ## 数列类问题实例 4 | 5 | #### [Leetcode 1 两数相加](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/twoSum.java) 6 | #### [Leetcode 66 加一](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/plusOne.java) 7 | #### [Leetcode 118 帕斯卡三角形](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/pascalTriangle.java) 8 | #### [Leetcode 169 主要元素](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/majorityElement.java) 9 | #### [Leetcode 217 检查重复元素](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/containDuplicates.java) 10 | #### [Leetcode 238 数列排除当前元素相乘](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/productExceptSelf.java) 11 | #### [Leetcode 283 移动零](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/moveZeros.java) 12 | ### 结合树类问题的数列类问题 13 | #### [树类问题链接](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/tree/master/chapter_Tree) 14 | #### [Leetcode 105 数列前序中序建造二分树](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/sortedArrayToBST.java) 15 | #### [Leetcode 108 正序数列转化为二分搜索树](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/orderBuildTree.java) 16 | 17 | ### 运用两个指针策略解决问题 18 | #### [Leetcode 11 最大盛水容器](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/maxAreaContainer.java) 19 | #### [Leetcode 42 收集雨水](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/trapWater.java) 20 | 21 | ### 结合动态规划类问题的数列类问题 22 | #### [Leetcode 121 股票最大收益](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/maxProfit.java) 23 | #### [Leetcode 122 股票最大收益 II](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_Arrays&Strings/leetcode/maxProfitTwo.java) 24 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/2Keyboards.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSteps(int n) { 3 | int [] dp = new int [n+1]; 4 | for(int i=2; i<=n; i++){ 5 | dp[i] = i; 6 | for(int j=i/2; j>1; j--){ 7 | if(i%j==0){ 8 | dp[i] = dp[j] + i/j; 9 | break; 10 | } 11 | } 12 | } 13 | return dp[n]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/LRUCache.java: -------------------------------------------------------------------------------- 1 | class LRUCache { 2 | class DLinkedNode { 3 | int key; 4 | int value; 5 | DLinkedNode pre; 6 | DLinkedNode post; 7 | } 8 | // always add node to the right of the head 9 | private void addNode(DLinkedNode node){ 10 | node.pre = head; 11 | node.post = head.post; 12 | head.post.pre = node; 13 | head.post = node; 14 | } 15 | 16 | private void removeNode(DLinkedNode node){ 17 | DLinkedNode pre = node.pre; 18 | DLinkedNode post = node.post; 19 | pre.post = post; 20 | post.pre = pre; 21 | } 22 | 23 | private void moveToHead(DLinkedNode node){ 24 | this.removeNode(node); 25 | this.addNode(node); 26 | } 27 | 28 | private DLinkedNode popTail(){ 29 | DLinkedNode res = tail.pre; 30 | this.removeNode(res); 31 | return res; 32 | } 33 | 34 | HashMap cache = new HashMap<>(); 35 | DLinkedNode head; 36 | DLinkedNode tail; 37 | int count; 38 | int capacity; 39 | 40 | public LRUCache(int capacity) { 41 | this.count = 0; 42 | this.capacity = capacity; 43 | this.head = new DLinkedNode(); 44 | head.pre = null; 45 | this.tail = new DLinkedNode(); 46 | tail.post = null; 47 | 48 | head.post = tail; 49 | tail.pre = head; 50 | } 51 | 52 | public int get(int key) { 53 | DLinkedNode node = cache.get(key); 54 | if(node == null) return -1; 55 | this.moveToHead(node); 56 | return node.value; 57 | } 58 | 59 | public void put(int key, int value) { 60 | DLinkedNode node = cache.get(key); 61 | if(node==null){ 62 | DLinkedNode newNode = new DLinkedNode(); 63 | newNode.key = key; 64 | newNode.value = value; 65 | this.cache.put(key, newNode); 66 | this.addNode(newNode); 67 | count++; 68 | if(count > capacity){ 69 | DLinkedNode tail = this.popTail(); 70 | this.cache.remove(tail.key); 71 | count--; 72 | } 73 | }else{ 74 | node.value = value; 75 | this.moveToHead(node); 76 | } 77 | } 78 | } 79 | 80 | /** 81 | * Your LRUCache object will be instantiated and called as such: 82 | * LRUCache obj = new LRUCache(capacity); 83 | * int param_1 = obj.get(key); 84 | * obj.put(key,value); 85 | */ 86 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/StrobogrammaticNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isStrobogrammatic(String num) { 3 | for(int i=0, j=num.length()-1; i<=j; i++, j--){ 4 | if(!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j))) 5 | return false; 6 | } 7 | return true; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/StrobogrammaticNumberTwo.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List findStrobogrammatic(int n) { 3 | return helper(n, n); 4 | } 5 | 6 | Listhelper(int n, int m){ 7 | if(n == 0) return new ArrayList(Arrays.asList("")); 8 | if(n == 1) return new ArrayList(Arrays.asList("0", "1", "8")); 9 | List list = helper(n-2, m); 10 | List res = new ArrayList<>(); 11 | 12 | for(int i=0; i= 0 || j>=0){ 8 | int sum = carry; 9 | if(j>=0) sum += b.charAt(j--) - '0'; 10 | if(i>=0) sum += a.charAt(i--) - '0'; 11 | sb.append(sum % 2); 12 | carry = sum / 2; 13 | } 14 | if(carry!=0) sb.append(carry); 15 | return sb.reverse().toString(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/addTwoNumber.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_Arrays&Strings/leetcode/addTwoNumber.java -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/basicCalculatorTwo.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int calculate(String s) { 3 | int len = s.length(); 4 | if(len==0 || s == null) return 0; 5 | Stack stack = new Stack<>(); 6 | int num = 0; 7 | char sign = '+'; 8 | for(int i=0; i1) 8 | k--; 9 | } 10 | return res; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/bulbSwitcher.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int bulbSwitch(int n) { 3 | return (int)Math.sqrt(n); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/canAttendMeetings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * public class Interval { 4 | * int start; 5 | * int end; 6 | * Interval() { start = 0; end = 0; } 7 | * Interval(int s, int e) { start = s; end = e; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean canAttendMeetings(Interval[] intervals) { 12 | Arrays.sort(intervals, new Comparator(){ 13 | public int compare(Interval a, Interval b) { 14 | return a.start - b.start; 15 | } 16 | }); 17 | 18 | for(int i=1; i neighbors; 6 | * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } 7 | * }; 8 | */ 9 | public class Solution { 10 | public UndirectedGraphNode cloneGraph(UndirectedGraphNode graph) { 11 | if(graph==null) return null; 12 | Map map = new HashMap<>(); 13 | return DFS(graph, map); 14 | } 15 | 16 | private UndirectedGraphNode DFS(UndirectedGraphNode graph, Map map){ 17 | if(map.containsKey(graph)) { 18 | return map.get(graph); 19 | } 20 | UndirectedGraphNode graphCopy = new UndirectedGraphNode(graph.label); 21 | map.put(graph, graphCopy); 22 | for(UndirectedGraphNode neighbor : graph.neighbors){ 23 | graphCopy.neighbors.add(DFS(neighbor, map)); 24 | } 25 | return graphCopy; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/combinationSum.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public List> combinationSum(int[] candidates, int target) { 4 | List> ans = new ArrayList<>(); 5 | if (candidates.length ==0 || candidates == null) return ans; 6 | backtrack(candidates, ans, new ArrayList<>(), target, 0); 7 | return ans; 8 | } 9 | 10 | public void backtrack(int[] candidates, List> ans, List tempList, int remain, int start){ 11 | if (remain < 0) return; 12 | if (remain == 0) { 13 | ans.add(new ArrayList(tempList)); 14 | } else { 15 | for(int i=start; i> combinationSum2(int[] candidates, int target) { 4 | List> ans = new ArrayList<>(); 5 | Arrays.sort(candidates); 6 | backtrack(ans, new ArrayList<>(), 0, target, candidates); 7 | return ans; 8 | } 9 | 10 | public void backtrack(List> ans, List tempList, int curr, int target, int [] candidates){ 11 | if(target < 0) return; 12 | if(target == 0){ 13 | ans.add(new ArrayList(tempList)); 14 | }else{ 15 | for(int i=curr; i curr && candidates[i] == candidates[i-1]) continue; 17 | tempList.add(candidates[i]); 18 | backtrack(ans, tempList, i + 1, target - candidates[i], candidates); 19 | tempList.remove(tempList.size() - 1); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/containDuplicates.java: -------------------------------------------------------------------------------- 1 | public boolean containsDuplicate(int[] nums) { 2 | 3 | final Set distinct = new HashSet(); 4 | for(int num : nums) { 5 | if(distinct.contains(num)) { 6 | return true; 7 | } 8 | distinct.add(num); 9 | } 10 | return false; 11 | } 12 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/containDuplicatesThree.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_Arrays&Strings/leetcode/containDuplicatesThree.java -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/containDuplicatesTwo.java: -------------------------------------------------------------------------------- 1 | public boolean containsNearbyDuplicate(int[] nums, int k) { 2 | Set set = new HashSet(); 3 | for(int i = 0; i < nums.length; i++){ 4 | if(i > k) set.remove(nums[i-k-1]); 5 | if(!set.add(nums[i])) return true; 6 | } 7 | return false; 8 | } 9 | 10 | public boolean containsNearbyDuplicate(int[] nums, int k) { 11 | Map map = new HashMap(); 12 | for (int i = 0; i < nums.length; i++) { 13 | if (map.containsKey(nums[i])) { 14 | if (i - map.get(nums[i]) <= k) return true; 15 | } 16 | map.put(nums[i], i); 17 | } 18 | return false; 19 | } 20 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/countAndSay.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String countAndSay(int n) { 3 | String str = "1"; 4 | while(--n > 0){ 5 | str = helper(str); 6 | } 7 | return str; 8 | } 9 | 10 | public String helper(String str){ 11 | StringBuilder sb = new StringBuilder(); 12 | int pos = 0; 13 | while(pos < str.length()){ 14 | int count = 1; 15 | while(pos + 1 < str.length() && str.charAt(pos) == str.charAt(pos + 1)){ 16 | count++; 17 | pos++; 18 | } 19 | sb.append(count + "" + str.charAt(pos)); 20 | pos++; 21 | } 22 | return sb.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/countNodes.java: -------------------------------------------------------------------------------- 1 | //Source: https://leetcode.com/problems/count-complete-tree-nodes/#/solutions 2 | 3 | public class Solution { 4 | public int height(TreeNode root){ 5 | return root==null? -1 : 1+ height(root.left); 6 | } 7 | public int countNodes(TreeNode root){ 8 | int h = height(root); 9 | return h < 0 ? 0 : height(root.right)==h-1 ? (1< countSmaller(int[] nums) { 14 | Integer [] result = new Integer [nums.length]; 15 | Node root = null; 16 | for(int i=nums.length - 1; i>=0; i--){ 17 | root = insert(nums[i], root, result, i, 0); 18 | } 19 | return Arrays.asList(result); 20 | } 21 | 22 | private Node insert(int num, Node node, Integer[] result, int i, int preSum){ 23 | if (node == null) { 24 | node = new Node(num, 0); 25 | result[i] = preSum; 26 | } else if (node.val == num) { 27 | node.dup++; 28 | result[i] = preSum + node.sum; 29 | } else if (node.val > num) { 30 | node.sum ++; 31 | node.left = insert(num, node.left, result, i, preSum); 32 | } else { 33 | node.right = insert(num, node.right, result, i, preSum + node.dup + node.sum); 34 | } 35 | return node; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/createMaximumNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] maxNumber(int[] nums1, int[] nums2, int k) { 3 | int n = nums1.length; 4 | int m = nums2.length; 5 | int[] ans = new int[k]; 6 | for (int i = Math.max(0, k - m); i <= k && i <= n; ++i) { 7 | int[] candidate = merge(maxArray(nums1, i), maxArray(nums2, k - i), k); 8 | if (greater(candidate, 0, ans, 0)) ans = candidate; 9 | } 10 | return ans; 11 | } 12 | private int[] merge(int[] nums1, int[] nums2, int k) { 13 | int[] ans = new int[k]; 14 | for (int i = 0, j = 0, r = 0; r < k; ++r) 15 | ans[r] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++]; 16 | return ans; 17 | } 18 | public boolean greater(int[] nums1, int i, int[] nums2, int j) { 19 | while (i < nums1.length && j < nums2.length && nums1[i] == nums2[j]) { 20 | i++; 21 | j++; 22 | } 23 | return j == nums2.length || (i < nums1.length && nums1[i] > nums2[j]); 24 | } 25 | public int[] maxArray(int[] nums, int k) { 26 | int n = nums.length; 27 | int[] ans = new int[k]; 28 | for (int i = 0, j = 0; i < n; ++i) { 29 | while (n - i + j > k && j > 0 && ans[j - 1] < nums[i]) j--; 30 | if (j < k) ans[j++] = nums[i]; 31 | } 32 | return ans; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/decodedWays.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numDecodings(String s) { 3 | int n = s.length(); 4 | if(n==0) return 0; 5 | int [] dp = new int [n+1]; 6 | dp[0] = 1; 7 | dp[1] = (s.charAt(0) == '0') ? 0 : 1; 8 | for (int i=2; i<=n; i++) { 9 | int first = Integer.valueOf(s.substring(i-1, i)); 10 | int second = Integer.valueOf(s.substring(i-2, i)); 11 | if(first >= 1 && first <= 9){ 12 | dp[i] = dp[i-1] + dp[i]; 13 | } 14 | if(second >= 10 && second <= 26){ 15 | dp[i] = dp[i-2] + dp[i]; 16 | } 17 | } 18 | return dp[n]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/encodeTinyUrl.java: -------------------------------------------------------------------------------- 1 | public class Codec { 2 | List urls = new ArrayList(); 3 | public String encode(String longUrl) { 4 | urls.add(longUrl); 5 | return String.valueOf(urls.size()-1); 6 | } 7 | 8 | public String decode(String shortUrl) { 9 | int index = Integer.valueOf(shortUrl); 10 | return (index 0){ 5 | n--; 6 | sb.insert(0, (char)('A' + n % 26)); 7 | n /=26; 8 | } 9 | return sb.toString(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/expressionAddOperators.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List addOperators(String num, int target) { 3 | Listres = new LinkedList<>(); 4 | if(num.length() == 0 || num == null) return res; 5 | long eval = 0; 6 | long multi = 0; 7 | helper(res, "", num, target, 0, eval, multi); 8 | return res; 9 | } 10 | 11 | public void helper(List result, String path, String num, int target, int pos, long eval, long multi){ 12 | if(pos == num.length()){ 13 | if(eval == target){ 14 | result.add(path); 15 | return; 16 | } 17 | } 18 | 19 | for(int i=pos; i findDuplicates(int[] nums) { 3 | List res = new ArrayList<>(); 4 | for(int i=0; i findDisappearedNumbers(int[] nums) { 3 | List ret = new ArrayList(); 4 | for(int i=0; i 0) 7 | nums[val] = -nums[val]; 8 | } 9 | for(int i=0; i 0) 11 | ret.add(i+1); 12 | } 13 | return ret; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/findKPairsSmallestSum.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public List kSmallestPairs(int[] nums1, int[] nums2, int k) { 4 | PriorityQueue pq = new PriorityQueue<>(); 5 | int m = nums1.length; int n = nums2.length; 6 | List res = new ArrayList<>(); 7 | if(nums1 == null || nums1.length == 0 || nums2 == null || nums.length == 0 || k<=0) return res; 8 | for(int j=0; j<=n-1; j++) pq.offer(new Tuple(0, j, nums1[0] + nums2[j])); 9 | for(int i=0; i { 21 | int x, y, val; 22 | public Tuple (int x, int y, int val){ 23 | this.x = x; 24 | this.y = y; 25 | this.val = val; 26 | } 27 | 28 | @Override 29 | public int compareTo(Tuple that) { 30 | return this.val - that.val; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/findMedianSortedArrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 | int m = nums1.length; 4 | int n = nums2.length; 5 | 6 | if (m > n) { 7 | return findMedianSortedArrays(nums2, nums1); 8 | } 9 | 10 | int i = 0, j = 0, imin = 0, imax = m, half = (m + n + 1) / 2; 11 | double maxLeft = 0, minRight = 0; 12 | while(imin <= imax){ 13 | i = (imin + imax) / 2; 14 | j = half - i; 15 | if(j > 0 && i < m && nums2[j - 1] > nums1[i]){ 16 | imin = i + 1; 17 | }else if(i > 0 && j < n && nums1[i - 1] > nums2[j]){ 18 | imax = i - 1; 19 | }else{ 20 | if(i == 0){ 21 | maxLeft = (double)nums2[j - 1]; 22 | }else if(j == 0){ 23 | maxLeft = (double)nums1[i - 1]; 24 | }else{ 25 | maxLeft = (double)Math.max(nums1[i - 1], nums2[j - 1]); 26 | } 27 | break; 28 | } 29 | } 30 | if((m + n) % 2 == 1){ 31 | return maxLeft; 32 | } 33 | if(i == m){ 34 | minRight = (double)nums2[j]; 35 | }else if(j == n){ 36 | minRight = (double)nums1[i]; 37 | }else{ 38 | minRight = (double)Math.min(nums1[i], nums2[j]); 39 | } 40 | 41 | return (double)(maxLeft + minRight) / 2; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/findMinimunInRotation.java: -------------------------------------------------------------------------------- 1 | int findMin(vector& nums) { 2 | int left = 0, right = nums.size() - 1; 3 | while(left < right) { 4 | if(nums[left] < nums[right]) 5 | return nums[left]; 6 | 7 | int mid = (left + right)/2; 8 | if(nums[mid] > nums[right]) 9 | left = mid + 1; 10 | else 11 | right = mid; 12 | } 13 | 14 | return nums[left]; 15 | } 16 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/findTheDuplicateNumber.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int findDuplicate(int[] nums) { 4 | if(nums.length > 1){ 5 | int slow = nums[0]; 6 | int fast = nums[nums[0]]; 7 | while(slow != fast){ 8 | slow = nums[slow]; 9 | fast = nums[nums[fast]]; 10 | } 11 | fast = 0; 12 | while(fast != slow){ 13 | fast = nums[fast]; 14 | slow = nums[slow]; 15 | } 16 | return slow; 17 | } 18 | return -1; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/firstUnique.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int firstUniqChar(String s) { 4 | int [] freq = new int [26]; 5 | for(int i=0; i getList(); 17 | * } 18 | */ 19 | public class NestedIterator implements Iterator { 20 | Stack stack= new Stack<>(); 21 | public NestedIterator(List nestedList) { 22 | for(int i=nestedList.size() - 1; i>=0; i--) 23 | stack.push(nestedList.get(i)); 24 | } 25 | 26 | @Override 27 | public Integer next() { 28 | return stack.pop().getInteger(); 29 | } 30 | 31 | @Override 32 | public boolean hasNext() { 33 | while(!stack.isEmpty()){ 34 | NestedInteger curr = stack.peek(); 35 | if(curr.isInteger()){ 36 | return true; 37 | } 38 | stack.pop(); 39 | for(int i=curr.getList().size() - 1; i>=0; i--){ 40 | stack.push(curr.getList().get(i)); 41 | } 42 | } 43 | return false; 44 | } 45 | } 46 | 47 | /** 48 | * Your NestedIterator object will be instantiated and called as such: 49 | * NestedIterator i = new NestedIterator(nestedList); 50 | * while (i.hasNext()) v[f()] = i.next(); 51 | */ 52 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/fourSum.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public List> fourSum(int[] nums, int target) { 4 | ArrayList> res = new ArrayList>(); 5 | int len = nums.length; 6 | if ( nums == null || len < 4) return res; 7 | Arrays.sort(nums); 8 | 9 | if(4*nums[0] > target || 4*nums[len - 1] < target) 10 | return res; 11 | 12 | int z; 13 | for(int i=0; i0 && z == nums[i-1]) continue; 16 | if(z + 3 * nums[len - 1] < target) continue; 17 | if(4 * z > target) continue; 18 | if(4 * z == target){ 19 | if(i + 3 < len && nums[i+3] == z) 20 | res.add(Arrays.asList(z, z, z, z)); 21 | break; 22 | } 23 | threeSum(nums, target - z, i+1, len-1, res, z); 24 | } 25 | return res; 26 | } 27 | public void threeSum(int [] nums, int target, int low, int high, ArrayList> fourSumList, int z1){ 28 | if(low + 1 >= high) 29 | return; 30 | int max = nums[high]; 31 | if(3*max < target || 3*nums[low] > target) return; 32 | int z; 33 | for(int i=low; ilow && z==nums[i-1]) continue; 36 | if(z + 2*max < target) continue; 37 | if(3*z > target) break; 38 | if(3*z == target){ 39 | if(i+1 < high && nums[i + 2] == z) 40 | fourSumList.add(Arrays.asList(z1, z, z, z)); 41 | break; 42 | } 43 | 44 | twoSum(nums, target - z, i + 1, high, fourSumList, z1, z); 45 | } 46 | } 47 | 48 | public void twoSum(int [] nums, int target, int low, int high, ArrayList> fourSumList, int z1, int z2){ 49 | if(low >= high) 50 | return; 51 | if(2*nums[low] > target || 2*nums[high] < target) return; 52 | int sum, x, i, j; 53 | i = low; 54 | j = high; 55 | while(i < j){ 56 | sum = nums[i] + nums[j]; 57 | if(sum == target){ 58 | fourSumList.add(Arrays.asList(z1, z2, nums[i], nums[j])); 59 | while(i < j && nums[i]== nums[i+1]) i++; 60 | while(i < j &&nums[j] == nums[j-1]) j--; 61 | i++; 62 | j--; 63 | 64 | }else if(sum > target){ 65 | j--; 66 | }else{ 67 | i++; 68 | } 69 | } 70 | return; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/fourSumTwo.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { 5 | Map map = new HashMap<>(); 6 | int sum; 7 | int res = 0; 8 | for(int i = 0; i rank[rootP]) { 28 | parent[rootP] = rootQ; 29 | } 30 | else { 31 | parent[rootQ] = rootP; 32 | if (rank[rootP] == rank[rootQ]) { 33 | rank[rootP]++; 34 | } 35 | } 36 | count--; 37 | } 38 | 39 | public int count() { 40 | return count; 41 | } 42 | } 43 | public int findCircleNum(int[][] M) { 44 | int n = M.length; 45 | UnionFind uf = new UnionFind(n); 46 | for (int i = 0; i < n ; i++) { 47 | for (int j = 0; j < n; j++) { 48 | if (M[i][j] == 1) uf.union(i, j); 49 | } 50 | } 51 | return uf.count(); 52 | } 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/gasStation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | int tank = 0; 4 | int sumGas = 0; 5 | int sumCost = 0; 6 | int start = 0; 7 | for(int i=0; i generateParenthesis(int n) { 4 | List result = new LinkedList<>(); 5 | if(n==0) return result; 6 | backtracking(result, new StringBuilder(), 0, 0, n); 7 | return result; 8 | } 9 | 10 | public void backtracking(List result, StringBuilder sb, int open, int close, int n){ 11 | if(open == n && close == n){ 12 | result.add(sb.toString()); 13 | return; 14 | } 15 | if(open < n){ 16 | sb.append("("); 17 | backtracking(result, sb, open + 1, close, n); 18 | sb.setLength(sb.length() - 1); 19 | } 20 | 21 | if(close < open){ 22 | sb.append(")"); 23 | backtracking(result, sb, open, close + 1, n); 24 | sb.setLength(sb.length() - 1); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/groupAnagrams.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public List> groupAnagrams(String[] strs) { 4 | if(strs == null || strs.length == 0) return new ArrayList>(); 5 | Map> map = new HashMap<>(); 6 | for(String str : strs){ 7 | char[] chars = str.toCharArray(); 8 | Arrays.sort(chars); 9 | String keyStr = String.valueOf(chars); 10 | if(!map.containsKey(keyStr)) map.put(keyStr, new ArrayList()); 11 | map.get(keyStr).add(str); 12 | } 13 | return new ArrayList> (map.values()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/guessNumber.java: -------------------------------------------------------------------------------- 1 | /* The guess API is defined in the parent class GuessGame. 2 | @param num, your guess 3 | @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 | int guess(int num); */ 5 | 6 | public class Solution extends GuessGame { 7 | public int guessNumber(int n) { 8 | int left = 1; 9 | int right = n; 10 | int mid = (right - left) / 2 + left; 11 | 12 | while(left < right){ 13 | mid = (right - left) / 2 + left; 14 | if(guess(mid) == 1){ 15 | left = mid + 1; 16 | }else{ 17 | right = mid; 18 | } 19 | } 20 | return left; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/happyNumber.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public boolean isHappy(int n) { 4 | Setloop = new HashSet<>(); 5 | int squareSum = 0; 6 | int remain = 0; 7 | while(loop.add(n)){ 8 | squareSum = 0; 9 | while(n > 0){ 10 | remain = n % 10; 11 | squareSum += remain * remain; 12 | n /= 10; 13 | } 14 | if(squareSum == 1) return true; 15 | else n = squareSum; 16 | } 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/imageSmoother.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] imageSmoother(int[][] M) { 3 | int sum; 4 | int count; 5 | int m = M.length; 6 | int n = M[0].length; 7 | int [][] ret = new int[m][n]; 8 | 9 | for(int i=0; i= 0 && i-1 < m && j-1 >=0 && j-1 < n){ 14 | count += 1; 15 | sum += M[i-1][j-1]; // cell0 16 | } 17 | if(i-1 >= 0 && i-1 < m){ 18 | count += 1; 19 | sum += M[i-1][j]; // cell1 20 | } 21 | if(i-1 >= 0 && i-1 < m && j+1 >=0 && j+1 < n){ 22 | count += 1; 23 | sum += M[i-1][j+1]; // cell2 24 | } 25 | if(j-1 >=0 && j-1 < n){ 26 | count += 1; 27 | sum += M[i][j-1]; //cell3 28 | } 29 | if(j+1 >=0 && j+1 < n){ 30 | count += 1; 31 | sum += M[i][j+1]; //cell4 32 | } 33 | if(i+1 >= 0 && i+1 < m && j-1 >=0 && j-1 < n){ 34 | count += 1; 35 | sum += M[i+1][j-1]; //cell5 36 | } 37 | if(i+1 >= 0 && i+1 < m){ 38 | count += 1; 39 | sum += M[i+1][j]; //cell6 40 | } 41 | if(i+1 >= 0 && i+1 < m && j+1 >=0 && j+1 < n){ 42 | count += 1; 43 | sum += M[i+1][j+1]; 44 | } 45 | sum += M[i][j]; //itself 46 | count+=1; 47 | ret[i][j] = sum / count; 48 | } 49 | } 50 | return ret; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/increasingTripletSubsequence.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public boolean increasingTriplet(int[] nums) { 4 | int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE; 5 | for(int n : nums){ 6 | if(n <= small){ 7 | small = n; 8 | } else if (n <= big) { 9 | big = n; 10 | } else { 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/intToEnglish.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private final String [] LESS_THAN_20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; 3 | private final String [] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; 4 | private final String [] THOUSANDS = {"", "Thousand", "Million", "Billion"}; 5 | public String numberToWords(int num) { 6 | if(num == 0) return "Zero"; 7 | String words = ""; 8 | int i = 0; 9 | while(num > 0) { 10 | if(num % 1000 > 0) 11 | words = helper(num % 1000) + THOUSANDS[i] + " " + words; 12 | num /= 1000; 13 | i++; 14 | } 15 | return words.trim(); 16 | } 17 | 18 | private String helper (int num) { 19 | if (num == 0) 20 | return ""; 21 | else if(num < 20) 22 | return LESS_THAN_20[num] + " "; 23 | else if(num < 100) 24 | return TENS[num / 10] + " " + helper(num % 10); 25 | else 26 | return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/intersectionOfTwoArrays.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] intersect(int[] nums1, int[] nums2) { 4 | HashSet set = new HashSet(); 5 | ArrayList res = new ArrayList(); 6 | //Add all elements to set from array 1 7 | for(int i =0; i< nums1.length; i++) set.add(nums1[i]); 8 | for(int j = 0; j < nums2.length; j++) { 9 | // If present in array 2 then add to res and remove from set 10 | if(set.contains(nums2[j])) { 11 | res.add(nums2[j]); 12 | set.remove(nums2[j]); 13 | } 14 | } 15 | // Convert ArrayList to array 16 | int[] arr = new int[res.size()]; 17 | for (int i= 0; i < res.size(); i++) arr[i] = res.get(i); 18 | return arr; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/intersectionOfTwoArraysTwo.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] intersect(int[] nums1, int[] nums2) { 4 | HashMap map = new HashMap<>(); 5 | ArrayList result = new ArrayList<>(); 6 | for(int i=0; i 0){ 13 | result.add(nums2[i]); 14 | map.put(nums2[i], map.get(nums2[i]) + 1); 15 | } 16 | } 17 | 18 | int [] ans = new int [result.size()]; 19 | for(int i=0; i pq = new PriorityQueue<>(); 6 | for(int j=0; j { 16 | int x, y, val; 17 | public Tuple (int x, int y, int val) { 18 | this.x = x; 19 | this.y = y; 20 | this.val = val; 21 | } 22 | 23 | @Override 24 | public int compareTo(Tuple that){ 25 | return this.val - that.val; 26 | } 27 | } 28 | } 29 | 30 | 31 | class Solution { 32 | public int kthSmallest(int[][] matrix, int k) { 33 | int n = matrix.length; 34 | int left = matrix[0][0]; 35 | int right = matrix[n-1][n-1]; 36 | 37 | while(left < right){ 38 | int mid = left + (right - left) / 2; 39 | int count = 0, j= n-1; 40 | for(int i=0; i=0 && matrix[i][j] > mid) j--; 42 | count += (j + 1); 43 | } 44 | if(count < k) left = mid + 1; 45 | else right = mid; 46 | } 47 | return left; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/largestIncreasingPath.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public static final int [][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 4 | public int longestIncreasingPath(int[][] matrix) { 5 | if(matrix.length == 0) return 0; 6 | int m = matrix.length, n = matrix[0].length; 7 | int [][] cache = new int[m][n]; 8 | int max = 1; 9 | for(int i = 0; i=m || y<0 || y>=n || matrix[x][y] <= matrix[i][j]) continue; 24 | int len = 1 + dfs(matrix, x, y, m, n, cache); 25 | max = Math.max(max, len); 26 | } 27 | cache[i][j] = max; 28 | return max; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/largestReactrangeArea.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int largestRectangleArea(int[] heights) { 4 | int len = heights.length; 5 | Stack s = new Stack(); 6 | int maxArea = 0; 7 | for(int i=0; i<=len; i++){ 8 | int h = (i==len ? 0 : heights[i]); 9 | if(s.isEmpty() || h >= heights[s.peek()]){ 10 | s.push(i); 11 | }else{ 12 | int tp = s.pop(); 13 | maxArea = Math.max(maxArea, heights[tp] * (s.isEmpty() ? i : i-1-s.peek())); 14 | i--; 15 | } 16 | } 17 | return maxArea; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/lengthOfLongestSubstring.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLongestSubstring(String s){ 3 | int n = s.length(); 4 | Set set = new HashSet<>(); 5 | int ans = 0, i = 0, j = 0; 6 | while(i < n && j < n) { 7 | if(!set.contains(s.charAt(j))){ 8 | set.add(s.charAt(j++)); 9 | ans = Math.max(ans, j - i); 10 | }else{ 11 | set.remove(s.charAt(i++)); 12 | } 13 | } 14 | return ans; 15 | 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/lengthOfLongestSubstringTwo.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLongestSubstringTwoDistinct(String s) { 3 | if(s.length() < 1) return 0; 4 | HashMap index = new HashMap(); 5 | int lo = 0; 6 | int hi = 0; 7 | int maxLength = 0; 8 | while(hi < s.length()) { 9 | if(index.size() <= 2) { 10 | char c = s.charAt(hi); 11 | index.put(c, hi); 12 | hi++; 13 | } 14 | if(index.size() > 2) { 15 | int leftMost = s.length(); 16 | for(int i : index.values()) { 17 | leftMost = Math.min(leftMost,i); 18 | } 19 | char c = s.charAt(leftMost); 20 | index.remove(c); 21 | lo = leftMost+1; 22 | } 23 | maxLength = Math.max(maxLength, hi-lo); 24 | } 25 | return maxLength; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/letterCombination.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private final String [] LETTERS = new String [] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 3 | public List letterCombinations(String digits) { 4 | LinkedList result = new LinkedList<>(); 5 | if (digits.length() == 0) return result; 6 | result.add(""); 7 | for(int i=0; i hm = new HashMap<>(); 5 | for(int n: nums){ 6 | if(!hm.containsKey(n)){ 7 | int left = (hm.containsKey(n-1)) ? hm.get(n-1) : 0; 8 | int right = (hm.containsKey(n+1)) ? hm.get(n+1) : 0; 9 | int sum = left + right + 1; 10 | res = Math.max(res, sum); 11 | hm.put(n, sum); 12 | 13 | hm.put(n-left, sum); 14 | hm.put(n+right, sum); 15 | 16 | }else{ 17 | continue; 18 | } 19 | } 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/longestPalindrome.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String longestPalindrome(String s) { 3 | int start = 0; 4 | int end = 0; 5 | for (int i = 0; i < s.length();i++){ 6 | int len1 = expandPalindrome(i,i+1,s); 7 | int len2 = expandPalindrome(i,i,s); 8 | int len = Math.max(len1,len2); 9 | if(len>end-start){ 10 | start = i-(len-1)/2; 11 | end = i+len/2; 12 | } 13 | } 14 | return s.substring(start,end+1); 15 | } 16 | 17 | public int expandPalindrome(int left, int right, String s){ 18 | int l = left; 19 | int r = right; 20 | while(l>=0&&r stack = new Stack<>(); 6 | stack.push(-1); 7 | for (int i = 0; i < s.length(); i++) { 8 | if (s.charAt(i) == '(') { 9 | stack.push(i); 10 | } else { 11 | stack.pop(); 12 | if (stack.empty()) { 13 | stack.push(i); 14 | } else { 15 | maxans = Math.max(maxans, i - stack.peek()); 16 | } 17 | } 18 | } 19 | return maxans; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/majorityElement.java: -------------------------------------------------------------------------------- 1 | // Sorting 2 | public int majorityElement1(int[] nums) { 3 | Arrays.sort(nums); 4 | return nums[nums.length/2]; 5 | } 6 | 7 | // Hashtable 8 | public int majorityElement2(int[] nums) { 9 | Map myMap = new HashMap(); 10 | //Hashtable myMap = new Hashtable(); 11 | int ret=0; 12 | for (int num: nums) { 13 | if (!myMap.containsKey(num)) 14 | myMap.put(num, 1); 15 | else 16 | myMap.put(num, myMap.get(num)+1); 17 | if (myMap.get(num)>nums.length/2) { 18 | ret = num; 19 | break; 20 | } 21 | } 22 | return ret; 23 | } 24 | 25 | // Moore voting algorithm 26 | public int majorityElement3(int[] nums) { 27 | int count=0, ret = 0; 28 | for (int num: nums) { 29 | if (count==0) 30 | ret = num; 31 | if (num!=ret) 32 | count--; 33 | else 34 | count++; 35 | } 36 | return ret; 37 | } 38 | 39 | // Bit manipulation 40 | public int majorityElement(int[] nums) { 41 | int[] bit = new int[32]; 42 | for (int num: nums) 43 | for (int i=0; i<32; i++) 44 | if ((num>>(31-i) & 1) == 1) 45 | bit[i]++; 46 | int ret=0; 47 | for (int i=0; i<32; i++) { 48 | bit[i]=bit[i]>nums.length/2?1:0; 49 | ret += bit[i]*(1<<(31-i)); 50 | } 51 | return ret; 52 | } 53 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/maxAreaContainer.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxArea(int[] height) { 3 | int left = 0, right = height.length - 1; 4 | int maxArea = 0; 5 | while(left < right) { 6 | maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left)); 7 | if(height[left] < height[right]) 8 | left++; 9 | else 10 | right--; 11 | } 12 | return maxArea; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/maxProductSubArray.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProduct(int[] A) { 3 | assert A.length > 0; 4 | int max = A[0], min = A[0], maxAns = A[0]; 5 | for (int i=1 ; i b ? a : b; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/maxProfit.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int minPrice = Integer.MAX_VALUE; 4 | int profit = 0; 5 | for(int i=0; iprices[i]) total += prices[i+1]-prices[i]; 6 | } 7 | 8 | return total; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/maxSubArrayLen.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxSubArrayLen(int[] nums, int k) { 3 | int sum = 0, max = 0; 4 | HashMap map = new HashMap(); 5 | for(int i=0; i=0; j--){ 33 | if(matrix[i][j] == '1') 34 | right[j] = Math.min(right[j], curr_right); 35 | else { 36 | right[j] = n-1; 37 | curr_right = j-1; 38 | } 39 | } 40 | 41 | for (int j=0; j 0 ? dp[i - 1] : 0); 9 | max = Math.max(max, dp[i]); 10 | } 11 | return max; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/mergeIntervals.java: -------------------------------------------------------------------------------- 1 | /* Definition for an interval. 2 | * public class Interval { 3 | * int start; 4 | * int end; 5 | * Interval() { start = 0; end = 0; } 6 | * Interval(int s, int e) { start = s; end = e; } 7 | * } 8 | */ 9 | class Solution { 10 | public List merge(List intervals) { 11 | if(intervals.size() <= 1) return intervals; 12 | List result = new LinkedList<>(); 13 | Collections.sort(intervals, new Comparator(){ 14 | public int compare(Interval i1, Interval i2){ 15 | return i1.start - i2.start; 16 | } 17 | }); 18 | 19 | int start = intervals.get(0).start; 20 | int end = intervals.get(0).end; 21 | 22 | for(Interval interval : intervals){ 23 | if(interval.start <= end){ 24 | end = Math.max(end, interval.end); 25 | } else { 26 | result.add(new Interval(start, end)); 27 | start = interval.start; 28 | end = interval.end; 29 | } 30 | } 31 | result.add(new Interval(start, end)); 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/mergeKSortedLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode mergeKLists(ListNode[] lists) { 11 | if (lists==null||lists.length==0) return null; 12 | 13 | PriorityQueue queue= new PriorityQueue(lists.length,new Comparator(){ 14 | @Override 15 | public int compare(ListNode o1,ListNode o2){ 16 | if (o1.val= 0 && j >= 0) { 6 | if (A[i] > B[i]) 7 | A[k--] = A[i--]; 8 | else 9 | A[k--] = B[j--]; 10 | } 11 | while (j>=0) 12 | A[k--] = B[j--]; 13 | } 14 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/mergeSortedList.java: -------------------------------------------------------------------------------- 1 | public ListNode mergeTwoList(ListNode l1, ListNode l2) { 2 | if (l1 == null) return l2; 3 | if (l2 == null) return l1; 4 | 5 | if(l1.val < l2.val) { 6 | l1.next = mergeTwoList(l1.next, l2); 7 | return l1; 8 | } else { 9 | l2.next = mergeTwoList(l1.next, l2); 10 | return l2; 11 | } 12 | } 13 | 14 | public class Solution { 15 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 16 | if(l1 == null || l2 == null ) { 17 | return l1 == null ? l2 : l1; 18 | } 19 | ListNode dummy = new ListNode(0); 20 | ListNode current = dummy; 21 | while(l1 != null && l2 != null ) { 22 | if(l1.val < l2.val ) { 23 | current.next = l1; 24 | l1 = l1.next; 25 | } 26 | else { 27 | current.next = l2; 28 | l2 = l2.next; 29 | } 30 | current = current.next; 31 | } 32 | current.next = l1 == null ? l2 : l1; 33 | return dummy.next; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/miniStack.java: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | int min = Integer.MAX_VALUE; 3 | Stackstack = new Stack<>(); 4 | /** initialize your data structure here. */ 5 | public MinStack() { 6 | 7 | } 8 | 9 | public void push(int x) { 10 | if(x <= min){ 11 | stack.push(min); 12 | min = x; 13 | } 14 | stack.push(x); 15 | } 16 | 17 | public void pop() { 18 | if(min == stack.pop()) min = stack.pop(); 19 | } 20 | 21 | public int top() { 22 | return stack.peek(); 23 | } 24 | 25 | public int getMin() { 26 | return min; 27 | } 28 | } 29 | 30 | /** 31 | * Your MinStack object will be instantiated and called as such: 32 | * MinStack obj = new MinStack(); 33 | * obj.push(x); 34 | * obj.pop(); 35 | * int param_3 = obj.top(); 36 | * int param_4 = obj.getMin(); 37 | */ 38 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/minimumWindowSubstring.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String minWindow(String s, String t) { 3 | if(s==null || t==null) return ""; 4 | HashMap hm = new HashMap<>(); 5 | for(char c : s.toCharArray()){ 6 | hm.put(c, 0); 7 | } 8 | for(char c : t.toCharArray()){ 9 | if(hm.containsKey(c)){ 10 | hm.put(c, hm.get(c) + 1); 11 | }else{ 12 | return ""; 13 | } 14 | } 15 | 16 | int start = 0; 17 | int end = 0; 18 | int minLen = Integer.MAX_VALUE; 19 | int counter = t.length(); 20 | int minStart = 0; 21 | 22 | while(end < s.length()){ 23 | char c1 = s.charAt(end); 24 | if(hm.get(c1) > 0) 25 | counter--; 26 | hm.put(c1, hm.get(c1) - 1); 27 | end++; 28 | 29 | while(counter == 0){ 30 | if(end - start < minLen){ 31 | minLen = end - start; 32 | minStart = start; 33 | } 34 | char c2 = s.charAt(start); 35 | hm.put(c2, hm.get(c2) + 1); 36 | if(hm.get(c2) > 0) 37 | counter++; 38 | start++; 39 | } 40 | } 41 | return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/missingNumber.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int missingNumber(int[] nums) { 4 | int xor = 0; 5 | int i; 6 | for( i=0; imid) right = mid-1; 20 | else left = mid+1; 21 | } 22 | return left; 23 | } 24 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/missingRanges.java: -------------------------------------------------------------------------------- 1 | public List findMissingRanges(int[] vals, int start, int end){ 2 | List ranges = new ArrayList<>(); 3 | int prev = start - 1 ; 4 | for(int i = 0; i <= vals.length; i++){ 5 | int curr = (i == vals.length) ? end + 1 : vals[i]; 6 | if ( curr - prev >= 2) { 7 | ranges.add(getRange(prev + 1, curr - 1)); 8 | } 9 | prev = curr; 10 | } 11 | return ranges; 12 | } 13 | 14 | private String getRange(int from, int to){ 15 | return (from == to) ? String.value(from) : from + "->" + to; 16 | } 17 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/moveZeros.java: -------------------------------------------------------------------------------- 1 | // Shift non-zero values as far forward as possible 2 | // Fill remaining space with zeros 3 | 4 | public void moveZeroes(int[] nums) { 5 | if (nums == null || nums.length == 0) return; 6 | 7 | int insertPos = 0; 8 | for (int num: nums) { 9 | if (num != 0) nums[insertPos++] = num; 10 | } 11 | 12 | while (insertPos < nums.length) { 13 | nums[insertPos++] = 0; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/multipleStrings.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public String multiply(String num1, String num2) { 4 | int m = num1.length(); 5 | int n = num2.length(); 6 | int [] res = new int[m+n]; 7 | for(int i = m-1; i>=0; i--){ 8 | for(int j=n-1; j>=0; j--){ 9 | int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 10 | int p1 = i + j, p2 = i + j + 1; 11 | int sum = mul + res[p2]; 12 | 13 | res[p1] += sum / 10; 14 | res[p2] = sum % 10; 15 | } 16 | } 17 | 18 | StringBuilder sb = new StringBuilder(); 19 | for(int p : res) if(!(sb.length()==0 && p==0)) sb.append(p); 20 | return sb.length() == 0 ? "0" : sb.toString(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/nextGreaterElementThree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int nextGreaterElement(int n) { 3 | char[] number = (n + "").toCharArray(); 4 | 5 | int i, j; 6 | 7 | for (i = number.length-1; i > 0; i--) 8 | if (number[i-1] < number[i]) 9 | break; 10 | 11 | if (i == 0) 12 | return -1; 13 | 14 | int x = number[i-1], smallest = i; 15 | for (j = i+1; j < number.length; j++) 16 | if (number[j] > x && number[j] <= number[smallest]) 17 | smallest = j; 18 | 19 | 20 | char temp = number[i-1]; 21 | number[i-1] = number[smallest]; 22 | number[smallest] = temp; 23 | 24 | Arrays.sort(number, i, number.length); 25 | a 26 | long val = Long.parseLong(new String(number)); 27 | return (val <= Integer.MAX_VALUE) ? (int) val : -1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/numberOfDigitOne.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countDigitOne(int n) { 3 | int count = 0; 4 | 5 | for (long k = 1; k <= n; k *= 10) { 6 | long r = n / k, m = n % k; 7 | // sum up the count of ones on every place k 8 | count += (r + 8) / 10 * k + (r % 10 == 1 ? m + 1 : 0); 9 | } 10 | 11 | return count; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/numberOfIsland.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numIslands(char[][] grid) { 3 | int m = grid.length; 4 | if(m==0)return 0; 5 | int n = grid[0].length; 6 | int count = 0; 7 | for(int i=0; i= grid.length || j >= grid[0].length || grid[i][j] != '1') return; 19 | 20 | grid[i][j] = '0'; 21 | 22 | countIsland(grid, i-1, j); 23 | 24 | countIsland(grid, i, j-1); 25 | 26 | countIsland(grid, i+1, j); 27 | 28 | countIsland(grid, i, j+1); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/oddEvenLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Definition for singly-linked list. 4 | * public class ListNode { 5 | * int val; 6 | * ListNode next; 7 | * ListNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public ListNode oddEvenList(ListNode head) { 12 | if(head != null){ 13 | ListNode odd = head, even = head.next, evenHead = even; 14 | while(even != null && even.next != null){ 15 | odd.next = odd.next.next; 16 | even.next = even.next.next; 17 | odd = odd.next; 18 | even = even.next; 19 | } 20 | odd.next = evenHead; 21 | } 22 | return head; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/oneEditDistance.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isOneEditDistance(String s, String t) { 3 | for(int i=0; i> partition(String s) { 4 | List> list = new ArrayList<>(); 5 | backtrack(list, new ArrayList<>(), s, 0); 6 | return list; 7 | } 8 | 9 | public void backtrack(List> list, List tempList, String s, int start){ 10 | if (start == s.length()) { 11 | list.add(new ArrayList<>(tempList)); 12 | } else { 13 | for(int i=start; i> generate(int numRows) { 3 | List> result = new ArrayList>(); 4 | int first = 0; 5 | int second = 0; 6 | if(numRows<=0) return result; 7 | for(int i=0; ilevel = new ArrayList(); 9 | for(int j=0; j getRow(int rowIndex) { 3 | List ret = new ArrayList(); 4 | ret.add(1); 5 | for(int i=1; i<=rowIndex; i++) { 6 | for(int j=i-1; j>=1; j--){ 7 | int tmp = ret.get(j-1) + ret.get(j); 8 | ret.set(j, tmp); 9 | } 10 | ret.add(1); 11 | } 12 | return ret; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/permutation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> permute(int[] nums) { 3 | List> ans = new ArrayList<>(); 4 | backtrack(nums, ans, new ArrayList<>()); 5 | return ans; 6 | } 7 | public void backtrack(int[] nums, List> ans, List tempList){ 8 | if(tempList.size() == nums.length){ 9 | ans.add(new ArrayList<>(tempList)); 10 | } else { 11 | for(int i=0; i> permuteUnique(int[] nums) { 3 | List> result = new ArrayList<>(); 4 | boolean [] used = new boolean [nums.length]; 5 | Arrays.sort(nums); 6 | backtrack(result, new ArrayList<>(), nums, used); 7 | return result; 8 | } 9 | 10 | private void backtrack(List> result, List tempList, int [] nums, boolean [] used){ 11 | if(tempList.size() == nums.length){ 12 | result.add(new ArrayList<>(tempList)); 13 | } else { 14 | for(int i=0; i 0 && nums[i] == nums[i-1] && !used[i-1]) continue; 17 | used[i] = true; 18 | tempList.add(nums[i]); 19 | backtrack(result, tempList, nums, used); 20 | used[i] = false; 21 | tempList.remove(tempList.size() - 1); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/plusOne.java: -------------------------------------------------------------------------------- 1 | public int[] plusOne(int[] digits) { 2 | 3 | int n = digits.length; 4 | for(int i=n-1; i>=0; i--) { 5 | if(digits[i] < 9) { 6 | digits[i]++; 7 | return digits; 8 | } 9 | 10 | digits[i] = 0; 11 | } 12 | 13 | int[] newNumber = new int [n+1]; 14 | newNumber[0] = 1; 15 | 16 | return newNumber; 17 | } 18 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/powerOfThree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPowerOfThree(int n) { 3 | return ( n>0 && 1162261467%n==0); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/powerOfTwo.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPowerOfTwo(int n) { 3 | if(n<=0) 4 | return (n & (n-1)) == 0; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/productExceptSelf.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | int n = nums.length; 4 | int[] res = new int[n]; 5 | res[0] = 1; 6 | for (int i = 1; i < n; i++) { 7 | res[i] = res[i - 1] * nums[i - 1]; 8 | System.out.println(res[i]); 9 | } 10 | int right = 1; 11 | for (int i = n - 1; i >= 0; i--) { 12 | res[i] *= right; 13 | right *= nums[i]; 14 | } 15 | return res; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/readNCharactersGivenRead4.java: -------------------------------------------------------------------------------- 1 | /* The read4 API is defined in the parent class Reader4. 2 | int read4(char[] buf); */ 3 | 4 | public class Solution extends Reader4 { 5 | /** 6 | * @param buf Destination buffer 7 | * @param n Maximum number of characters to read 8 | * @return The number of characters read 9 | */ 10 | public int read(char[] buf, int n) { 11 | boolean eof = false; 12 | int total = 0; 13 | char[] tmp = new char[4]; 14 | 15 | while(!eof && total < n){ 16 | int count = read4(tmp); 17 | eof = count < 4; 18 | count = Math.min(count, n-total); 19 | for(int i=0; i= buffCnt) buffPtr = 0; 24 | } 25 | return ptr; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/remove9.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int newInteger(int n) { 3 | return Integer.parseInt(Integer.toString(n, 9)); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/removeDuplicatedFromSortedArray.java: -------------------------------------------------------------------------------- 1 | public int removeDuplicates(int[] nums) { 2 | if (nums.length == 0) return 0; 3 | int i = 0; 4 | for (int j = 1; j < nums.length; j++) { 5 | if (nums[j] != nums[i]) { 6 | i++; 7 | nums[i] = nums[j]; 8 | } 9 | } 10 | return i + 1; 11 | } 12 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/removeElement.java: -------------------------------------------------------------------------------- 1 | int removeElement (int A [], int n, int elem) { 2 | int begin = 0; 3 | for (int i=0; i removeInvalidParentheses(String s) { 3 | List res = new ArrayList<>(); 4 | Set visited = new HashSet<>(); 5 | Queue queue = new LinkedList<>(); 6 | 7 | if(s==null) return res; 8 | 9 | queue.add(s); 10 | visited.add(s); 11 | boolean found = false; 12 | 13 | while(!queue.isEmpty()){ 14 | s = queue.poll(); 15 | if(isValid(s)){ 16 | res.add(s); 17 | found = true; 18 | } 19 | 20 | if(found) continue; 21 | 22 | for(int i=0; i=0; i--){ 6 | sb.append(s.charAt(i)); 7 | } 8 | return sb.toString(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/reverseVowel.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseVowels(String s) { 3 | char [] chars = s.toCharArray(); 4 | int start = 0; 5 | int end = s.length()-1; 6 | String vowels = "aeiouAEIOU"; 7 | while(start < end){ 8 | while(start < end && !vowels.contains(chars[start] + "")) 9 | start++; 10 | 11 | while(start < end && !vowels.contains(chars[end] + "")) 12 | end--; 13 | 14 | char tmp = chars[start]; 15 | chars[start] = chars[end]; 16 | chars[end] = tmp; 17 | start++; 18 | end--; 19 | } 20 | return new String(chars); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/reverseWords.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String reverseWords(String s) { 3 | StringBuilder reverseString = new StringBuilder(); 4 | int j = s.length(); 5 | for(int i = s.length()-1;i>=0;i--){ 6 | if(s.charAt(i)==' '){ 7 | j=i; 8 | }else if(i==0||s.charAt(i-1)==' '){ 9 | if(reverseString.length()!=0){ 10 | reverseString.append(' '); 11 | } 12 | reverseString.append(s.substring(i,j)); 13 | 14 | } 15 | } 16 | return reverseString.toString(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/reverseWordsTwo.java: -------------------------------------------------------------------------------- 1 | public void reverseWords(char[] s){ 2 | reverse(s, 0, s.length); 3 | for(int i = 0, j = 0; j <= s.length; j++){ 4 | if(j == s.length || s[j] == ' '){ 5 | reverse(s, i, j); 6 | i = j+1; 7 | } 8 | } 9 | } 10 | private void reverse(char[] s, int begin, int end){ 11 | for(int i=0; i<(end-begin)/2;i++){ 12 | char temp = s[begin + i]; 13 | s[begin + i] = s[end - i - 1]; 14 | s[end - i - 1] = temp; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/romanToInt.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | int nums[]=new int[s.length()]; 4 | for(int i=0;i getSkyline(int[][] buildings) { 4 | Map> cps = new TreeMap<>(); 5 | for(int [] b : buildings) { 6 | cps.putIfAbsent(b[0], new LinkedList<>()); 7 | cps.putIfAbsent(b[1], new LinkedList<>()); 8 | cps.get(b[0]).add(b); 9 | cps.get(b[1]).add(b); 10 | } 11 | 12 | PriorityQueue heap = new PriorityQueue<>(new Comparator(){ 13 | public int compare(int [] b1, int [] b2) { 14 | return Integer.compare(b2[2], b1[2]); 15 | } 16 | }); 17 | 18 | List res = new ArrayList<>(); 19 | for(Map.Entry> entry : cps.entrySet()){ 20 | int c = entry.getKey(); 21 | List bs = entry.getValue(); 22 | 23 | for(int [] b : bs) { 24 | if(c == b[0]) { 25 | heap.add(b); 26 | } else { 27 | heap.remove(b); 28 | } 29 | } 30 | 31 | if(heap.isEmpty()) { 32 | res.add(new int[] {c, 0}); 33 | } else { 34 | int h = heap.peek()[2]; 35 | if(res.isEmpty() || res.get(res.size() - 1)[1] != h) { 36 | res.add(new int [] {c, h}); 37 | } 38 | } 39 | 40 | } 41 | return res; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/slidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] maxSlidingWindow(int[] nums, int k) { 4 | int n = nums.length; 5 | if (n==0) 6 | return nums; 7 | int [] result = new int [n - k + 1]; 8 | LinkedList dq = new LinkedList<>(); 9 | for(int i=0; i= nums[dq.peekLast()]){ 15 | dq.pollLast(); 16 | } 17 | dq.offer(i); 18 | if(i - k + 1 >= 0){ 19 | result[i-k+1] = nums[dq.peek()]; 20 | } 21 | } 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/sortColors.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public void sortColors(int[] nums) { 4 | if(nums==null || nums.length<2) return; 5 | int left = 0; int right = nums.length - 1; 6 | for(int i=left; i<=right;){ 7 | if(nums[i] == 0){ 8 | int temp = nums[i]; 9 | nums[i] = nums[left]; 10 | nums[left] = temp; 11 | i++; 12 | left++; 13 | }else if(nums[i] == 2){ 14 | System.out.print( right); 15 | int temp = nums[i]; 16 | nums[i] = nums[right]; 17 | nums[right] = temp; 18 | right--; 19 | }else{ 20 | i++; 21 | } 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/sortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Source; https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/#/description 3 | * Definition for a binary tree node. 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class Solution { 12 | public TreeNode sortedArrayToBST(int[] nums) { 13 | if(nums.length == 0) return null; 14 | TreeNode head = buildTree(nums, 0, nums.length-1); 15 | return head; 16 | } 17 | 18 | public TreeNode buildTree(int[] nums, int low, int high){ 19 | if(low > high) return null; 20 | int mid = low + (high - low)/2; 21 | TreeNode node = new TreeNode(nums[mid]); 22 | node.left = buildTree(nums, low, mid-1); 23 | node.right = buildTree(nums, mid+1, high); 24 | return node; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/sparseMatrix.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[][] multiply(int[][] A, int[][] B) { 3 | int m = A.length; 4 | int n = A[0].length; 5 | int nB = B[0].length; 6 | int [][] C = new int[m][nB]; 7 | for(int i=0; i spiralOrder(int[][] matrix) { 2 | Listres = new ArrayList(); 3 | if( matrix.length == 0) return res; 4 | 5 | int rowBegin = 0; 6 | int rowEnd = matrix.length - 1; 7 | int colBegin = 0; 8 | int colEnd = matrix[0].length - 1; 9 | 10 | while (rowBegin <= rowEnd && colBegin <= colEnd){ 11 | // Traverse Right 12 | for (int j = colBegin; j <= colEnd; j++) { 13 | res.add(matrix[rowBegin][j]); 14 | } 15 | rowBegin++; 16 | 17 | // Traverse Down 18 | for (int j = rowBegin; j <= rowEnd; j++) { 19 | res.add(matrix[j][colEnd]); 20 | } 21 | colEnd--; 22 | 23 | // Traverse Left 24 | if (rowBegin < rowEnd) { 25 | for (int j = colEnd; j>= colBegin; j--) { 26 | res.add(matrix[rowEnd][j]); 27 | } 28 | } 29 | rowEnd--; 30 | 31 | // Traverse Up 32 | if (colBegin <= colEnd) { 33 | for (int j = rowEnd; j >= rowBegin; j--) { 34 | res.add(matrix[j][colBegin]); 35 | } 36 | } 37 | colBegin ++; 38 | } 39 | return res; 40 | } 41 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/sqrt.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mySqrt(int x) { 3 | if(x==0) 4 | return 0; 5 | 6 | int left = 1; 7 | int right = x; 8 | 9 | while(true){ 10 | int mid = (right -left) / 2 + left; 11 | if(mid > x/mid) { 12 | right = mid; 13 | }else{ 14 | if(mid + 1 > x/(mid+ 1)) 15 | return mid; 16 | left = mid; 17 | } 18 | 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/strStr.java: -------------------------------------------------------------------------------- 1 | //implement strstr(). Returns the index of the first ocurrence of needle in haystack or -1 if needle is not part of haystack 2 | 3 | 4 | public int strStr(String haystack, String needle){ 5 | for(int i = 0; ;i++){ 6 | for(int j = 0; ;j++){ 7 | if(j == needle.length()) return i; 8 | if(i + j == haystack.length()) return -1; 9 | if(needle.charAt(j)!=haystack.charAt(i+j)) break; 10 | } 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/stringToInt.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private static final int maxDiv10 = Integer.MAX_VALUE / 10; 3 | public int myAtoi(String str) { 4 | int i = 0, n = str.length(); 5 | while(i < n && Character.isWhitespace(str.charAt(i))) i++; 6 | int sign = 1; 7 | if(i < n && str.charAt(i) == '+'){ 8 | i++; 9 | }else if(i maxDiv10 || num == maxDiv10 && digit >= 8 ) { 17 | return sign == 1 ? Integer.MAX_VALUE:Integer : MIN_VALUE; 18 | } 19 | num = num * 10 + digit; 20 | i++; 21 | 22 | } 23 | 24 | return sign * num; 25 | } 26 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/subarraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | public int subarraySum(int [] nums, int k) { 2 | int sum = 0, result = 0; 3 | Map preSum = new HashMap<>(); 4 | preSum.put(0, 1); 5 | 6 | for (int i=0; i> subsets(int[] nums) { 3 | List> list = new ArrayList<>(); 4 | Arrays.sort(nums); 5 | backtrack(list, new ArrayList<>(), nums, 0); 6 | return list; 7 | } 8 | 9 | private void backtrack(List> list, List tempList, int [] nums, int start){ 10 | list.add(new ArrayList<>(tempList)); 11 | for(int i=start; i> subsetsWithDup(int[] nums) { 6 | List> result = new ArrayList<>(); 7 | Arrays.sort(nums); 8 | backtrack(result, new ArrayList<>(), nums, 0); 9 | return result; 10 | } 11 | 12 | private void backtrack(List> result, List tempList, int [] nums, int start){ 13 | result.add(new ArrayList<>(tempList)); 14 | for(int i=start; i start && nums[i] == nums[i-1]) continue; 16 | tempList.add(nums[i]); 17 | backtrack(result, tempList, nums, i+1); 18 | tempList.remove(tempList.size() - 1); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/summaryRanges.java: -------------------------------------------------------------------------------- 1 | public List summaryRanges (int[] nums) { 2 | List summary = new ArrayList<>(); 3 | for (int i=0, j=0; j" + nums[j]); 10 | i = j + 1; 11 | } 12 | return summary; 13 | } 14 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/surroundedRegions.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void solve(char[][] board) { 3 | int i, j; 4 | int row = board.length; 5 | if(row == 0) return; 6 | int col = board[0].length; 7 | 8 | for(i = 0; i < row; i++) { 9 | check(board, i, 0, row, col); 10 | if(col > 1) 11 | check(board, i, col-1, row, col); 12 | } 13 | for(j=1; j +1 1) 16 | check(board, row - 1, j, row, col); 17 | } 18 | for(i =0; i < row; i++) 19 | for(j = 0; j < col; j++) 20 | if(board[i][j]=='O') 21 | board[i][j] = 'X'; 22 | for(i=0; i < row; i++) 23 | for(j = 0; j < col; j++) 24 | if(board[i][j]=='1') 25 | board[i][j] = 'O'; 26 | } 27 | 28 | private void check(char[][] vec, int i, int j, int row, int col) { 29 | if(vec[i][j]=='O') { 30 | vec[i][j]='1'; 31 | if(i>1) 32 | check(vec, i -1, j, row, col); 33 | if(j>1) 34 | check(vec, i, j-1, row, col); 35 | if(i+1 0 ? 0 : subsetSum(nums, (s + sum) >>> 1); 7 | } 8 | 9 | public int subsetSum(int[] nums, int s) { 10 | int[] dp = new int[s + 1]; 11 | dp[0] = 1; 12 | for (int n : nums) 13 | for (int i = s; i >= n; i--) 14 | dp[i] += dp[i - n]; 15 | return dp[s]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/threeSum.java: -------------------------------------------------------------------------------- 1 | public List> threeSum(int[] num) { 2 | Arrays.sort(num); 3 | List> res = new LinkedList<>(); 4 | for (int i = 0; i < num.length-2; i++) { 5 | if (i == 0 || (i > 0 && num[i] != num[i-1])) { 6 | int lo = i+1, hi = num.length-1, sum = 0 - num[i]; 7 | while (lo < hi) { 8 | if (num[lo] + num[hi] == sum) { 9 | res.add(Arrays.asList(num[i], num[lo], num[hi])); 10 | while (lo < hi && num[lo] == num[lo+1]) lo++; 11 | while (lo < hi && num[hi] == num[hi-1]) hi--; 12 | lo++; hi--; 13 | } else if (num[lo] + num[hi] < sum) lo++; 14 | else hi--; 15 | } 16 | } 17 | } 18 | return res; 19 | } 20 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/topKFrequent.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public List topKFrequent(int[] nums, int k) { 4 | List res = new ArrayList<>(); 5 | List [] bucket = new List[nums.length + 1]; 6 | Map frequencyMap = new HashMap<>(); 7 | for(int n : nums) { 8 | frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1); 9 | } 10 | 11 | for(int key : frequencyMap.keySet()) { 12 | int frequency = frequencyMap.get(key); 13 | if(bucket[frequency] == null){ 14 | bucket[frequency] = new ArrayList<>(); 15 | } 16 | bucket[frequency].add(key); 17 | } 18 | 19 | for(int pos = bucket.length - 1; pos >=0 && res.size() < k; pos--){ 20 | if(bucket[pos] != null) 21 | res.addAll(bucket[pos]); 22 | } 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/trapWater.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int trap(int[] A) { 3 | int left = 0, right = A.length - 1; 4 | int res = 0; 5 | int maxLeft = 0, maxRight = 0; 6 | while (left <= right) { 7 | if(A[left] <= A[right]) { 8 | if(A[left] >= maxLeft) maxLeft = A[left]; 9 | else res += maxLeft - A[left]; 10 | left++; 11 | } else { 12 | if(A[right] >= maxRight) maxRight = A[right]; 13 | else res += maxRight - A[right]; 14 | right--; 15 | } 16 | } 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/trie.java: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | public boolean isWord; 3 | public TrieNode[] children = new TrieNode[26]; 4 | public TrieNode() {} 5 | } 6 | public class Trie { 7 | private TrieNode root; 8 | public Trie() { 9 | root = new TrieNode(); 10 | } 11 | 12 | 13 | /** Inserts a word into the trie. */ 14 | public void insert(String word) { 15 | TrieNode ws = root; 16 | for(int i=0; i map = new HashMap<>(); 3 | for (int i = 0; i < numbers.length; i++) { 4 | int x = numbers[i]; 5 | if (map.containsKey(target - x)) { 6 | return new int[] { map.get(target - x) + 1, i + 1 }; 7 | } 8 | map.put(x, i); 9 | } 10 | throw new IllegalArgumentException("No two sum solution"); 11 | } 12 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/twoSumThree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Question: 3 | Design and implement a TwoSum class. It should support the following operation: add and find 4 | 5 | add(input) - Add the number input into an internal data structure 6 | 7 | find(value) - Find if there exist any pair of numbers which sum is equal to the value 8 | 9 | for example; add(1); add(3); add(5); find(4)->true; find(7)->false; 10 | */ 11 | 12 | /* 13 | Solution 1: 14 | add-O(n) runtime, find-O(1) runtime, O(n^2) space - store pair sums in hash table 15 | 16 | Solution 2: 17 | add-O(n) runtime, find-O(n) runtime, O(n) space - Binary Search + Two Pointers 18 | 19 | Solution 3: 20 | store each input into a hash table with the input as key and its count as value. To find if a pair sum exists, just iterate through the hash table in O(n) run time 21 | */ 22 | 23 | public class twoSum{ 24 | private Maptable = new HashMap<>(); 25 | 26 | public void add(int input){ 27 | int count = table.containsKey(input)? table.get(input):0; 28 | table.put(input, count+1) 29 | } 30 | 31 | public boolean find(int val){ 32 | for(Map.Entry entry : table.entrySet()){ 33 | int num = entry.getKey(); 34 | int y = val - num; 35 | if(y == num){ 36 | if(entry.getValue() >= 2) return false; 37 | }else if(table.cotainsKey(y)){ 38 | return true 39 | } 40 | } 41 | return false; 42 | } 43 | 44 | } 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/twoSumTwo.java: -------------------------------------------------------------------------------- 1 | //what if the input is already sorted in ascending order? 2 | 3 | public class Solution { 4 | public int[] twoSum(int[] numbers, int target) { 5 | for(int i=0; i stack = new Stack(); 4 | for (char c : s.toCharArray()) { 5 | if ( c == '(') 6 | stack.push(')'); 7 | else if ( c == '{') 8 | stack.push('}'); 9 | else if ( c == '[') 10 | stack.push(']'); 11 | else if(stack.isEmpty() || stack.pop() != c) 12 | return false; 13 | } 14 | return stack.isEmpty(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/wordBreak.java: -------------------------------------------------------------------------------- 1 | public boolean wordBreak(String s, Set wordDict){ 2 | boolean [] f = new boolean [s.length()+1]; 3 | f[0]=true; 4 | for(int i=0; i<=s.length(); i++){ 5 | for(int j = 0; j> map = new HashMap<>(); 4 | public List wordBreak(String s, List wordDict) { 5 | if(map.containsKey(s)) 6 | return map.get(s); 7 | LinkedList res = new LinkedList<>(); 8 | if(s.length() == 0){ 9 | res.add(""); 10 | return res; 11 | } 12 | for(String word : wordDict){ 13 | if(s.startsWith(word)){ 14 | ListsubList = wordBreak(s.substring(word.length()), wordDict); 15 | for(String sub : subList) 16 | res.add(word + (sub.isEmpty() ? "" : " ") + sub); 17 | } 18 | } 19 | map.put(s, res); 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter_Arrays&Strings/leetcode/wordSearch.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public boolean exist(char[][] board, String word) { 4 | char [] w = word.toCharArray(); 5 | for(int i=0; i findWords(char[][] board, String[] words) { 4 | List res = new ArrayList<>(); 5 | TrieNode root = buildTrie(words); 6 | for(int y=0; y res){ 15 | char c = board[y][x]; 16 | if(c=='#' || p.next[c - 'a'] == null) return; 17 | p = p.next[c - 'a']; 18 | if(p.word != null){ 19 | res.add(p.word); 20 | p.word = null; 21 | } 22 | 23 | board[y][x] = '#'; 24 | if(y>0) dfs(board, y-1, x, p, res); 25 | if(x>0) dfs(board, y, x-1, p, res); 26 | if(y= 1 || num <= 0) { 3 | return "Error"; 4 | } 5 | 6 | StringBuilder binary = new StringBuilder(); 7 | double frac = 0.5; 8 | binary.append("."); 9 | while (num > 0) { 10 | if( binary.length() > 32) { 11 | return "Error"; 12 | } 13 | if (num >= fraction) { 14 | binary.append("1"); 15 | binary -= fraction' 16 | } else { 17 | binary.append("0"); 18 | } 19 | frac /= 2; 20 | } 21 | return binary.toString(); 22 | } 23 | -------------------------------------------------------------------------------- /chapter_Bit_Manipulation/cc150/insertion.java: -------------------------------------------------------------------------------- 1 | int updateBits(int n, int m, int i, int j) { 2 | int allOnes = ~0; // will equal sequence of all ones 3 | 4 | // 1s before position j, then 0s 5 | int left = allOnes << (j+1); // left = 11100000 6 | int right = ((1 << i) - 1); // right = 00000011 7 | int mask = left | right;: 8 | 9 | int n_cleared = n & mask; 10 | int m_shifted = m << i; 11 | 12 | return n_cleared | m_shifted; 13 | } 14 | -------------------------------------------------------------------------------- /chapter_Bit_Manipulation/leetcode/singleNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int singleNumber(int[] nums) { 3 | int result = 0; 4 | for(int i=0; i> i) & 1) == 1){ 8 | sum++; 9 | sum %= 3; 10 | } 11 | } 12 | if(sum!=0){ 13 | ans |= sum << i; 14 | } 15 | } 16 | return ans; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /chapter_Bit_Manipulation/leetcode/sumOfTwo.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int getSum(int a, int b) { 4 | if(a == 0) return b; 5 | if(b == 0) return a; 6 | while(b != 0){ 7 | int carry = a & b; 8 | a = a ^ b; 9 | b = carry << 1; 10 | } 11 | return a; 12 | } 13 | } 14 | 15 | public int getSubtract(int a, int b) { 16 | while (b != 0) { 17 | int borrow = (~a) & b; 18 | a = a ^ b; 19 | b = borrow << 1; 20 | } 21 | 22 | return a; 23 | } 24 | 25 | // Recursive 26 | public int getSum(int a, int b) { 27 | return (b == 0) ? a : getSum(a ^ b, (a & b) << 1); 28 | } 29 | 30 | // Recursive 31 | public int getSubtract(int a, int b) { 32 | return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1); 33 | } 34 | 35 | // Get negative number 36 | public int negate(int x) { 37 | return ~x + 1; 38 | } 39 | -------------------------------------------------------------------------------- /chapter_DP/README.md: -------------------------------------------------------------------------------- 1 | ### 动态规划讲解 2 | [动态规划](https://zh.wikipedia.org/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92)常常适用于有重叠子问题和最优子结构性质的问题。 3 | 4 | 动态规划背后的基本思想非常简单。大致上,若要解一个给定问题,我们需要解其不同部分(即子问题),再合并子问题的解以得出原问题的解。通常许多子问题非常相似,为此动态规划法试图仅仅解决每个子问题一次,从而减少计算量:一旦某个给定子问题的解已经算出,则将其记忆化存储,以便下次需要同一个子问题解之时直接查表。这种做法在重复子问题的数目关于输入的规模呈指数增长时特别有用。 5 | 6 | 动态规划系列题目中一般涉及到3种情况,当题目中出现相关词时,可以考虑动态规划。 7 | 8 | ``` 9 | 1. 求最大值或者最小值 10 | 2. 判断方案是否可行 11 | 3. 统计方案的个数 12 | ``` 13 | * 动态规划四要素 14 | 15 | ``` 16 | 1. 划分状态 state,确定f[i], f[i][j]的意义; 17 | 2. 状态转化 function,确定f[i]和f[i - 1]的关系; 18 | 3. 初始状态 initialization; 19 | 4. 边界条件 确定求解最大状态是什么? 20 | ``` 21 | 22 | * 动态规划模板 23 | 24 | 动态规划没有直接的模板,但是可以通过fibonacci来理解动态规划的基本过程。 25 | 26 | ```java 27 | public static long fibonacciDP(int n) { 28 | long[] results = new long[n+1]; 29 | results[0] = 1; 30 | results[1] = 1; 31 | for (int i = 2; i <= n; i++) { 32 | results[i] = results[i-1] + results[i-2]; 33 | } 34 | return results[n]; 35 | } 36 | ``` 37 | 38 | ### 343. Integer Break [微信总结连接](https://mp.weixin.qq.com/s?__biz=MzAwMDk1MTUyNw==&mid=2247483903&idx=1&sn=7547ab490ba22d4a119eeb30e767b65f&chksm=9ae05477ad97dd6130b3d4b3f543545b4d2d7d5336e738fd6556c5fa3342fd5fc1e2ceea5772&scene=21#wechat_redirect) 39 | 40 | 题目描述 41 | -- 42 | 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. 43 | 44 | For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). 45 | 46 | Note: You may assume that n is not less than 2 and not larger than 58. 47 | 48 | 注意: 题目要求至少要讲该数字分成两部分。比如2 ,一定要分成 1 + 1, 不能分成 2 + 0 。 所以当n = 2的时候,结果应该是 1 49 | 50 | 51 | 思路解析 52 | -- 53 | 这个题目完全可以用《139. work break》分析的思路解决。 54 | 55 | * 一. 使用暴力搜索 + 缓存 56 | n 的组合的乘积的最大值 应该是 如下两个值中取最大值:x * (n - x) 和 x * f(n -x), 其中 x = 0 -> n - 1。 57 | 58 | 举个例子,假设n = 10 : 59 | 当x = 1,其最大值在 1 * ( 10 - 1 ) = 9 和 1 * f(9) 之间 60 | 当x = 2,其最大值在 2 * ( 10 - 2) = 16 和 2 * f(8) 之间 61 | ... 62 | 当 x = 9,其最大值在 9 * (10-9) = 9 和 9 * f(1) 之间 63 | 64 | 然后在上叙最大值集合中找最大值,其就是结果。 65 | 66 | 任何算法都可以通过暴力搜索的基础上优化得到。我们在上面的分析中可以发现, f(x) 会被多次计算。只要将f(x)的结果缓存起来(使用 Hash Table 或者数组都行),就能减少运算次数。具体请看后面的代码。 67 | 68 | * 二. 使用自底向上的DP写法 69 | 其思路跟暴力搜索差不多,不同的是,暴力搜索的小标是从 n - 1 -> 1; 自底向上的写法的小标是从 1 -> n - 1, 从叶节点出发,先计算分支情况。 70 | 71 | 将动态规划问题分解成子问题时,有*自底向上*和*自顶向下*的两种方法: 72 | 1. 自顶向下 其实就是从 根节点出发 ,深度优先搜索 一颗树 。这样复杂度是降低的,因为每次进入新的一个节点,状态是减少的。 73 | 2. 自底向上 是从 叶子节点出发 ,将结果汇聚到 跟节点,这样的好处是处理 很多 支路 重复的情况 ,这也是DP比较关键的有点:寻找重叠的子问题。重叠的子问题,映射到数上,就是 结果重复的分支。 74 | 75 | * 三. 数学解法 76 | 这道题目的数学解法比较的有意思,而且有很多版本。 77 | 78 | * 数学解法的第一个版本, 要求符合条件的组合的最大值,其实就是不断的将 n 分解成 3 的倍数。举个例子: 79 | 当 n = 10 的时候, 最大值一定是 3 + 7 (7 还没有分); 80 | 当 n = 7 的时候,最大值一定是 3 + 4( 4 分成 2 x 2 , 唯一特殊的数字) 81 | 当 n = 10 的时候, 3 + 3 + 4 是符合条件的组合, 结果 3 * 3 * 4 = 36 82 | 83 | * 数学揭发的第二个版本,最佳的结果其实是按照 3 来循环的,具体请看下图 (@M.renard) ![](./images/image3.jpeg) 84 | 85 | * 数学解法的第三个版本, 思路是 f(n) = max{ f(n - 2) * 2, f(n -3) *3} (@D@vid) 86 | 87 | * 四. 严格数学证明 88 | 设把N分成x份,则最大乘积为f(x) = (N/x)^x。 89 | f(x)对x求导,可以得到 90 | f'(x) = (N/x)^x * (ln (N/x) - 1) 91 | 令 f'(x) = 0, 求得 N/x = e 约等于2.7 92 | 所以,如果这题可以分解成小数,尽量分解成自然对数2.7 93 | 而2.7最近的整数就是2和3. 94 | 2*2*2 < 3*3 95 | 所以如果分成整数,尽量分分解成3。 96 | 边界需要注意1,2,3,4,5。 97 | 98 | 深入讨论 99 | -- 100 | 这个问题展示了一步步分析总结,得出动态规划解法和数学解法的过程,题目解法并不唯一。 101 | 102 | 1. 熟悉 自顶向下思考 和 自底向上 写代码的方法以后,DP问题不再是不可解决的问题 103 | 2. 从简单到复杂,归纳总结,可以得出一些特别快速的数学方法。比如 104 | 3. 第二个数学解法的时间复杂度几乎是O(1) 105 | 106 | 代码提交 107 | -- 108 | 可以查看[文件夹](./images)下面的图片,查看各个群友的提交。 109 | 110 | 111 | 更多例题: 112 | #### [Leetcode 53 最大子数组](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_DP/leetcode/maximumSubarray.java) 113 | #### [Leetcode 70 爬楼梯](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_DP/leetcode/climbingStairs.java) 114 | #### [Leetcode 198 入室抢劫](https://github.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/blob/master/chapter_DP/leetcode/houseRobber.java) 115 | -------------------------------------------------------------------------------- /chapter_DP/images/image1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image1.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image10ruby.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image10ruby.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image11java.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image11java.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image12java.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image12java.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image13java.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image13java.png -------------------------------------------------------------------------------- /chapter_DP/images/image14ruby.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image14ruby.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image2.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image3.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image3.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image4.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image4.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image5.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image5.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image6ruby.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image6ruby.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image7ruby.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image7ruby.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image8ruby.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image8ruby.jpeg -------------------------------------------------------------------------------- /chapter_DP/images/image9ruby.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/images/image9ruby.jpeg -------------------------------------------------------------------------------- /chapter_DP/leetcode/.perfectSquares.java.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_DP/leetcode/.perfectSquares.java.swp -------------------------------------------------------------------------------- /chapter_DP/leetcode/burstBallons.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxCoins(int[] iNums) { 3 | int[] nums = new int[iNums.length + 2]; 4 | int n = 1; 5 | for (int x : iNums) if (x > 0) nums[n++] = x; 6 | nums[0] = nums[n++] = 1; 7 | 8 | 9 | int[][] dp = new int[n][n]; 10 | for (int k = 2; k < n; ++k) 11 | for (int left = 0; left < n - k; ++left) { 12 | int right = left + k; 13 | for (int i = left + 1; i < right; ++i) 14 | dp[left][right] = Math.max(dp[left][right], 15 | nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right]); 16 | } 17 | 18 | return dp[0][n - 1]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /chapter_DP/leetcode/climbStairs.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int climbStairs(int n) { 3 | int res = 0; 4 | if(n == 0) return res; 5 | if(n == 1) return 1; 6 | if(n == 2) return 2; 7 | int []stairs = new int[n+1]; 8 | stairs[0] = 0; 9 | stairs[1] = 1; 10 | stairs[2] = 2; 11 | for(int i = 3; i <= n; i++){ 12 | stairs[i] = stairs[i-2] + stairs[i-1]; 13 | } 14 | return stairs[n]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /chapter_DP/leetcode/countingBits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] countBits(int num) { 3 | int [] result = new int[num + 1]; 4 | for(int i=1; i<=num; i++){ 5 | result[i] = result[i >> 1] + (i&1); 6 | } 7 | return result; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /chapter_DP/leetcode/houseRobber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | int ifRobPrevious = 0; 4 | int ifNotRobPrevious = 0; 5 | for(int i=0; i 0; 4 | int max = A[0], min = A[0], maxAns = A[0]; 5 | for(int i=1; i=count[0]; i--){ 7 | for(int j=n; j>=count[1]; j--){ 8 | dp[i][j] = Math.max(dp[i][j], 1 + dp[i-count[0]][j-count[1]]); 9 | } 10 | } 11 | } 12 | return dp[m][n]; 13 | } 14 | 15 | public int [] getCounts(String str){ 16 | int [] count = new int[2]; 17 | for(int i=0; i= 0) { 10 | min = Math.min(min, dp[i - j*j] + 1); 11 | j++; 12 | } 13 | dp[i] = min; 14 | } 15 | return dp[n]; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /chapter_DP/leetcode/regularExpressionMatching.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isMatch(String s, String p) { 3 | boolean dp[][] = new boolean[s.length()+1][p.length()+1]; 4 | dp[0][0]=true; 5 | for(int i=1; i=0; r--){ 7 | for(int c= n-1; c>=0; c--){ 8 | mat[r][c] = mat[r+1][c] + mat[r][c+1]; 9 | } 10 | } 11 | return mat[0][0]; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /chapter_DP/leetcode/uniquePathTwo.java: -------------------------------------------------------------------------------- 1 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 2 | int m = obstacleGrid.length; 3 | if (m == 0) return 0; 4 | int n = obstacleGrid[0].length; 5 | int[][] mat = new int[m + 1][n + 1]; 6 | mat[m - 1][n] = 1; 7 | for (int r = m - 1; r >= 0; r--) { 8 | for (int c = n - 1; c >= 0; c--) { 9 | mat[r][c] = (obstacleGrid[r][c] == 1) ? 0 : mat[r][c+1] + mat[r+1][c]; 10 | } } 11 | return mat[0][0]; 12 | } 13 | 14 | class Solution { 15 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 16 | int m = obstacleGrid.length; 17 | int n = obstacleGrid[0].length; 18 | int [][] dp = new int [m][n]; 19 | dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1; 20 | for(int i = 1; i 36 | 因此,从上面的描述中我们可以发现,直接插入排序可以用两个循环完成: 37 | 1. 第一层循环:遍历待比较的所有数组元素 38 | 2. 第二层循环:将本轮选择的元素(selected)与已经排好序的元素(ordered)相比较。 39 | 如果:selected > ordered,那么将二者交换 40 | - 代码实现 41 | 42 | void insert_sort(int[] nums) { 43 | if (nums == null || nums.length == 0) { 44 | return; 45 | } 46 | for (int i = 1; i < nums.length; i++) { 47 | for (int j = i - 1; j >= 0; j--) { 48 | if (nums[j + 1] < nums[j]) { 49 | int temp = nums[j + 1]; 50 | nums[j + 1] = nums[j]; 51 | nums[j] = temp; 52 | } 53 | } 54 | } 55 | } 56 | 57 | ### 希尔排序 58 | - 算法思想 59 | ![希尔排序.png](http://upload-images.jianshu.io/upload_images/1156494-80700e24aed3d83e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 60 | 61 | - 希尔排序的算法思想:将待排序数组按照步长gap进行分组,然后将每组的元素利用直接插入排序的方法进行排序;每次将gap折半减小,循环上述操作;当gap=1时,利用直接插入,完成排序。 62 | 同样的:从上面的描述中我们可以发现:希尔排序的总体实现应该由三个循环完成: 63 | 1. 第一层循环:将gap依次折半,对序列进行分组,直到gap=1 64 | 2. 第二、三层循环:也即直接插入排序所需要的两次循环。具体描述见上。 65 | 66 | - 代码实现 67 | 68 | ### 简单选择排序 69 | - 算法思想 70 | 71 | ![简单选择排序.gif](http://upload-images.jianshu.io/upload_images/1156494-25821a7cb5aec881.gif?imageMogr2/auto-orient/strip) 72 | 73 | 简单选择排序的基本思想:比较+交换。 74 | 1. 从待排序序列中,找到关键字最小的元素; 75 | 2.  如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换; 76 | 3. 从余下的 N - 1 个元素中,找出关键字最小的元素,重复(1)、(2)步,直到排序结束。 77 | 因此我们可以发现,简单选择排序也是通过两层循环实现。 78 | 第一层循环:依次遍历序列当中的每一个元素 79 | 第二层循环:将遍历得到的当前元素依次与余下的元素进行比较,符合最小元素的条件,则交换。 80 | 81 | - 代码实现 82 | 83 | ### 堆排序 84 | * 堆的概念 85 | 86 | 堆:本质是一种数组对象。特别重要的一点性质:任意的叶子节点小于(或大于)它所有的父节点。对此,又分为大顶堆和小顶堆,大顶堆要求节点的元素都要大于其孩子,小顶堆要求节点元素都小于其左右孩子,两者对左右孩子的大小关系不做任何要求。 87 | 88 | 利用堆排序,就是基于大顶堆或者小顶堆的一种排序方法。下面,我们通过大顶堆来实现。 89 | 90 | * 基本思想: 91 | 堆排序可以按照以下步骤来完成: 92 | 1. 首先将序列构建称为大顶堆; 93 | (这样满足了大顶堆那条性质:位于根节点的元素一定是当前序列的最大值) 94 | 95 | ![构建大顶堆.png](http://upload-images.jianshu.io/upload_images/1156494-596eee6397817ca2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 96 | 97 | 2. 取出当前大顶堆的根节点,将其与序列末尾元素进行交换; 98 | (此时:序列末尾的元素为已排序的最大值;由于交换了元素,当前位于根节点的堆并不一定满足大顶堆的性质) 99 | 3. 对交换后的n-1个序列元素进行调整,使其满足大顶堆的性质; 100 | 101 | ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/1156494-7e5c63ce1ed48ebf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 102 | 103 | 4. 重复2.3步骤,直至堆中只有1个元素为止 104 | 105 | * 代码实现: 106 | 107 | ### 冒泡排序 108 | - 算法思想 109 | 110 | ![冒泡排序.gif](http://upload-images.jianshu.io/upload_images/1156494-fef2b2e3edc03289.gif?imageMogr2/auto-orient/strip) 111 | 112 | 冒泡排序思路比较简单: 113 | 1. 将序列当中的左右元素,依次比较,保证右边的元素始终大于左边的元素; 114 | ( 第一轮结束后,序列最后一个元素一定是当前序列的最大值;) 115 | 2. 对序列当中剩下的n-1个元素再次执行步骤1。 116 | 3. 对于长度为n的序列,一共需要执行n-1轮比较 117 | (利用while循环可以减少执行次数) 118 | 119 | - 代码实现 120 | 121 | ### 快速排序 122 | - 算法思想 123 | 124 | ![快速排序.gif](http://upload-images.jianshu.io/upload_images/1156494-2d150e5550b700fa.gif?imageMogr2/auto-orient/strip) 125 | 126 | 快速排序的基本思想:**挖坑填数+分治法** 127 | 1. 从序列当中选择一个基准数(pivot) 128 | 在这里我们选择序列当中第一个数最为基准数 129 | 2. 将序列当中的所有数依次遍历,比基准数大的位于其右侧,比基准数小的位于其左侧 130 | 3. 重复步骤1.2,直到所有子集当中只有一个元素为止。 131 | 132 | - 代码实现 133 | 134 | ### 归并排序 135 | - 算法思想 136 | 137 | ![归并排序.gif](http://upload-images.jianshu.io/upload_images/1156494-0597aa6877e219f0.gif?imageMogr2/auto-orient/strip) 138 | 139 | 1. 归并排序是建立在归并操作上的一种有效的排序算法,该算法是采用**分治法**的一个典型的应用。它的基本操作是:将已有的子序列合并,达到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。 140 | 141 | 2. 归并排序其实要做两件事: 142 | * 分解----将序列每次**折半拆分** 143 | * 合并----将划分后的序列段**两两排序合并** 144 | 因此,归并排序实际上就是两个操作,拆分+合并 145 | 146 | 3. 如何合并? 147 | L[first...mid]为第一段,L[mid+1...last]为第二段,并且两端已经有序,现在我们要将两端合成达到L[first...last]并且也有序。 148 | * 首先依次从第一段与第二段中取出元素比较,将较小的元素赋值给temp[] 149 | * 重复执行上一步,当某一段赋值结束,则将另一段剩下的元素赋值给temp[] 150 | * 此时将temp[]中的元素复制给L[],则得到的L[first...last]有序 151 | 152 | 4. 如何分解? 153 | 在这里,我们采用递归的方法,首先将待排序列分成A,B两组;然后重复对A、B序列 154 | 分组;直到分组后组内只有一个元素,此时我们认为组内所有元素有序,则分组结束。 155 | 156 | - 代码实现 157 | 158 | ### 基数排序 159 | - 算法思想 160 | 161 | ![基数排序.gif](http://upload-images.jianshu.io/upload_images/1156494-70872a75238d1269.gif?imageMogr2/auto-orient/strip) 162 | 163 | 1. 基数排序:通过序列中各个元素的值,对排序的N个元素进行若干趟的“分配”与“收集”来实现排序。 164 | 165 | **分配**:我们将L[i]中的元素取出,首先确定其个位上的数字,根据该数字分配到与之序号相同的桶中 166 | 167 | **收集**:当序列中所有的元素都分配到对应的桶中,再按照顺序依次将桶中的元素收集形成新的一个待排序列L[ ] 168 | 对新形成的序列L[]重复执行分配和收集元素中的十位、百位...直到分配完该序列中的最高位,则排序结束 169 | 170 | 2. 根据上述“基数排序”的展示,我们可以清楚的看到整个实现的过程 171 | 172 | - 代码实现 173 | 174 | 175 | ### 参考资料 176 | * LeeLom简书:[数据结构常见的八大排序算法(详细整理)](http://www.jianshu.com/p/7d037c332a9d) 177 | * 数据结构可视化:[visualgo](http://zh.visualgo.net/) 178 | * 希尔排序介绍:[希尔排序](http://www.cnblogs.com/jingmoxukong/p/4303279.html) 179 | * 堆排序:[[《算法导论》读书笔记之第6章 堆排序](http://www.cnblogs.com/Anker/archive/2013/01/23/2873422.html)](http://www.cnblogs.com/Anker/archive/2013/01/23/2873422.html) 180 | * 博客园:[静默虚空](http://home.cnblogs.com/u/jingmoxukong/) 181 | * 博客:[vincent-cws](http://blog.chinaunix.net/uid/21457204.html) -------------------------------------------------------------------------------- /chapter_Tree/.README.md.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_Tree/.README.md.swp -------------------------------------------------------------------------------- /chapter_Tree/images/bst.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_Tree/images/bst.jpg -------------------------------------------------------------------------------- /chapter_Tree/leetcode/.bstMaxPathSum.java.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_Tree/leetcode/.bstMaxPathSum.java.swp -------------------------------------------------------------------------------- /chapter_Tree/leetcode/balancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 问题链接: 3 | * Definition for a binary tree node. 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class Solution { 12 | public boolean isBalanced(TreeNode root) { 13 | if(root == null) return true; 14 | int left = treeHeight(root.left); 15 | int right = treeHeight(root.right); 16 | return Math.abs(left-right)<=1 && isBalanced(root.left) && isBalanced(root.right); 17 | } 18 | //O(N^2)time & O(N) space because of the height recalculation 19 | public int treeHeight(TreeNode root){ 20 | if(root == null) return 0; 21 | return Math.max(treeHeight(root.left), treeHeight(root.right))+1; 22 | } 23 | 24 | } 25 | 26 | // pass -1 to represent if the tree is unbalanced, this is 27 | // a bottom-up approach 28 | public boolean isBalanced(TreeNode root) { 29 | return maxDepth(root) != -1; 30 | } 31 | private int maxDepth(TreeNode root) { 32 | if (root == null) return 0; 33 | int L = maxDepth(root.left); 34 | if (L == -1) return -1; 35 | int R = maxDepth(root.right); 36 | if (R == -1) return -1; 37 | return (Math.abs(L - R) <= 1) ? (Math.max(L, R) + 1) : -1; 38 | } 39 | 40 | // 41 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/bstIterator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Source: https://discuss.leetcode.com/topic/6575/my-solutions-in-3-languages-with-stack 3 | * Definition for binary tree 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | * 11 | * calling next() will return the next smallest number in the BST 12 | * next() and hasNext() should run in O(1) and use O(h), where h is the height of the tree 13 | */ 14 | 15 | public class BSTIterator { 16 | private Stackstack = new Stack(); 17 | public BSTIterator(TreeNode root) { 18 | pushAll(root); 19 | } 20 | 21 | /** @return whether we have a next smallest number */ 22 | public boolean hasNext() { 23 | return !stack.isEmpty(); 24 | } 25 | 26 | /** @return the next smallest number */ 27 | public int next() { 28 | TreeNode tmpNode = stack.pop(); 29 | pushAll(tmpNode.right); 30 | return tmpNode.val; 31 | } 32 | 33 | private void pushAll(TreeNode node){ 34 | for(;node != null; stack.push(node), node = node.left); 35 | } 36 | } 37 | 38 | /** 39 | * Your BSTIterator will be called like this: 40 | * BSTIterator i = new BSTIterator(root); 41 | * while (i.hasNext()) v[f()] = i.next(); 42 | */ 43 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/bstLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List> levelOrder(TreeNode root) { 12 | List> res = new ArrayList<>(); 13 | if (root == null) return res; 14 | Queue queue = new LinkedList<>(); 15 | queue.add(root); 16 | while (!queue.isEmpty()) { 17 | List level = new ArrayList<>(); 18 | int cnt = queue.size(); 19 | for (int i = 0; i < cnt; i++) { 20 | TreeNode node = queue.poll(); 21 | level.add(node.val); 22 | if (node.left != null) { 23 | queue.add(node.left); 24 | } 25 | if (node.right != null) { 26 | queue.add(node.right); 27 | } 28 | } 29 | res.add(level); 30 | } 31 | return res; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/bstMaxPathSum.java: -------------------------------------------------------------------------------- 1 | /**Source: https://leetcode.com/problems/binary-tree-maximum-path-sum/#/solutions 2 | * 问题链接:https://leetcode.com/problems/binary-tree-maximum-path-sum/#/description 3 | * Definition for a binary tree node. 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class Solution { 12 | int maxValue; 13 | public int maxPathSum(TreeNode root) { 14 | maxValue = Integer.MIN_VALUE; 15 | maxPathDown(root); 16 | return maxValue; 17 | } 18 | 19 | private int maxPathDown(TreeNode node){ 20 | if(node == null) return 0; 21 | int left = Math.max(0, maxPathDown(node.left)); 22 | int right = Math.max(0, maxPathDown(node.right)); 23 | maxValue = Math.max(maxValue, left + right + node.val); 24 | return Math.max(left,right) + node.val; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/bstPaths.java: -------------------------------------------------------------------------------- 1 | /** 2 | *Source: https://discuss.leetcode.com/topic/21474/accepted-java-simple-solution-in-8-lines 3 | *问题链接:https://leetcode.com/problems/binary-tree-paths/#/solutions 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public List binaryTreePaths(TreeNode root) { 14 | List result = new ArrayList(); 15 | if(root!=null)searchBT(root, "", result); 16 | return result; 17 | } 18 | 19 | private void searchBT(TreeNode root, String path, Listresult){ 20 | if(root.left == null && root.right == null) result.add(path + root.val); 21 | if(root.left != null ) searchBT(root.left, path + root.val + "->", result); 22 | if(root.right != null) searchBT(root.right, path + root.val + "->", result); 23 | } 24 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/closestValue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int closestValue(TreeNode root, double target) { 12 | int a = root.val; 13 | TreeNode kid = target < a ? root.left : root.right; 14 | if (kid == null) return a; 15 | int b = closestValue(kid, target); 16 | return Math.abs(a - target) < Math.abs(b - target) ? a : b; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/closestValueTwo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List closestKValues(TreeNode root, double target, int k) { 12 | List res = new ArrayList<>(); 13 | Stack s1 = new Stack<>(); 14 | Stack s2 = new Stack<>(); 15 | 16 | inorder(root, target, false, s1); 17 | inorder(root, target, true, s2); 18 | 19 | while ( k-- > 0) { 20 | if (s1.isEmpty()) 21 | res.add(s2.pop()); 22 | else if (s2.isEmpty()) 23 | res.add(s1.pop()); 24 | else if (Math.abs(s1.peek() - target) < Math.abs(s2.peek() - target )) 25 | res.add(s1.pop()); 26 | else 27 | res.add(s2.pop()); 28 | } 29 | 30 | return res; 31 | } 32 | 33 | void inorder(TreeNode root, double target, boolean reverse, Stack stack) { 34 | if (root == null) return; 35 | inorder(reverse ? root.right: root.left, target, reverse, stack); 36 | if ((reverse && root.val <= target) || (!reverse && root.val > target)) return; 37 | stack.push(root.val); 38 | inorder(reverse ? root.left: root.right, target, reverse, stack); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/countNodes.java: -------------------------------------------------------------------------------- 1 | //Source: https://leetcode.com/problems/count-complete-tree-nodes/#/solutions 2 | 3 | public class Solution { 4 | public int height(TreeNode root){ 5 | return root==null? -1 : 1+ height(root.left); 6 | } 7 | public int countNodes(TreeNode root){ 8 | int h = height(root); 9 | return h < 0 ? 0 : height(root.right)==h-1 ? (1< root.val) { 18 | root.right = deleteNode(root.right, key); 19 | }else{ 20 | if(root.left == null){ 21 | return root.right; 22 | }else if(root.right == null){ 23 | return root.left; 24 | } 25 | 26 | TreeNode minNode = findMin(root.right); 27 | root.val = minNode.val; 28 | root.right = deleteNode(root.right, root.val); 29 | } 30 | return root; 31 | } 32 | 33 | private TreeNode findMin(TreeNode node) { 34 | while(node.left != null) { 35 | node = node.left; 36 | } 37 | return node; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/findBottomLeftValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Question Source: https://leetcode.com/problems/find-bottom-left-tree-value/#/description 3 | * Solution Source: https://discuss.leetcode.com/topic/78981/right-to-left-bfs-python-java 4 | * 5 | * Definition for a binary tree node. 6 | * public class TreeNode { 7 | * int val; 8 | * TreeNode left; 9 | * TreeNode right; 10 | * TreeNode(int x) { val = x; } 11 | * } 12 | */ 13 | public class Solution { 14 | // (非常聪明的广度优先搜索改写) 15 | public int findBottomLeftValue(TreeNode root) { 16 | Queue queue = new LinkedList<>(); 17 | queue.add(root); 18 | while(!queue.isEmpty()){ 19 | root = queue.poll(); 20 | if(root.right != null) 21 | queue.add(root.right); 22 | if(root.left != null) 23 | queue.add(root.left); 24 | } 25 | return root.val; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/findKthSmallest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int kthSmallest(TreeNode root, int k) { 12 | int count = countNodes(root.left); 13 | if (k <= count) { 14 | return kthSmallest(root.left, k); 15 | } else if (k > count + 1) { 16 | return kthSmallest(root.right, k - 1 - count); 17 | } 18 | return root.val; 19 | } 20 | 21 | public int countNodes(TreeNode n){ 22 | if(n == null) return 0; 23 | return 1 + countNodes(n.left) + countNodes(n.right); 24 | } 25 | /** 26 | * Definition for a binary tree node. 27 | * public class TreeNode { 28 | * int val; 29 | * TreeNode left; 30 | * TreeNode right; 31 | * TreeNode(int x) { val = x; } 32 | * } 33 | */ 34 | public class Solution { 35 | private static int number = 0; 36 | private static int count = 0; 37 | 38 | public int kthSmallest(TreeNode root, int k) { 39 | count = k; 40 | helper(root); 41 | return number; 42 | } 43 | 44 | private void helper(TreeNode n) { 45 | if (n.left != null) helper(n.left); 46 | count--; 47 | if(count == 0) { 48 | number = n.val; 49 | return; 50 | } 51 | if (n.right != null) helper(n.right); 52 | } 53 | }} 54 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/flattenTree.java: -------------------------------------------------------------------------------- 1 | private TreeNode prev = null; 2 | 3 | public void flatten(TreeNode root) { 4 | if (root == null) 5 | return; 6 | flatten(root.right); 7 | flatten(root.left); 8 | root.right = prev; 9 | root.left = null; 10 | prev = root; 11 | } 12 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/implementTrie.java: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | public boolean isWord; 3 | public TrieNode[] children = new TrieNode[26]; 4 | public TrieNode() {} 5 | } 6 | public class Trie { 7 | private TrieNode root; 8 | public Trie() { 9 | root = new TrieNode(); 10 | } 11 | 12 | 13 | /** Inserts a word into the trie. */ 14 | public void insert(String word) { 15 | TrieNode ws = root; 16 | for(int i=0; i inorderTraversal(TreeNode root) { 12 | Listresult = new LinkedList<>(); 13 | if(root==null) return result; 14 | helper(root, result); 15 | return result; 16 | } 17 | 18 | public void helper(TreeNode root, Listresult){ 19 | if(root == null) return; 20 | helper(root.left, result); 21 | result.add(root.val); 22 | helper(root.right, result); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/inorderSuccessor.java: -------------------------------------------------------------------------------- 1 | public TreeNode successor(TreeNode root, TreeNode p) { 2 | if (root == null) 3 | return null; 4 | 5 | if (root.val <= p.val) { 6 | return successor(root.right, p); 7 | } else { 8 | TreeNode left = successor(root.left, p); 9 | return (left != null) ? left : root; 10 | } 11 | } 12 | public TreeNode predecessor(TreeNode root, TreeNode p) { 13 | if (root == null) 14 | return null; 15 | 16 | if (root.val >= p.val) { 17 | return predecessor(root.left, p); 18 | } else { 19 | TreeNode right = predecessor(root.right, p); 20 | return (right != null) ? right : root; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/invertTree.java: -------------------------------------------------------------------------------- 1 | //第一种写法使用了递归深度优先搜索 但当树结构太大时有可能导致栈溢出 2 | //第二种写法为优化后的使用自定义队列的广度优先搜索 3 | public TreeNode invertTree(TreeNode root){ 4 | if(root == null) { 5 | return null; 6 | } 7 | final TreeNode left = root.left, 8 | right = root.right; 9 | root.left = invertTree(right); 10 | root.right = invertTree(left); 11 | return root; 12 | 13 | } 14 | public TreeNode invertTree(TreeNode root) { 15 | 16 | if (root == null) { 17 | return null; 18 | } 19 | 20 | final Queue queue = new LinkedList<>(); 21 | queue.offer(root); 22 | 23 | while(!queue.isEmpty()) { 24 | final TreeNode node = queue.poll(); 25 | final TreeNode left = node.left; 26 | node.left = node.right; 27 | node.right = left; 28 | 29 | if(node.left != null) { 30 | queue.offer(node.left); 31 | } 32 | if(node.right != null) { 33 | queue.offer(node.right); 34 | } 35 | } 36 | return root; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/isSameTree.java: -------------------------------------------------------------------------------- 1 | public boolean isSameTree(TreeNode p, TreeNode 1){ 2 | if(p==null && q==null) return true; 3 | if(p==null || q==null) return false; 4 | if(p.val == q.val) 5 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);; 6 | return false; 7 | } 8 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/kthLargestElement.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapter_Tree/leetcode/kthLargestElement.java -------------------------------------------------------------------------------- /chapter_Tree/leetcode/largestValues.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public List largestValues(TreeNode root) { 12 | List res = new ArrayList<>(); 13 | if(root== null) return res; 14 | helper(res, root, 0); 15 | return res; 16 | } 17 | 18 | public void helper(List res, TreeNode node, int d){ 19 | if(node==null) return; 20 | if(res.size() == d){ 21 | res.add(node.val); 22 | }else{ 23 | res.set(d, Math.max(node.val, res.get(d))); 24 | } 25 | helper(res, node.left, d+1); 26 | helper(res, node.right, d+1); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/longestConsecutive.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | private int max = 0; 12 | public int longestConsecutive(TreeNode root) { 13 | if(root == null) return 0; 14 | helper(root, 0, root.val); 15 | return max; 16 | } 17 | 18 | public void helper(TreeNode root, int cur, int target) { 19 | if(root == null) return; 20 | if(root.val == target) cur++; 21 | else cur = 1; 22 | max = Math.max(cur, max); 23 | helper(root.left, cur, root.val + 1); 24 | helper(root.right, cur, root.val + 1); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/lowestCommonAncestor.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Definition for a binary tree node. 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | */ 11 | class Solution { 12 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 13 | if (root == null || root == p || root == q) return root; 14 | TreeNode left = lowestCommonAncestor(root.left, p, q); 15 | TreeNode right = lowestCommonAncestor(root.right, p, q); 16 | return left == null ? right : right == null ? left : root; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/lowestCommonAncestorBinary.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 | if(root == p || root == q || root == null) return root; 13 | TreeNode left = lowestCommonAncestor(root.left, p, q); 14 | TreeNode right = lowestCommonAncestor(root.right, p, q); 15 | if(left == null){ 16 | return right; 17 | }else if(right==null){ 18 | return left; 19 | }else{ 20 | return root; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/maxDepth.java: -------------------------------------------------------------------------------- 1 | public int maxDepth(TreeNode root){ 2 | if(root == null) return 0; 3 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 4 | } 5 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/minDepth.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | //O(n) running time and O(logN) space 12 | public int minDepth(TreeNode root) { 13 | if(root == null) return 0; 14 | int left = minDepth(root.left); 15 | int right = minDepth(root.right); 16 | return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1; 17 | 18 | } 19 | } 20 | //O(N) running time and O(N) space with with BFS 21 | 22 | public int minDepth(TreeNode root) { 23 | public int minDepth(TreeNode root) { 24 | if(root==null) return 0; 25 | Queue q = new LinkedList<>(); 26 | q.add(root); 27 | TreeNode rightMost = root; 28 | int depth = 1; 29 | while(!q.isEmpty()){ 30 | TreeNode node = q.poll(); 31 | if(node.left==null && node.right==null) break; 32 | if(node.left!=null) q.add(node.left); 33 | if(node.right!=null) q.add(node.right); 34 | if(node==rightMost){ 35 | depth++; 36 | rightMost = (node.right!=null) ? node.right : node.left; 37 | } 38 | } 39 | return depth; 40 | } 41 | 42 | } 43 | 44 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/orderBuildTree.java: -------------------------------------------------------------------------------- 1 | public TreeNode buildTree(int[] preorder, int[] inorder) { 2 | if(preorder.length!=inorder.length) return null; 3 | return build(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1); 4 | } 5 | 6 | public TreeNode build(int [] preorder, int preLow, int preHigh, int[] inorder, int inLow, int inHigh){ 7 | if(preLow>preHigh || inLow>inHigh) return null; 8 | TreeNode root = new TreeNode(preorder[preLow]); 9 | 10 | int inorderRoot = inLow; 11 | for(int i=inLow;i<=inHigh;i++){ 12 | if(inorder[i]==root.val){ inorderRoot=i; break; } 13 | } 14 | 15 | int leftTreeLen = inorderRoot-inLow; 16 | root.left = build(preorder, preLow+1, preLow+leftTreeLen, inorder, inLow, inorderRoot-1); 17 | root.right = build(preorder, preLow+leftTreeLen+1, preHigh, inorder, inorderRoot+1, preHigh); 18 | return root; 19 | } 20 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/pathSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean hasPathSum(TreeNode root, int sum) { 12 | if(root==null) return false; 13 | if(root.left == null && root.right == null) return sum == root.val; 14 | return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right,sum-root.val); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/pathSumThree.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int pathSum(TreeNode root, int sum) { 3 | if (root == null) return 0; 4 | return pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); 5 | } 6 | 7 | private int pathSumFrom(TreeNode node, int sum) { 8 | if (node == null) return 0; 9 | return (node.val == sum ? 1 : 0) 10 | + pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val); 11 | } 12 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/pathSumTwo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public List> pathSum(TreeNode root, int sum) { 12 | List>res = new ArrayList>(); 13 | List currentList = new ArrayList<>(); 14 | helper(root, sum, res, currentList); 15 | return res; 16 | } 17 | 18 | public void helper(TreeNode node, int sum, List> res, List currentList){ 19 | if(node==null) return; 20 | currentList.add(node.val); 21 | if(node.left == null && node.right == null && node.val == sum) { 22 | res.add(new ArrayList(currentList)); 23 | }else{ 24 | helper(node.left, sum - node.val, res, currentList); 25 | helper(node.right, sum - node.val, res, currentList); 26 | } 27 | currentList.remove(currentList.size() - 1); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/populatingNextRight.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * public class TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode left, right, next; 6 | * TreeLinkNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public void connect(TreeLinkNode root) { 11 | if(root == null || root.left == null) return; 12 | connectNodes(root.left, root.right); 13 | } 14 | public void connectNodes(TreeLinkNode p, TreeLinkNode q){ 15 | p.next = q; 16 | if(p.left!=null){ 17 | connectNodes(p.right,q.left); 18 | connectNodes(p.left,p.right); 19 | connectNodes(q.left, q.right); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/postorder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List postorderTraversal(TreeNode root) { 12 | Listresult = new LinkedList<>(); 13 | if(root==null) return result; 14 | helper(root, result); 15 | return result; 16 | } 17 | 18 | public void helper(TreeNode root, Listresult){ 19 | if(root == null) return; 20 | helper(root.left, result); 21 | helper(root.right, result); 22 | result.add(root.val); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/preorder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List preorderTraversal(TreeNode root) { 12 | Listresult = new LinkedList<>(); 13 | if(root==null) return result; 14 | helper(root, result); 15 | return result; 16 | } 17 | 18 | public void helper(TreeNode root, Listresult){ 19 | if(root == null) return; 20 | result.add(root.val); 21 | helper(root.left, result); 22 | helper(root.right, result); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/recoverBST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | TreeNode firstElement = null; 12 | TreeNode secondElement = null; 13 | TreeNode prevElement = new TreeNode(Integer.MIN_VALUE); 14 | public void recoverTree(TreeNode root) { 15 | traverse(root); 16 | int temp = firstElement.val; 17 | firstElement.val = secondElement.val; 18 | secondElement.val = temp; 19 | } 20 | 21 | private void traverse(TreeNode root){ 22 | if(root==null) return; 23 | traverse(root.left); 24 | if(firstElement == null && prevElement.val >= root.val){ 25 | firstElement = prevElement; 26 | } 27 | if(firstElement != null && prevElement.val >= root.val){ 28 | secondElement=root; 29 | } 30 | prevElement = root; 31 | traverse(root.right); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/rightSideView.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List rightSideView(TreeNode root) { 12 | List result = new ArrayList(); 13 | rightView(root, result, 0); 14 | return result; 15 | } 16 | 17 | public void rightView(TreeNode curr, List result, int currDepth){ 18 | if(curr==null){ 19 | return; 20 | } 21 | if(currDepth == result.size()){ 22 | result.add(curr.val); 23 | } 24 | rightView(curr.right, result, currDepth + 1); 25 | rightView(curr.left, result, currDepth + 1); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/serializeTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Codec { 11 | private final String NN = "X"; 12 | private final String spliter = ","; 13 | // Encodes a tree to a single string. 14 | public String serialize(TreeNode root) { 15 | StringBuilder sb = new StringBuilder(); 16 | serialBuild(root, sb); 17 | return sb.toString(); 18 | } 19 | public void serialBuild(TreeNode node, StringBuilder sb){ 20 | if(node == null){ 21 | sb.append(NN).append(spliter); 22 | }else{ 23 | sb.append(node.val).append(spliter); 24 | serialBuild(node.left, sb); 25 | serialBuild(node.right, sb); 26 | } 27 | } 28 | 29 | // Decodes your encoded data to tree. 30 | public TreeNode deserialize(String data) { 31 | Dequenodes = new LinkedList<>(); 32 | nodes.addAll(Arrays.asList(data.split(spliter))); 33 | return buildTree(nodes); 34 | } 35 | 36 | public TreeNode buildTree(Deque nodes){ 37 | String val = nodes.remove(); 38 | if(val.equals(NN))return null; 39 | TreeNode node = new TreeNode(Integer.valueOf(val)); 40 | node.left = buildTree(nodes); 41 | node.right = buildTree(nodes); 42 | return node; 43 | } 44 | } 45 | 46 | // Your Codec object will be instantiated and called as such: 47 | // Codec codec = new Codec(); 48 | // codec.deserialize(codec.serialize(root)); 49 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/sortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Source; https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/#/description 3 | * Definition for a binary tree node. 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class Solution { 12 | public TreeNode sortedArrayToBST(int[] nums) { 13 | if(nums.length == 0) return null; 14 | TreeNode head = buildTree(nums, 0, nums.length-1); 15 | return head; 16 | } 17 | 18 | public TreeNode buildTree(int[] nums, int low, int high){ 19 | if(low > high) return null; 20 | int mid = low + (high - low)/2; 21 | TreeNode node = new TreeNode(nums[mid]); 22 | node.left = buildTree(nums, low, mid-1); 23 | node.right = buildTree(nums, mid+1, high); 24 | return node; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/sortedListToBST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | /** 10 | * Definition for a binary tree node. 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode(int x) { val = x; } 16 | * } 17 | */ 18 | class Solution { 19 | public TreeNode sortedListToBST(ListNode head) { 20 | if(head == null) return null; 21 | return buildTree(head, null); 22 | } 23 | 24 | public TreeNode buildTree(ListNode head, ListNode tail){ 25 | ListNode slow = head; 26 | ListNode fast = head; 27 | if(head == tail) return null; 28 | while(fast!=tail && fast.next!=tail){ 29 | slow = slow.next; 30 | fast = fast.next.next; 31 | } 32 | TreeNode thead = new TreeNode(slow.val); 33 | thead.left = buildTree(head, slow); 34 | thead.right = buildTree(slow.next, tail); 35 | return thead; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/sumOfLeftLeaves.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int sumOfLeftLeaves(TreeNode root) { 12 | if(root == null) return 0; 13 | int ans = 0; 14 | if(root.left != null) { 15 | if(root.left.left == null && root.left.right == null) ans += root.left.val; 16 | else ans += sumOfLeftLeaves(root.left); 17 | } 18 | ans += sumOfLeftLeaves(root.right); 19 | return ans; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/sumRootToLeafNums.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int sumNumbers(TreeNode root) { 12 | return sum(root, 0); 13 | } 14 | public int sum(TreeNode root, int s){ 15 | if(root == null) return 0; 16 | if(root.left == null && root.right == null){ 17 | return s*10 + root.val; 18 | } 19 | return sum(root.left, s*10 + root.val) + sum(root.right, s*10 + root.val); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/symmetricTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Question: https://leetcode.com/problems/symmetric-tree/#/description 3 | * Solution Source: https://discuss.leetcode.com/topic/5941/recursive-and-non-recursive-solutions-in-java 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * int val; 7 | * TreeNode left; 8 | * TreeNode right; 9 | * TreeNode(int x) { val = x; } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean isSymmetric(TreeNode root) { 14 | return root == null || isSymmtricHelper(root.left, root.right); 15 | } 16 | 17 | private boolean isSymmetricHelper(TreeNode left, TreeNode right){ 18 | if(left==null||right==null) 19 | return left == right; 20 | if(left.val != right.val) 21 | return false; 22 | return isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/uniqueBST.java: -------------------------------------------------------------------------------- 1 | //问题链接: https://leetcode.com/problems/unique-binary-search-trees/#/description 2 | //Source: https://leetcode.com/problems/unique-binary-search-trees/#/solutions 3 | public class Solution { 4 | public int numTrees(int n) { 5 | int[] G = new int[n+1]; 6 | G[0] = G[1] = 1; 7 | for(int i=2; i<=n; i++){ 8 | for(int j = 1; j<=i; j++){ 9 | G[i] += G[j-1] * G[i-j]; 10 | } 11 | } 12 | return G[n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/uniqueBSTTwo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List generateTrees(int n) { 12 | if (n <= 0) return new ArrayList<>(); 13 | return generate(1, n); 14 | } 15 | 16 | private List generate(int start, int end) { 17 | if (start > end) return Arrays.asList(new TreeNode[]{null}); 18 | List ret = new ArrayList<>(); 19 | for (int i = start; i <= end; i++) { 20 | for (TreeNode left : generate(start, i - 1)) { 21 | for (TreeNode right : generate(i + 1, end)) { 22 | TreeNode root = new TreeNode(i); 23 | root.left = left; 24 | root.right = right; 25 | ret.add(root); 26 | } 27 | } 28 | } 29 | return ret; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/upsideDownBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode upsideDownBinaryTree(TreeNode root) { 12 | if(root == null || root.left == null) { 13 | return root; 14 | } 15 | 16 | TreeNode newRoot = upsideDownBinaryTree(root.left); 17 | root.left.left = root.right; 18 | root.left.right = root; 19 | root.left = null; 20 | root.right = null; 21 | return newRoot; 22 | } 23 | } 24 | public TreeNode upsideDownBinaryTree(TreeNode root) { 25 | TreeNode curr = root; 26 | TreeNode next = null; 27 | TreeNode temp = null; 28 | TreeNode prev = null; 29 | 30 | while(curr != null) { 31 | next = curr.left; 32 | 33 | // swapping nodes now, need temp to keep the previous right child 34 | curr.left = temp; 35 | temp = curr.right; 36 | curr.right = prev; 37 | 38 | prev = curr; 39 | curr = next; 40 | } 41 | return prev; 42 | } 43 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/validBST.java: -------------------------------------------------------------------------------- 1 | public boolean isValidBST(TreeNode root){ 2 | return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); 3 | } 4 | 5 | public boolean isValidBST(TreeNode root, long lowerBound, long upperBound){ 6 | if(root == null) return true; 7 | if(root.val >= upperBound || root.val <= lowerBound) return false; 8 | return isValidBST(root.left, lowerBound, root.val) && 9 | isValidBST(root.right, root.val, upperBound); 10 | } 11 | 12 | /** 13 | * Definition for a binary tree node. 14 | * public class TreeNode { 15 | * int val; 16 | * TreeNode left; 17 | * TreeNode right; 18 | * TreeNode(int x) { val = x; } 19 | * } 20 | */ 21 | public class Solution { 22 | private boolean help(TreeNode p, Integer low, Integer high) { 23 | if (p == null) return true; 24 | return (low == null || p.val > low) && (high == null || p.val < high) && help(p.left, low, p.val) && help(p.right, p.val, high); 25 | } 26 | 27 | public boolean isValidBST(TreeNode root) { 28 | return help(root, null, null); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/verifyPreorder.java: -------------------------------------------------------------------------------- 1 | public boolean verifyPreorder(int[] preorder) { 2 | int low = Integer.MIN_VALUE; 3 | Stack path = new Stack(); 4 | for (int p : preorder) { 5 | if (p < low) 6 | return false; 7 | while (!path.empty() && p > path.peek()) 8 | low = path.pop(); 9 | path.push(p); 10 | } 11 | return true; 12 | } 13 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/verticalOrder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List> verticalOrder(TreeNode root) { 12 | List> res = new ArrayList<>(); 13 | Map> map = new HashMap<>(); 14 | Queue queue = new LinkedList<>(); 15 | Queue cols = new LinkedList<>(); 16 | 17 | queue.add(root); 18 | cols.add(0); 19 | 20 | int min = 0; 21 | int max = 0; 22 | if(root == null) return res; 23 | while(!queue.isEmpty()){ 24 | TreeNode n = queue.poll(); 25 | int col = cols.poll(); 26 | if(!map.containsKey(col)){ 27 | map.put(col, new ArrayList()); 28 | } 29 | map.get(col).add(n.val); 30 | if(n.left!=null){ 31 | queue.add(n.left); 32 | cols.add(col-1); 33 | min = Math.min(min, col-1); 34 | } 35 | if(n.right!=null){ 36 | queue.add(n.right); 37 | cols.add(col+1); 38 | max = Math.max(max, col+1); 39 | } 40 | 41 | } 42 | 43 | for(int i=min; i<=max; i++){ 44 | res.add(map.get(i)); 45 | } 46 | return res; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /chapter_Tree/leetcode/zigZagTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List> zigzagLevelOrder(TreeNode root) { 12 | List> sol = new ArrayList<>(); 13 | travel(root, sol, 0); 14 | return sol; 15 | } 16 | 17 | private void travel(TreeNode curr, List>sol, int level){ 18 | if (curr == null) return; 19 | if (sol.size() <= level) 20 | { 21 | List newLevel = new LinkedList<>(); 22 | sol.add(newLevel); 23 | } 24 | 25 | List collection = sol.get(level); 26 | if(level % 2 == 0) collection.add(curr.val); 27 | else collection.add(0, curr.val); 28 | 29 | travel(curr.left, sol, level + 1); 30 | travel(curr.right, sol, level + 1); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /chapter_linkedList/README.md: -------------------------------------------------------------------------------- 1 | 链表 2 | -------------------------------------------------------------------------------- /chapter_linkedList/leetcode/addTwoNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 | ListNode dummyHead = new ListNode(0); 12 | ListNode p = l1, q = l2, curr = dummyHead; 13 | int carry = 0; 14 | while(p!=null || q!=null){ 15 | int x = (p != null) ? p.val : 0; 16 | int y = (q != null) ? q.val : 0; 17 | int digit = x + y + carry; 18 | carry = digit/10; 19 | curr.next = new ListNode(digit % 10); 20 | curr = curr.next; 21 | if(p!=null) p = p.next; 22 | if(q!=null) q = q.next; 23 | } 24 | if(carry>0){ 25 | curr.next = new ListNode(carry); 26 | } 27 | return dummyHead.next; 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /chapter_linkedList/leetcode/copyRandomPointer.java: -------------------------------------------------------------------------------- 1 | public RandomListNode copyRandomList(RandomListNode head) { 2 | Map map = new HashMap<>(); 3 | RandomListNode p = head; 4 | RandomListNode dummy = new RandomListNode(0); 5 | RandomListNode q = dummy; 6 | while (p != null) { 7 | q.next = new RandomListNode(p.label); 8 | map.put(p, q.next); 9 | p = p.next; 10 | q = q.next; 11 | } 12 | p = head; 13 | q = dummy; 14 | while (p != null) { 15 | q.next.random = map.get(p.random); 16 | p = p.next; 17 | q = q.next; 18 | } 19 | return dummy.next; 20 | } 21 | -------------------------------------------------------------------------------- /chapter_linkedList/leetcode/mergeKSorted.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode mergeKLists(ListNode[] lists) { 11 | if(lists.length==0) return null; 12 | int end = lists.length - 1; 13 | while(end > 0) { 14 | int begin = 0; 15 | while(begin < end) { 16 | lists[begin]= merge2Lists(lists[begin], lists[end]); 17 | begin++; 18 | end--; 19 | } 20 | } 21 | return lists[0]; 22 | } 23 | 24 | private ListNode merge2Lists(ListNode l1, ListNode l2){ 25 | ListNode dummyHead = new ListNode(0); 26 | ListNode p = dummyHead; 27 | while(l1 != null && l2 !=null){ 28 | if(l1.val q p r s -> q p sr 9 | */ 10 | 11 | 12 | public class Solution { 13 | public ListNode swapPairs(ListNode head) { 14 | ListNode dummy = new ListNode(0); 15 | dummy.next = head; 16 | ListNode p = head; 17 | ListNode prev = dummy; 18 | while(p!=null && p.next!=null){ 19 | ListNode q = p.next, r = p.next.next; 20 | prev.next = q; 21 | q.next = p; 22 | p.next = r; 23 | prev = p; 24 | p = r; 25 | } 26 | return dummy.next; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /chapters/.git_keeper: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/algorithmdaybyday/Practice-an-algorithm-question-every-day/aef1d86f83314c4fc2be7208375b9fbfaefef06c/chapters/.git_keeper --------------------------------------------------------------------------------