├── 3Sum.java ├── 3SumClosest.java ├── 4Sum.java ├── AddBinary.java ├── AddTwoNumbers.java ├── Anagrams.java ├── BalancedBinaryTree.java ├── BestTimetoBuyandSellStock.java ├── BestTimetoBuyandSellStockII.java ├── BestTimetoBuyandSellStockIII.java ├── BinarySearchTreeIterator.java ├── BinaryTreeInorderTraversal.java ├── BinaryTreeLevelOrderTraversal.java ├── BinaryTreeLevelOrderTraversalII.java ├── BinaryTreeMaximumPathSum.java ├── BinaryTreePostorderTraversal.java ├── BinaryTreePreorderTraversal.java ├── BinaryTreeZigzagLevelOrderTraversal.java ├── Candy.java ├── ClimbingStairs.java ├── CloneGraph.java ├── CombinationSum.java ├── CombinationSumII.java ├── Combinations.java ├── CompareVersionNumbers.java ├── ConstructBinaryTreefromInorderandPostorderTraversal.java ├── ConstructBinaryTreefromPreorderandInorderTraversal.java ├── ContainerWithMostWater.java ├── ConvertSortedArraytoBinarySearchTree.java ├── ConvertSortedListtoBinarySearchTree.java ├── CopyListwithRandomPointer.java ├── CountandSay.java ├── DecodeWays.java ├── DistinctSubsequences.java ├── DivideTwoIntegers.java ├── DungeonGame.java ├── EditDistance.java ├── EvaluateReversePolishNotation.java ├── ExcelSheetColumnNumber.java ├── ExcelSheetColumnTitle.java ├── FactorialTrailingZeroes.java ├── FindMinimumInRotatedSortedArray.java ├── FindMinimumInRotatedSortedArrayII.java ├── FindPeakElement.java ├── FirstMissingPositive.java ├── FlattenBinaryTreetoLinkedList.java ├── FractionToRecurringDecimal.java ├── GasStation.java ├── GenerateParentheses.java ├── GrayCode.java ├── ImplementstrStr().java ├── InsertInterval.java ├── InsertionSortList.java ├── IntegertoRoman.java ├── InterleavingString.java ├── IntersectionOfTwoLinkedLists.java ├── JumpGame.java ├── JumpGameII.java ├── LRUCache.java ├── LargestNumber.java ├── LargestRectangleinHistogram.java ├── LengthofLastWord.java ├── LetterCombinationsofaPhoneNumber.java ├── LinkedListCycle.java ├── LinkedListCycleII.java ├── LongestCommonPrefix.java ├── LongestConsecutiveSequence.java ├── LongestPalindromicSubstring.java ├── LongestSubstringWithoutRepeatingCharacters.java ├── LongestValidParentheses.java ├── MajorityElement.java ├── MaxPointsOnALine.java ├── MaximalRectangle.java ├── MaximumDepthofBinaryTree.java ├── MaximumGap.java ├── MaximumProductSubarray.java ├── MaximumSubarray.java ├── MedianofTwoSortedArrays.java ├── MergeIntervals.java ├── MergeSortedArray.java ├── MergeTwoSortedLists.java ├── MergekSortedLists.java ├── MinStack.java ├── MinimumDepthofBinaryTree.java ├── MinimumPathSum.java ├── MinimumWindowSubstring.java ├── MultiplyStrings.java ├── N-Queens.java ├── N-QueensII.java ├── NextPermutation.java ├── PalindromeNumber.java ├── PalindromePartitioning.java ├── PalindromePartitioningII.java ├── PartitionList.java ├── Pascal'sTriangle.java ├── Pascal'sTriangleII.java ├── PathSum.java ├── PathSum2.java ├── PermutationSequence.java ├── Permutations.java ├── PermutationsII.java ├── PlusOne.java ├── PopulatingNextRightPointersinEachNode.java ├── PopulatingNextRightPointersinEachNodeII.java ├── Pow(x,n).java ├── README.md ├── RecoverBinarySearchTree.java ├── RegularExpressionMatching.java ├── RemoveDuplicatesfromSortedArray.java ├── RemoveDuplicatesfromSortedArrayII.java ├── RemoveDuplicatesfromSortedList.java ├── RemoveDuplicatesfromSortedListII.java ├── RemoveElement.java ├── RemoveNthNodeFromEndofList.java ├── ReorderList.java ├── RepeatedDNASequences.java ├── RestoreIPAddresses.java ├── ReverseInteger.java ├── ReverseLinkedListII.java ├── ReverseNodesinkGroup.java ├── ReverseWordsInAString.java ├── RomantoInteger.java ├── RotateImage.java ├── RotateList.java ├── SameTree.java ├── ScrambleString.java ├── SearchInsertPosition.java ├── Searcha2DMatrix.java ├── SearchforaRange.java ├── SearchinRotatedSortedArray.java ├── SearchinRotatedSortedArrayII.java ├── SetMatrixZeroes.java ├── SimplifyPath.java ├── SingleNumber.java ├── SingleNumberII.java ├── SortColors.java ├── SortColorsII.java ├── SortList.java ├── SpiralMatrix.java ├── SpiralMatrixII.java ├── Sqrt(x).java ├── StringtoInteger(atoi).java ├── Subsets.java ├── SubsetsII.java ├── SubstringwithConcatenationofAllWords.java ├── SudokuSolver.java ├── SumRoottoLeafNumbers.java ├── SurroundedRegions.java ├── SwapNodesinPairs.java ├── SymmetricTree.java ├── TextJustification.java ├── TrappingRainWater.java ├── Triangle.java ├── TwoSum.java ├── UniqueBinarySearchTrees.java ├── UniqueBinarySearchTreesII.java ├── UniquePaths.java ├── UniquePathsII.java ├── ValidNumber.java ├── ValidPalindrome.java ├── ValidParentheses.java ├── ValidSudoku.java ├── ValidateBinarySearchTree.java ├── WildcardMatching.java ├── WordBreak.java ├── WordBreakII.java ├── WordLadder.java ├── WordLadderII.java ├── WordSearch.java └── ZigZagConversion.java /3Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: 3Sum 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/3sum/ 7 | Notes: 8 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? 9 | Find all unique triplets in the array which gives the sum of zero. 10 | Note: 11 | Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c) 12 | The solution set must not contain duplicate triplets. 13 | For example, given array S = {-1 0 1 2 -1 -4}, 14 | A solution set is: 15 | (-1, 0, 1) 16 | (-1, -1, 2) 17 | 18 | Solution: Simplify '3sum' to '2sum' O(n^2). http://en.wikipedia.org/wiki/3SUM 19 | */ 20 | public class Solution { 21 | public List> threeSum(int[] num) { 22 | List> res = new ArrayList>(); 23 | Arrays.sort(num); 24 | int N = num.length; 25 | for (int i = 0; i < N-2 && num[i] <= 0; ++i) 26 | { 27 | if (i > 0 && num[i] == num[i-1]) 28 | continue; // avoid duplicates 29 | int twosum = 0 - num[i]; 30 | int l = i + 1, r = N - 1; 31 | while (l < r) 32 | { 33 | int sum = num[l] + num[r]; 34 | if (sum < twosum) ++l; 35 | else if (sum > twosum) --r; 36 | else { 37 | ArrayList tmp = new ArrayList(); 38 | tmp.add(num[i]); tmp.add(num[l]); tmp.add(num[r]); 39 | res.add(tmp); 40 | ++l; --r; 41 | while (l < r && num[l] == num[l-1]) ++l; // avoid duplicates 42 | while (l < r && num[r] == num[r+1]) --r; // avoid duplicates 43 | } 44 | } 45 | } 46 | return res; 47 | } 48 | } -------------------------------------------------------------------------------- /3SumClosest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: 3Sum Closest 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/3sum-closest/ 7 | Notes: 8 | Given an array S of n integers, find three integers in S such that the sum is closest to 9 | a given number, target. Return the sum of the three integers. 10 | You may assume that each input would have exactly one solution. 11 | For example, given array S = {-1 2 1 -4}, and target = 1. 12 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 13 | 14 | Solution: Similar to 3Sum, taking O(n^2) time complexity. 15 | */ 16 | 17 | public class Solution { 18 | public int threeSumClosest(int[] num, int target) { 19 | int N = num.length; 20 | if (N < 3) return 0; 21 | int res = num[0] + num[1] + num[2]; 22 | Arrays.sort(num); 23 | for (int i = 0; i < N-2; ++i) 24 | { 25 | int l = i + 1, r = N - 1; 26 | while (l < r) 27 | { 28 | int threesum = num[i] + num[l] + num[r]; 29 | if (threesum == target) return target; 30 | else if (threesum < target) ++l; 31 | else --r; 32 | if (Math.abs(threesum - target) < Math.abs(res - target)) 33 | res = threesum; 34 | } 35 | } 36 | return res; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /4Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: 4Sum 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/4sum/ 7 | Notes: 8 | Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? 9 | Find all unique triplets in the array which gives the sum of zero. 10 | Note: 11 | Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? 12 | Find all unique quadruplets in the array which gives the sum of target. 13 | Note: 14 | Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= c <= d) 15 | The solution set must not contain duplicate quadruplets. 16 | For example, given array S = {1 0 -1 0 -2 2}, and target = 0. 17 | A solution set is: 18 | (-1, 0, 0, 1) 19 | (-2, -1, 1, 2) 20 | (-2, 0, 0, 2) 21 | 22 | Solution: Similar to 3Sum, 2Sum. 23 | */ 24 | 25 | public class Solution { 26 | public List> fourSum(int[] num, int target) { 27 | int N = num.length; 28 | List> res = new ArrayList>(); 29 | if (N < 4) return res; 30 | Arrays.sort(num); 31 | for (int i = 0; i < N; ++i) 32 | { 33 | if (i > 0 && num[i] == num[i-1]) continue; // avoid duplicates 34 | for (int j = i+1; j < N; ++j) 35 | { 36 | if (j > i+1 && num[j] == num[j-1]) continue; // avoid duplicates 37 | int twosum = target - num[i] - num[j]; 38 | int l = j + 1, r = N - 1; 39 | while (l < r) 40 | { 41 | int sum = num[l] + num[r]; 42 | if (sum == twosum) { 43 | ArrayList tmp = new ArrayList(); 44 | tmp.add(num[i]); tmp.add(num[j]); tmp.add(num[l]); tmp.add(num[r]); 45 | res.add(tmp); 46 | while (l < r && num[l+1] == num[l]) l++; // avoid duplicates 47 | while (l < r && num[r-1] == num[r]) r--; // avoid duplicates 48 | l++; r--; 49 | } 50 | else if (sum < twosum) l++; 51 | else r--; 52 | } 53 | } 54 | } 55 | return res; 56 | } 57 | } -------------------------------------------------------------------------------- /AddBinary.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Add Binary 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/add-binary/ 7 | Notes: 8 | Given two binary strings, return their sum (also a binary string). 9 | For example, 10 | a = "11" 11 | b = "1" 12 | Return "100". 13 | 14 | Solution: '1'-'0' = 1. 15 | */ 16 | 17 | public class Solution { 18 | public String addBinary(String a, String b) { 19 | StringBuffer res = new StringBuffer(); 20 | int N = a.length(), M = b.length(); 21 | int i = N - 1, j = M - 1; 22 | int carry = 0; 23 | while (i>=0 || j>=0) { 24 | int sum = carry; 25 | if (i >= 0) sum += a.charAt(i--) - '0'; 26 | if (j >= 0) sum += b.charAt(j--) - '0'; 27 | carry = sum / 2; 28 | res.insert(0,String.valueOf(sum % 2)); 29 | } 30 | if (carry == 1) res.insert(0,'1'); 31 | return res.toString(); 32 | } 33 | } -------------------------------------------------------------------------------- /AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 13, 2014 4 | Problem: Add Two Numbers 5 | Difficulty: easy 6 | Source: https://oj.leetcode.com/problems/add-two-numbers/ 7 | Notes: 8 | You are given two linked lists representing two non-negative numbers. 9 | The digits are stored in reverse order and each of their nodes contain a single digit. 10 | Add the two numbers and return it as a linked list. 11 | 12 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 13 | Output: 7 -> 0 -> 8 14 | 15 | Solution: dummy head... 16 | 17 | */ 18 | /** 19 | * Definition for singly-linked list. 20 | * public class ListNode { 21 | * int val; 22 | * ListNode next; 23 | * ListNode(int x) { 24 | * val = x; 25 | * next = null; 26 | * } 27 | * } 28 | */ 29 | public class Solution { 30 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 31 | ListNode dummy = new ListNode(0); 32 | ListNode cur = dummy; 33 | int carry = 0; 34 | while (l1 != null || l2 != null || carry != 0) { 35 | int sum = carry; 36 | if (l1 != null) { 37 | sum += l1.val; 38 | l1 = l1.next; 39 | } 40 | if (l2 != null) { 41 | sum += l2.val; 42 | l2 = l2.next; 43 | } 44 | carry = sum/10; 45 | sum = sum%10; 46 | ListNode node = new ListNode(sum); 47 | cur.next = node; 48 | cur = cur.next; 49 | } 50 | return dummy.next; 51 | } 52 | } -------------------------------------------------------------------------------- /Anagrams.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Anagrams 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/anagrams/ 7 | Notes: 8 | Given an array of strings, return all groups of strings that are anagrams. 9 | Note: All inputs will be in lower-case. 10 | 11 | Solution: Sort the string to see if they're anagrams. 12 | */ 13 | 14 | import java.util.Map.Entry; 15 | public class Solution { 16 | public List anagrams(String[] strs) { 17 | ArrayList res = new ArrayList(); 18 | HashMap> group = new HashMap>(); 19 | if (strs.length == 0) return res; 20 | for (int i = 0; i < strs.length; ++i) { 21 | char[] tmp = strs[i].toCharArray(); 22 | Arrays.sort(tmp); 23 | String s = String.valueOf(tmp); 24 | if(group.containsKey(s)) 25 | (group.get(s)).add(strs[i]); 26 | else { 27 | ArrayList t = new ArrayList(); 28 | t.add(strs[i]); 29 | group.put(s,t); 30 | } 31 | } 32 | Iterator>> iter = group.entrySet().iterator(); 33 | while (iter.hasNext()) { 34 | Map.Entry entry = (Map.Entry) iter.next(); 35 | ArrayList val = (ArrayList) entry.getValue(); 36 | if (val.size() > 1) res.addAll(val); 37 | } 38 | return res; 39 | } 40 | } -------------------------------------------------------------------------------- /BalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 07, 2014 4 | Problem: Balanced Binary Tree 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/balanced-binary-tree/ 7 | Notes: 8 | Given a binary tree, determine if it is height-balanced. 9 | For this problem, a height-balanced binary tree is defined as a binary tree in which 10 | the depth of the two subtrees of every node never differ by more than 1. 11 | 12 | Solution: DFS. 13 | */ 14 | /** 15 | * Definition for binary tree 16 | * public class TreeNode { 17 | * int val; 18 | * TreeNode left; 19 | * TreeNode right; 20 | * TreeNode(int x) { val = x; } 21 | * } 22 | */ 23 | public class Solution { 24 | public boolean isBalanced(TreeNode root) { 25 | if (root == null) return true; 26 | return isBalancedRe(root) > -1; 27 | } 28 | public int isBalancedRe(TreeNode root) { 29 | if (root == null) return 0; 30 | int left = isBalancedRe(root.left); 31 | int right = isBalancedRe(root.right); 32 | if (left == -1 || right == -1) return -1; 33 | if (Math.abs(left - right) > 1) return -1; 34 | return Math.max(left, right) + 1; 35 | } 36 | } -------------------------------------------------------------------------------- /BestTimetoBuyandSellStock.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 07, 2014 4 | Problem: Best Time to Buy and Sell Stock 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_121 7 | Notes: 8 | Say you have an array for which the ith element is the price of a given stock on day i. 9 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), 10 | design an algorithm to find the maximum profit. 11 | 12 | Solution: For each element, calculate the max difference with the former elements. 13 | */ 14 | 15 | public class Solution { 16 | public int maxProfit(int[] prices) { 17 | int n = prices.length; 18 | if (n <= 1) return 0; 19 | int res = 0, minVal = prices[0]; 20 | for (int i = 1; i < n; ++i) { 21 | res = Math.max(res, prices[i] - minVal); 22 | minVal = Math.min(minVal, prices[i]); 23 | } 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BestTimetoBuyandSellStockII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 02, 2015 4 | Problem: Best Time to Buy and Sell Stock II 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 7 | Notes: 8 | Say you have an array for which the ith element is the price of a given stock on day i. 9 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like 10 | (ie, buy one and sell one share of the stock multiple times). 11 | However, you may not engage in multiple transactions at the same time 12 | (ie, you must sell the stock before you buy again). 13 | 14 | Solution: 1. At the beginning of the ascending order: buy. 15 | At the ending of the ascending order: sell. 16 | */ 17 | public class Solution { 18 | public int maxProfit(int[] prices) { 19 | int res = 0; 20 | for (int i = 1; i < prices.length; ++i) { 21 | res += Math.max(0, prices[i] - prices[i-1]); 22 | } 23 | return res; 24 | } 25 | } -------------------------------------------------------------------------------- /BestTimetoBuyandSellStockIII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 02, 2015 4 | Problem: Best Time to Buy and Sell Stock III 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 7 | Notes: 8 | Say you have an array for which the ith element is the price of a given stock on day i. 9 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 10 | Note: 11 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 12 | 13 | Solution: dp. max profit = max { l2r[0...i] + r2l[i+1...N-1] }. 14 | 0 <= i <= N-1 15 | */ 16 | 17 | public class Solution { 18 | public int maxProfit(int[] prices) { 19 | int n = prices.length; 20 | if (n <= 1) return 0; 21 | int[] l2r = new int[n]; 22 | int[] r2l = new int[n]; 23 | l2r[0] = 0; r2l[n-1] = 0; 24 | int minVal = prices[0], maxVal = prices[n-1]; 25 | for (int i = 1; i < n; ++i) { 26 | l2r[i] = Math.max(l2r[i-1], prices[i] - minVal); 27 | minVal = Math.min(minVal, prices[i]); 28 | } 29 | for (int i = n - 2; i >= 0; --i) { 30 | r2l[i] = Math.max(r2l[i+1], maxVal - prices[i]); 31 | maxVal = Math.max(maxVal, prices[i]); 32 | } 33 | int res = l2r[n-1]; 34 | for (int i = 0; i < n - 1; ++i) { 35 | res = Math.max(res, l2r[i] + r2l[i+1]); 36 | } 37 | return res; 38 | } 39 | } -------------------------------------------------------------------------------- /BinaryTreeLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Dec 12, 2014 4 | Problem: Binary Tree Level Order Traversal 5 | Difficulty: easy 6 | Source: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ 7 | Notes: 8 | Given a binary tree, return the level order traversal of its nodes' values. 9 | (ie, from left to right, level by level). 10 | 11 | For example: 12 | Given binary tree {3,9,20,#,#,15,7}, 13 | 3 14 | / \ 15 | 9 20 16 | / \ 17 | 15 7 18 | return its level order traversal as: 19 | [ 20 | [3], 21 | [9,20], 22 | [15,7] 23 | ] 24 | 25 | Solution: 1. Use queue. In order to seperate the levels, use 'NULL' as the end indicator of one level. 26 | 2. DFS. 27 | */ 28 | 29 | /** 30 | * Definition for binary tree 31 | * public class TreeNode { 32 | * int val; 33 | * TreeNode left; 34 | * TreeNode right; 35 | * TreeNode(int x) { val = x; } 36 | * } 37 | */ 38 | public class Solution { 39 | public List> levelOrder_1(TreeNode root) { 40 | List> res = new ArrayList>(); 41 | if (root == null) return res; 42 | Queue q = new LinkedList(); 43 | q.offer(root); 44 | q.offer(null); 45 | List level = new ArrayList(); 46 | 47 | while(true) { 48 | TreeNode node = q.poll(); 49 | if (node != null) { 50 | level.add(node.val); 51 | if(node.left!=null) q.offer(node.left); 52 | if(node.right!=null) q.offer(node.right); 53 | } else { 54 | res.add(level); 55 | level = new ArrayList(); 56 | if(q.isEmpty()==true) break; 57 | q.offer(null); 58 | } 59 | } 60 | return res; 61 | } 62 | 63 | public List> levelOrder_2(TreeNode root) { 64 | List> res = new ArrayList>(); 65 | if (root == null) return res; 66 | levelOrderRe(root, 0, res); 67 | return res; 68 | } 69 | public void levelOrderRe(TreeNode root, int level, List> res) { 70 | if(root == null) return; 71 | if(level == res.size()) res.add(new ArrayList()); 72 | res.get(level).add(root.val); 73 | levelOrderRe(root.left, level+1, res); 74 | levelOrderRe(root.right,level+1, res); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /BinaryTreeLevelOrderTraversalII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Dec 12, 2014 4 | Problem: Binary Tree Level Order Traversal II 5 | Difficulty: easy 6 | Source: https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ 7 | Notes: 8 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. 9 | (ie, from left to right, level by level from leaf to root). 10 | 11 | For example: 12 | Given binary tree {3,9,20,#,#,15,7}, 13 | 3 14 | / \ 15 | 9 20 16 | / \ 17 | 15 7 18 | return its bottom-up level order traversal as: 19 | [ 20 | [15,7] 21 | [9,20], 22 | [3], 23 | ] 24 | 25 | Solution: Queue version. On the basis of 'Binary Tree Level Order Traversal', reverse the final vector. 26 | */ 27 | 28 | /** 29 | * Definition for binary tree 30 | * public class TreeNode { 31 | * int val; 32 | * TreeNode left; 33 | * TreeNode right; 34 | * TreeNode(int x) { val = x; } 35 | * } 36 | */ 37 | public class Solution { 38 | public List> levelOrderBottom(TreeNode root) { 39 | List> res = new ArrayList>(); 40 | if (root == null) return res; 41 | Queue q = new LinkedList(); 42 | q.offer(root); 43 | q.offer(null); 44 | List level = new ArrayList(); 45 | 46 | while(true) { 47 | TreeNode node = q.poll(); 48 | if (node != null) { 49 | level.add(node.val); 50 | if(node.left!=null) q.offer(node.left); 51 | if(node.right!=null) q.offer(node.right); 52 | } else { 53 | res.add(level); 54 | level = new ArrayList(); 55 | if(q.isEmpty()==true) break; 56 | q.offer(null); 57 | } 58 | } 59 | Collections.reverse(res); 60 | return res; 61 | } 62 | } -------------------------------------------------------------------------------- /BinaryTreeMaximumPathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 28, 2015 4 | Problem: Binary Tree Maximum Path Sum 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ 7 | Notes: 8 | Given a binary tree, find the maximum path sum. 9 | The path may start and end at any node in the tree. 10 | For example: 11 | Given the below binary tree, 12 | 1 13 | / \ 14 | 2 3 15 | Return 6. 16 | 17 | Solution: Recursion... 18 | */ 19 | 20 | /** 21 | * Definition for binary tree 22 | * public class TreeNode { 23 | * int val; 24 | * TreeNode left; 25 | * TreeNode right; 26 | * TreeNode(int x) { val = x; } 27 | * } 28 | */ 29 | public class Solution { 30 | public int maxPathSum(TreeNode root) { 31 | int[] res = new int[1]; 32 | res[0] = Integer.MIN_VALUE; 33 | maxPathSumRe(root, res); 34 | return res[0]; 35 | } 36 | int maxPathSumRe(TreeNode root, int[] res) { 37 | if (root == null) return 0; 38 | int left = maxPathSumRe(root.left, res); 39 | int right = maxPathSumRe(root.right, res); 40 | res[0] = Math.max(res[0], root.val + Math.max(left, 0) + Math.max(right, 0)); 41 | return Math.max(root.val, root.val + Math.max(left, right)); 42 | } 43 | } -------------------------------------------------------------------------------- /Candy.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Candy 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/candy/ 7 | Notes: 8 | There are N children standing in a line. Each child is assigned a rating value. 9 | You are giving candies to these children subjected to the following requirements: 10 | - Each child must have at least one candy. 11 | - Children with a higher rating get more candies than their neighbors. 12 | What is the minimum candies you must give? 13 | 14 | Solution: You may refer to https://github.com/AnnieKim/ITint5/blob/master/031_%E5%88%86%E9%85%8D%E7%B3%96%E6%9E%9C.cpp 15 | 1. O(n) space. 16 | 2. traverse only once with O(1) space. 17 | */ 18 | 19 | public class Solution { 20 | public int candy(int[] ratings) { 21 | return candy_1(ratings); 22 | } 23 | public int candy_1(int[] ratings) { 24 | int N = ratings.length; 25 | if (N == 0) return 0; 26 | int[] height = new int[N]; 27 | int res = 0; 28 | height[0] = 1; 29 | for (int i = 1; i < N; ++i) { 30 | height[i] = 1; 31 | if (ratings[i] > ratings[i - 1]) { 32 | height[i] = height[i - 1] + 1; 33 | } 34 | } 35 | for (int i = N - 2; i >= 0; --i) { 36 | if (ratings[i] > ratings[i + 1]) { 37 | height[i] = Math.max(height[i], height[i + 1] + 1); 38 | } 39 | } 40 | for (int i = 0; i < N; ++i) { 41 | res +=height[i]; 42 | } 43 | return res; 44 | } 45 | public int candy_2(int[] ratings) { 46 | int N = ratings.length; 47 | if (N == 0) return 0; 48 | int candy = 1, res = 1; 49 | int maxVal = 1, maxIdx = 0; 50 | for (int i = 1; i < N; ++i) { 51 | if (ratings[i] >= ratings[i - 1]) { 52 | candy = ratings[i] == ratings[i - 1] ? 1 : candy + 1; 53 | maxVal = candy; 54 | maxIdx = i; 55 | } else { 56 | if (candy == 1) { 57 | if (maxVal <= i - maxIdx) { 58 | ++maxVal; 59 | ++res; 60 | } 61 | res += i - maxIdx - 1; 62 | } 63 | candy = 1; 64 | } 65 | res += candy; 66 | } 67 | return res; 68 | } 69 | } -------------------------------------------------------------------------------- /ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King,wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Climbing Stairs 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/climbing-stairs/ 7 | Notes: 8 | You are climbing a stair case. It takes n steps to reach to the top. 9 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 10 | 11 | Solution: Clime one step from last stair or clime 2 steps from the last last stair. 12 | */ 13 | public class Solution { 14 | public int climbStairs(int n) { 15 | int[] f = new int[n+1]; 16 | f[0] = 1; f[1] = 1; 17 | for (int i = 2; i <= n; ++i) 18 | f[i] = f[i-1] + f[i-2]; 19 | return f[n]; 20 | } 21 | } -------------------------------------------------------------------------------- /CombinationSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Annie Kim, anniekim.pku@gmail.com 3 | Date: May 25, 2013 4 | Problem: Combination Sum 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_39 7 | Notes: 8 | Given a set of candidate numbers (C) and a target number (T), find all unique 9 | combinations in C where the candidate numbers sums to T. 10 | The same repeated number may be chosen from C unlimited number of times. 11 | Note: 12 | All numbers (including target) will be positive integers. 13 | Elements in a combination (a1, a2, .. , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak). 14 | The solution set must not contain duplicate combinations. 15 | For example, given candidate set 2,3,6,7 and target 7, 16 | A solution set is: 17 | [7] 18 | [2, 2, 3] 19 | 20 | Solution: Sort & Recursion. 21 | */ 22 | 23 | public class Solution { 24 | public List> combinationSum(int[] candidates, int target) { 25 | List> res = new ArrayList>(); 26 | Arrays.sort(candidates); 27 | ArrayList path = new ArrayList(); 28 | combinationSumRe(candidates, target, 0, path, res); 29 | return res; 30 | } 31 | void combinationSumRe(int[] candidates, int target, int start, ArrayList path, List> res) { 32 | if (target == 0) { 33 | ArrayList p = new ArrayList(path); 34 | res.add(p); 35 | return; 36 | } 37 | for (int i = start; i < candidates.length && target >= candidates[i]; ++i) { 38 | path.add(candidates[i]); 39 | combinationSumRe(candidates, target-candidates[i], i, path, res); 40 | path.remove(path.size() - 1); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /CombinationSumII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Combination Sum II 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/combination-sum-ii/ 7 | Notes: 8 | Given a collection of candidate numbers (C) and a target number (T), find all unique combinations 9 | in C where the candidate numbers sums to T. 10 | Each number in C may only be used once in the combination. 11 | Note: 12 | All numbers (including target) will be positive integers. 13 | Elements in a combination (a1, a2, .. , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak). 14 | The solution set must not contain duplicate combinations. 15 | For example, given candidate set 10,1,2,7,6,1,5 and target 8, 16 | A solution set is: 17 | [1, 7] 18 | [1, 2, 5] 19 | [2, 6] 20 | [1, 1, 6] 21 | 22 | Solution: ..Similar to Combination Sum I, except for line 42 && 44. 23 | */ 24 | public class Solution { 25 | public List> combinationSum2(int[] num, int target) { 26 | List> res = new ArrayList>(); 27 | Arrays.sort(num); 28 | ArrayList path = new ArrayList(); 29 | combinationSumRe(num, target, 0, path, res); 30 | return res; 31 | } 32 | void combinationSumRe(int[] candidates, int target, int start, ArrayList path, List> res) { 33 | if (target == 0) { 34 | ArrayList p = new ArrayList(path); 35 | res.add(p); 36 | return; 37 | } 38 | for (int i = start; i < candidates.length && target >= candidates[i]; ++i) { 39 | if (i!=start && candidates[i-1] == candidates[i]) continue; 40 | path.add(candidates[i]); 41 | combinationSumRe(candidates, target-candidates[i], i+1, path, res); 42 | path.remove(path.size() - 1); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Combinations.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Combinations 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/combinations/ 7 | Notes: 8 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 9 | For example, 10 | If n = 4 and k = 2, a solution is: 11 | [ 12 | [2,4], 13 | [3,4], 14 | [2,3], 15 | [1,2], 16 | [1,3], 17 | [1,4], 18 | ] 19 | 20 | Solution: DFS. 21 | */ 22 | public class Solution { 23 | public List> combine(int n, int k) { 24 | List> res = new ArrayList>(); 25 | ArrayList path = new ArrayList(); 26 | combineRe(n, k, 1, path, res); 27 | return res; 28 | } 29 | void combineRe(int n, int k, int start, ArrayList path, List> res){ 30 | int m = path.size(); 31 | if (m == k) { 32 | ArrayList p = new ArrayList(path); 33 | res.add(p); 34 | return; 35 | } 36 | for (int i = start; i <= n-(k-m)+1; ++i) { 37 | path.add(i); 38 | combineRe(n,k,i+1, path, res); 39 | path.remove(path.size() - 1); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /CompareVersionNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 15, 2014 4 | Problem: Compare Version Numbers 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/compare-version-numbers/ 7 | Notes: 8 | Compare two version numbers version1 and version1. 9 | If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. 10 | 11 | You may assume that the version strings are non-empty and contain only digits and the . character. 12 | The . character does not represent a decimal point and is used to separate number sequences. 13 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 14 | 15 | Here is an example of version numbers ordering: 16 | 17 | 0.1 < 1.1 < 1.2 < 13.37 18 | 19 | Solution: ... 20 | */ 21 | 22 | public class Solution { 23 | public int compareVersion(String version1, String version2) { 24 | long a = 0, b =0; 25 | int v1len = version1.length(), v2len = version2.length(); 26 | int i = 0, j = 0; 27 | while (i < v1len || j < v2len) { 28 | a = 0; b =0; 29 | while (i < v1len && version1.charAt(i) != '.') { 30 | a = a * 10 + version1.charAt(i) - '0'; 31 | ++i; 32 | } 33 | ++i; 34 | while (j < v2len && version2.charAt(j) != '.') { 35 | b = b * 10 + version2.charAt(j) - '0'; 36 | ++j; 37 | } 38 | ++j; 39 | if (a > b) return 1; 40 | if (a < b) return -1; 41 | } 42 | return 0; 43 | } 44 | } -------------------------------------------------------------------------------- /ConstructBinaryTreefromInorderandPostorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 16, 2015 4 | Problem: Construct Binary Tree from Inorder and Postorder Traversal 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_106 7 | Notes: 8 | Given inorder and postorder traversal of a tree, construct the binary tree. 9 | Note: 10 | You may assume that duplicates do not exist in the tree. 11 | 12 | Solution: Recursion. 13 | */ 14 | /** 15 | * Definition for binary tree 16 | * public class TreeNode { 17 | * int val; 18 | * TreeNode left; 19 | * TreeNode right; 20 | * TreeNode(int x) { val = x; } 21 | * } 22 | */ 23 | public class Solution { 24 | public TreeNode buildTree(int[] inorder, int[] postorder) { 25 | if(inorder.length==0||postorder.length==0||inorder.length!=postorder.length) 26 | return null; 27 | return buildTreeRe(inorder,0,inorder.length-1,postorder,0,postorder.length-1); 28 | } 29 | public TreeNode buildTreeRe(int[] inorder,int s1,int e1, int[] postorder, int s2,int e2){ 30 | if(e2 height[right]) --right; 24 | else ++left; 25 | } 26 | return res; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ConvertSortedArraytoBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 29, 2015 4 | Problem: Convert Sorted Array to Binary Search Tree 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 7 | Notes: 8 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 9 | 10 | Solution: Recursion. 1. preorder 11 | 2. inorder 12 | */ 13 | 14 | /** 15 | * Definition for binary tree 16 | * public class TreeNode { 17 | * int val; 18 | * TreeNode left; 19 | * TreeNode right; 20 | * TreeNode(int x) { val = x; } 21 | * } 22 | */ 23 | public class Solution { 24 | public TreeNode sortedArrayToBST_1(int[] num) { 25 | return sortedArrayToBSTRe(num, 0, num.length - 1); 26 | } 27 | public TreeNode sortedArrayToBSTRe(int[] num, int left, int right) { 28 | if (left > right) return null; 29 | if (left == right) return new TreeNode(num[left]); 30 | int mid = (left + right) / 2; 31 | TreeNode node = new TreeNode(num[mid]); 32 | node.left = sortedArrayToBSTRe(num, left, mid - 1); 33 | node.right = sortedArrayToBSTRe(num, mid + 1, right); 34 | return node; 35 | } 36 | public TreeNode sortedArrayToBST(int[] num) { 37 | int[] curidx = new int[1]; 38 | curidx[0] = 0; 39 | return sortedArrayToBSTRe1(num, num.length, curidx); 40 | } 41 | public TreeNode sortedArrayToBSTRe1(int[] num, int len, int[] curidx) { 42 | if (len == 0) return null; 43 | if (len == 1) return new TreeNode(num[curidx[0]++]); 44 | int mid = len / 2; 45 | TreeNode left = sortedArrayToBSTRe1(num, mid, curidx); 46 | TreeNode node = new TreeNode(num[curidx[0]++]); 47 | node.left = left; 48 | node.right = sortedArrayToBSTRe1(num, len - 1 - mid, curidx); 49 | return node; 50 | } 51 | } -------------------------------------------------------------------------------- /CountandSay.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Count and Say 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/count-and-say/ 7 | Notes: 8 | The count-and-say sequence is the sequence of integers beginning as follows: 9 | 1, 11, 21, 1211, 111221, ... 10 | 11 | 1 is read off as "one 1" or 11. 12 | 11 is read off as "two 1s" or 21. 13 | 21 is read off as "one 2, then one 1" or 1211. 14 | Given an integer n, generate the nth sequence. 15 | Note: The sequence of integers will be represented as a string. 16 | 17 | Solution: ... 18 | */ 19 | 20 | public class Solution { 21 | public String countAndSay(int n) { 22 | StringBuffer s = new StringBuffer("1"); 23 | StringBuffer res = new StringBuffer(); 24 | while((--n) != 0){ 25 | res.setLength(0); 26 | int size = s.length(); 27 | int cnt = 1; 28 | char cur = s.charAt(0); 29 | for(int i=1;i 1 10 | 'B' -> 2 11 | ... 12 | 'Z' -> 26 13 | Given an encoded message containing digits, determine the total number of ways to decode it. 14 | For example, 15 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 16 | The number of ways decoding "12" is 2. 17 | 18 | Solution: 1. dp. Time : O(n); Space : O(1). 19 | */ 20 | 21 | public class Solution { 22 | public int numDecodings(String s) { 23 | if (s.length() == 0 || s.charAt(0) == '0') return 0; 24 | int N = s.length(); 25 | int f0 = 1, f1 = 1; 26 | for (int i = 1; i < N; ++i) { 27 | if (s.charAt(i) == '0') f1 = 0; 28 | int num = s.charAt(i) - '0' + (s.charAt(i-1) - '0') * 10; 29 | if (num < 10 || num > 26) { 30 | f0 = 0; 31 | } 32 | int tmp = f1; 33 | f1 = f1 + f0; 34 | f0 = tmp; 35 | } 36 | return f1; 37 | } 38 | } -------------------------------------------------------------------------------- /DistinctSubsequences.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Oct 07, 2014 4 | Problem: Distinct Subsequences 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/distinct-subsequences/ 7 | Notes: 8 | Given a string S and a string T, count the number of distinct subsequences of T in S. 9 | A subsequence of a string is a new string which is formed from the original string by deleting 10 | some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 11 | 12 | Here is an example: 13 | S = "rabbbit", T = "rabbit" 14 | Return 3. 15 | 16 | Solution: dp. 17 | */ 18 | 19 | public class Solution { 20 | public int numDistinct(String S, String T) { 21 | int M = S.length(); 22 | int N = T.length(); 23 | int[] dp = new int[N+1]; 24 | Arrays.fill(dp, 0); 25 | dp[0] = 1; 26 | for (int i = 1; i <= M; ++i) { 27 | for (int j = N; j >=1; --j) { 28 | dp[j] = dp[j] + (S.charAt(i-1) == T.charAt(j-1) ? dp[j-1] : 0); 29 | } 30 | } 31 | return dp[N]; 32 | } 33 | } -------------------------------------------------------------------------------- /DivideTwoIntegers.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Nov 18, 2014 4 | Problem: Divide Two Integers 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/divide-two-integers/ 7 | Notes: 8 | Divide two integers without using multiplication, division and mod operator. 9 | 10 | Solution: Use << operator. 11 | */ 12 | public class Solution { 13 | public int divide(int dividend, int divisor) { 14 | boolean flag = dividend < 0 ^ divisor < 0; 15 | long Dividend = Math.abs((long)dividend); 16 | long Divisor = Math.abs((long)divisor); 17 | long res = 0; 18 | while (Dividend >= Divisor) { 19 | long c = Divisor; 20 | for (int i = 0; (c << i) <= Dividend; ++i) { 21 | Dividend -= (c << i); 22 | res += (1 << i); 23 | } 24 | } 25 | if (flag == true) res = -res; 26 | if (res > Integer.MAX_VALUE) return Integer.MAX_VALUE; 27 | return (int)res; 28 | } 29 | } -------------------------------------------------------------------------------- /EditDistance.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Edit Distance 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/edit-distance/ 7 | Notes: 8 | Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) 9 | You have the following 3 operations permitted on a word: 10 | a) Insert a character 11 | b) Delete a character 12 | c) Replace a character 13 | 14 | Solution: Dynamic Programming. 15 | 1. Time: O(mn) Space: O(mn) 16 | 2. Time: O(mn) Space: O(n); 17 | */ 18 | public class Solution { 19 | public int minDistance_1(String word1, String word2) { 20 | if(word1==word2) return 0; 21 | int len1 = word1.length(); 22 | int len2 = word2.length(); 23 | int[][] dp = new int[len1+1][len2+1]; 24 | 25 | for(int i=0;i<=len1;i++) 26 | dp[i][0] = i; 27 | for(int i=0;i<=len2;i++) 28 | dp[0][i] = i; 29 | 30 | for(int i=1;i<=len1;i++){ 31 | for(int j=1;j<=len2;j++){ 32 | if(word1.charAt(i-1)==word2.charAt(j-1)) dp[i][j] = dp[i-1][j-1]; 33 | else{ 34 | dp[i][j] = Math.min(dp[i-1][j],Math.min(dp[i][j-1],dp[i-1][j-1]))+1; 35 | } 36 | } 37 | } 38 | return dp[len1][len2]; 39 | } 40 | public int minDistance(String word1, String word2) { 41 | if(word1==word2) return 0; 42 | int len1 = word1.length(); 43 | int len2 = word2.length(); 44 | int[] dp = new int[len2+1]; 45 | 46 | for(int i=0;i<=len2;i++) 47 | dp[i] = i; 48 | 49 | for(int i=1;i<=len1;i++){ 50 | int upperLeftBak = dp[0]; 51 | dp[0] = i; 52 | for(int j=1;j<=len2;j++){ 53 | int upperLeft = upperLeftBak; 54 | upperLeftBak = dp[j]; 55 | if(word1.charAt(i-1)==word2.charAt(j-1)) dp[j] = upperLeft; 56 | else{ 57 | dp[j] = Math.min(dp[j],Math.min(dp[j-1],upperLeft))+1; 58 | } 59 | } 60 | } 61 | return dp[len2]; 62 | } 63 | } -------------------------------------------------------------------------------- /EvaluateReversePolishNotation.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 31, 2015 4 | Problem: Evaluate Reverse Polish Notation 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 7 | Notes: 8 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 9 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 10 | Some examples: 11 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 12 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 13 | Solution: stack. 14 | */ 15 | 16 | public class Solution { 17 | public int evalRPN(String[] tokens) { 18 | Stack stk = new Stack(); 19 | for (int i = 0; i < tokens.length; ++i) { 20 | if ((tokens[i].compareTo("+") != 0) && (tokens[i].compareTo("-") != 0) 21 | && (tokens[i].compareTo("*") != 0) && (tokens[i].compareTo("/") != 0)) { 22 | stk.push(Integer.parseInt(tokens[i])); 23 | } else { 24 | int op2 = stk.pop(); 25 | int op1 = stk.pop(); 26 | int res = 0; 27 | if(tokens[i].compareTo("+") == 0) 28 | res = op1 + op2; 29 | else if(tokens[i].compareTo("-") == 0) 30 | res = op1 - op2; 31 | else if(tokens[i].compareTo("*") == 0) 32 | res = op1 * op2; 33 | else if(tokens[i].compareTo("/") == 0) 34 | res = op1 / op2; 35 | stk.push(res); 36 | } 37 | } 38 | return stk.pop(); 39 | } 40 | } -------------------------------------------------------------------------------- /ExcelSheetColumnNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 28, 2014 4 | Problem: Excel Sheet Column Number 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/excel-sheet-column-number/ 7 | Notes: 8 | Related to question Excel Sheet Column Title 9 | 10 | Given a column title as appear in an Excel sheet, return its corresponding column number. 11 | 12 | For example: 13 | 14 | A -> 1 15 | B -> 2 16 | C -> 3 17 | ... 18 | Z -> 26 19 | AA -> 27 20 | AB -> 28 21 | 22 | Solution: 1. ... 23 | */ 24 | 25 | public class Solution { 26 | public int titleToNumber(String s) { 27 | int res = 0; 28 | if (s.length() == 0) return 0; 29 | for (int i = 0; i < s.length(); ++i) { 30 | res = res * 26 + s.charAt(i) - 'A' + 1; 31 | } 32 | return res; 33 | } 34 | } -------------------------------------------------------------------------------- /ExcelSheetColumnTitle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 19, 2014 4 | Problem: Excel Sheet Column Title 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/excel-sheet-column-title/ 7 | Notes: 8 | Given a non-zero positive integer, return its corresponding column title as appear in an Excel sheet. 9 | 10 | For example: 11 | 12 | 1 -> A 13 | 2 -> B 14 | 3 -> C 15 | ... 16 | 26 -> Z 17 | 27 -> AA 18 | 28 -> AB 19 | 20 | Solution: 1. Iteration. 21 | 2&3. recursion. 22 | */ 23 | public class Solution { 24 | public String convertToTitle(int n) { 25 | StringBuffer sb = new StringBuffer(); 26 | while (n > 0) { 27 | sb.insert(0,(char)((n - 1)%26 + 'A')); 28 | n = (n - 1) / 26; 29 | } 30 | return sb.toString(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /FactorialTrailingZeroes.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 13, 2014 4 | Problem: Factorial Trailing Zeroes 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/factorial-trailing-zeroes/ 7 | Notes: 8 | Given an integer n, return the number of trailing zeroes in n!. 9 | 10 | Note: Your solution should be in logarithmic time complexity. 11 | 12 | Solution: ... 13 | */ 14 | public class Solution { 15 | public int trailingZeroes_1(int n) { 16 | int res = 0; 17 | while (n != 0) { 18 | res += n / 5; 19 | n = n / 5; 20 | } 21 | return res; 22 | } 23 | public int trailingZeroes_2(int n) { 24 | if (n == 0) return 0; 25 | return n / 5 + trailingZeroes_2(n / 5); 26 | } 27 | } -------------------------------------------------------------------------------- /FindMinimumInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Oct 22, 2014 4 | Problem: Find Minimum in Rotated Sorted Array 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 7 | Notes: 8 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 9 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | 11 | Find the minimum element. 12 | 13 | You may assume no duplicate exists in the array. 14 | */ 15 | public class Solution { 16 | public int findMin(int[] num) { 17 | if (num.length == 0) return 0; 18 | int left = 0, right = num.length -1; 19 | while (left < right && num[left] > num[right]) { 20 | int mid = left + (right - left) / 2; 21 | if (num[mid] > num[right]) left = mid + 1; 22 | else right = mid; 23 | } 24 | return num[left]; 25 | } 26 | } -------------------------------------------------------------------------------- /FindMinimumInRotatedSortedArrayII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Oct 22, 2014 4 | Problem: Find Minimum in Rotated Sorted ArrayII 5 | Difficulty: Hard 6 | Source: https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ 7 | Notes: 8 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 9 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | 11 | Find the minimum element. 12 | 13 | The array may contain duplicates. 14 | */ 15 | 16 | public class Solution { 17 | public int findMin(int[] num) { 18 | if (num.length == 0) return 0; 19 | int left = 0, right = num.length -1; 20 | while (left < right && num[left] >= num[right]) { 21 | int mid = left + (right - left) / 2; 22 | if (num[mid] > num[right]) left = mid + 1; 23 | else if (num[mid] < num[right]) right = mid; 24 | else left++; 25 | } 26 | return num[left]; 27 | } 28 | } -------------------------------------------------------------------------------- /FindPeakElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 06, 2014 4 | Problem: Find Peak Element 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/find-peak-element/ 7 | Notes: 8 | A peak element is an element that is greater than its neighbors. 9 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 10 | You may imagine that num[-1] = num[n] = -∞. 11 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 12 | 13 | Find the peak element. 14 | */ 15 | public class Solution { 16 | public int findPeakElement(int[] num) { 17 | int left = 0, right = num.length - 1, mid = -1; 18 | while (left <= right) { 19 | mid = (left + right) /2; 20 | if ((mid == 0 || num[mid-1] <= num[mid]) && (mid == num.length - 1 || num[mid] >= num[mid+1])) 21 | return mid; 22 | if (mid > 0 && num[mid-1] > num[mid]) { 23 | right = mid - 1; 24 | } else if (num[mid+1] > num[mid]) { 25 | left = mid + 1; 26 | } 27 | } 28 | return mid; 29 | } 30 | } -------------------------------------------------------------------------------- /FirstMissingPositive.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: First Missing Positive 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/first-missing-positive/ 7 | Notes: 8 | Given an unsorted integer array, find the first missing positive integer. 9 | For example, 10 | Given [1,2,0] return 3, 11 | and [3,4,-1,1] return 2. 12 | Your algorithm should run in O(n) time and uses constant space. 13 | 14 | Solution: Although we can only use constant space, we can still exchange elements within input A! 15 | Swap elements in A and try to make all the elements in A satisfy: A[i] == i + 1. 16 | Pick out the first one that does not satisfy A[i] == i + 1. 17 | */ 18 | public class Solution { 19 | public int firstMissingPositive_1(int[] A) { 20 | for(int i=0;i0) return i+1; 32 | return A.length+1; 33 | } 34 | int firstMissingPositive_2(int A[], int n) { 35 | for(int i=0;i=1&&A[i]<=n&&A[i]!=A[A[i]-1]) { 37 | int tmp = A[i]; 38 | A[i] = A[tmp - 1]; 39 | A[tmp - 1] = tmp; 40 | } 41 | } 42 | int i=0; 43 | for(i=0;i stk = new Stack(); 62 | stk.push(root); 63 | while (stk.empty() == false) { 64 | TreeNode cur = stk.pop(); 65 | if (cur.right != null) stk.push(cur.right); 66 | if (cur.left != null) stk.push(cur.left); 67 | cur.left = null; 68 | cur.right = stk.empty() == true ? null : stk.peek(); 69 | } 70 | } 71 | public TreeNode flattenRe3(TreeNode root, TreeNode tail) { 72 | if (root == null) return tail; 73 | root.right = flattenRe3(root.left, flattenRe3(root.right, tail)); 74 | root.left = null; 75 | return root; 76 | } 77 | public void flatten_3(TreeNode root) { 78 | if (root == null) return; 79 | flattenRe3(root, null); 80 | } 81 | } -------------------------------------------------------------------------------- /FractionToRecurringDecimal.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 15, 2014 4 | Problem: Fraction to Recurring Decimal 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/fraction-to-recurring-decimal/ 7 | Notes: 8 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. 9 | 10 | If the fractional part is repeating, enclose the repeating part in parentheses. 11 | 12 | For example, 13 | 14 | Given numerator = 1, denominator = 2, return "0.5". 15 | Given numerator = 2, denominator = 1, return "2". 16 | Given numerator = 2, denominator = 3, return "0.(6)". 17 | 18 | Solution: ... 19 | */ 20 | public class Solution { 21 | public String fractionToDecimal(int numerator, int denominator) { 22 | if (numerator == 0) return new String("0"); 23 | boolean flag = (numerator < 0)^(denominator < 0); 24 | long Numerator = Math.abs((long)numerator); 25 | long Denominator = Math.abs((long)denominator); 26 | StringBuffer res = new StringBuffer(); 27 | if (flag == true) res.append('-'); 28 | res.append(String.valueOf((Numerator / Denominator))); 29 | Numerator = Numerator % Denominator; 30 | if (Numerator == 0) return res.toString(); 31 | res.append('.'); 32 | HashMap map = new HashMap(); 33 | for (int i = res.length(); Numerator != 0; ++i) { 34 | if (map.get(Numerator) != null) break; 35 | map.put(Numerator, i); 36 | Numerator *= 10; 37 | res.append(String.valueOf((Numerator / Denominator))); 38 | Numerator %= Denominator; 39 | } 40 | 41 | if (Numerator == 0) return res.toString(); 42 | res.insert(map.get(Numerator),"("); 43 | res.append(')'); 44 | return res.toString(); 45 | } 46 | } -------------------------------------------------------------------------------- /GasStation.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 3, 2015 4 | Problem: Gas Station 5 | Difficulty: Easy 6 | Source: http://oj.leetcode.com/problems/gas-station/ 7 | Notes: 8 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 9 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 10 | Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. 11 | The solution is guaranteed to be unique. 12 | 13 | Solution: ... 14 | */ 15 | public class Solution { 16 | public int canCompleteCircuit(int[] gas, int[] cost) { 17 | int N = gas.length; 18 | int res = 0, min = gas[0] - cost[0], sum = min; 19 | for (int i = 1; i < N; ++i) { 20 | sum += gas[i] - cost[i]; 21 | if (sum < min) { 22 | min = sum; 23 | res = i; 24 | } 25 | } 26 | return sum >= 0 ? (res + 1) % N : -1; 27 | } 28 | } -------------------------------------------------------------------------------- /GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Generate Parentheses 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/generate-parentheses/ 7 | Notes: 8 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 9 | For example, given n = 3, a solution set is: 10 | "((()))", "(()())", "(())()", "()(())", "()()()" 11 | 12 | Solution: Place n left '(' and n right ')'. 13 | Cannot place ')' if there are no enough matching '('. 14 | */ 15 | 16 | public class Solution { 17 | public List generateParenthesis(int n) { 18 | ArrayList res = new ArrayList(); 19 | generateParenthesisRe(res, n, n, ""); 20 | return res; 21 | } 22 | public void generateParenthesisRe(ArrayList res, int left, int right, String s) { 23 | if (left == 0 && right == 0) 24 | res.add(s); 25 | if (left > 0) 26 | generateParenthesisRe(res, left - 1, right, s + "("); 27 | if (right > left) 28 | generateParenthesisRe(res, left, right - 1, s + ")"); 29 | } 30 | } -------------------------------------------------------------------------------- /GrayCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 27, 2014 4 | Problem: Gray Code 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/gray-code/ 7 | Notes: 8 | The gray code is a binary numeral system where two successive values differ in only one bit. 9 | Given a non-negative integer n representing the total number of bits in the code, print the 10 | sequence of gray code. A gray code sequence must begin with 0. 11 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 12 | 00 - 0 13 | 01 - 1 14 | 11 - 3 15 | 10 - 2 16 | Note: 17 | For a given n, a gray code sequence is not uniquely defined. 18 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 19 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 20 | 21 | Solution: Refer to http://en.wikipedia.org/wiki/Gray_code. 22 | */ 23 | public class Solution { 24 | public List grayCode(int n) { 25 | ArrayList res = new ArrayList(); 26 | for (int i = 0; i < 1 << n; ++i) 27 | res.add((int)((i >> 1) ^ i)); 28 | return res; 29 | } 30 | } -------------------------------------------------------------------------------- /InsertionSortList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 02, 2015 4 | Problem: Insertion Sort List 5 | Difficulty: Easy 6 | Source: http://oj.leetcode.com/problems/insertion-sort-list/ 7 | Notes: 8 | Sort a linked list using insertion sort. 9 | 10 | Solution: ... 11 | */ 12 | /** 13 | * Definition for singly-linked list. 14 | * public class ListNode { 15 | * int val; 16 | * ListNode next; 17 | * ListNode(int x) { 18 | * val = x; 19 | * next = null; 20 | * } 21 | * } 22 | */ 23 | public class Solution { 24 | public ListNode insertionSortList(ListNode head) { 25 | if (head == null || head.next == null) return head; 26 | ListNode dummy = new ListNode(Integer.MIN_VALUE); 27 | dummy.next = head; 28 | ListNode cur = head.next; 29 | head.next = null; 30 | while (cur != null) { 31 | ListNode tmp = dummy; 32 | while (tmp.next != null && tmp.next.val <= cur.val) tmp = tmp.next; 33 | ListNode next = cur.next; 34 | cur.next = tmp.next; 35 | tmp.next = cur; 36 | cur = next; 37 | } 38 | return dummy.next; 39 | } 40 | } -------------------------------------------------------------------------------- /IntegertoRoman.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 13, 2014 4 | Problem: Integer to Roman 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/integer-to-roman/ 7 | Notes: 8 | Given an integer, convert it to a roman numeral. 9 | Input is guaranteed to be within the range from 1 to 3999. 10 | 11 | Solution: Buffer the roman numbers. 12 | */ 13 | 14 | public class Solution { 15 | public String intToRoman(int num) { 16 | int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 17 | String[] numerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; 18 | StringBuilder result = new StringBuilder(); 19 | for(int i=0; i=values[i]) 22 | { 23 | num-=values[i]; 24 | result.append(numerals[i]); 25 | } 26 | } 27 | return result.toString(); 28 | } 29 | } -------------------------------------------------------------------------------- /IntersectionOfTwoLinkedLists.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Nov 28, 2014 4 | Problem: Intersection of Two Linked Lists 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/intersection-of-two-linked-lists/ 7 | 8 | Notes: 9 | Write a program to find the node at which the intersection of two singly linked lists begins. 10 | Hints: 11 | If the two linked lists have no intersection at all, return null. 12 | The linked lists must retain their original structure after the function returns. 13 | You may assume there are no cycles anywhere in the entire linked structure. 14 | Your code should preferably run in O(n) time and use only O(1) memory. 15 | 16 | 17 | Solution: Two iteration. 18 | */ 19 | /** 20 | * Definition for singly-linked list. 21 | * public class ListNode { 22 | * int val; 23 | * ListNode next; 24 | * ListNode(int x) { 25 | * val = x; 26 | * next = null; 27 | * } 28 | * } 29 | */ 30 | public class Solution { 31 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 32 | ListNode cur = headA; 33 | int lenA = 0, lenB = 0; 34 | while (cur != null) { 35 | ++lenA; 36 | cur = cur.next; 37 | } 38 | cur = headB; 39 | while (cur != null) { 40 | ++lenB; 41 | cur = cur.next; 42 | } 43 | if (lenA >= lenB) { 44 | int diff = lenA - lenB; 45 | while (diff > 0) { 46 | headA = headA.next; 47 | --diff; 48 | } 49 | while (headA != null && headB != null) { 50 | if(headA == headB) { 51 | return headA; 52 | } 53 | headA = headA.next; 54 | headB = headB.next; 55 | } 56 | } else { 57 | int diff = lenB - lenA; 58 | while (diff > 0) { 59 | headB = headB.next; 60 | --diff; 61 | } 62 | while (headA != null && headB != null) { 63 | if(headA == headB) { 64 | return headA; 65 | } 66 | headA = headA.next; 67 | headB = headB.next; 68 | } 69 | } 70 | return null; 71 | } 72 | } -------------------------------------------------------------------------------- /JumpGame.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 21, 2014 4 | Problem: Jump Game 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/jump-game/ 7 | Notes: 8 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 9 | Each element in the array represents your maximum jump length at that position. 10 | Determine if you are able to reach the last index. 11 | For example: 12 | A = [2,3,1,1,4], return true. 13 | A = [3,2,1,0,4], return false. 14 | 15 | Solution: Updated solution: try every reachable index. 16 | Thank to Wenxin Xing for kindly feedback and pointing out my big mistake:) 17 | */ 18 | public class Solution { 19 | public boolean canJump(int[] A) { 20 | int pos = 0, n = A.length; 21 | for (int i = 0; i < n; ++i) { 22 | if (pos >= i) { 23 | pos = Math.max(pos, i + A[i]); 24 | } 25 | } 26 | return pos >= n - 1; 27 | } 28 | } -------------------------------------------------------------------------------- /JumpGameII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 21, 2014 4 | Problem: Jump Game II 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/jump-game-ii/ 7 | Notes: 8 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 9 | Each element in the array represents your maximum jump length at that position. 10 | Your goal is to reach the last index in the minimum number of jumps. 11 | For example: 12 | Given array A = [2,3,1,1,4] 13 | The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) 14 | 15 | Solution: Jump to the position where we can jump farthest (index + A[index]) next time. 16 | */ 17 | public class Solution { 18 | public int jump(int[] A) { 19 | int n = A.length; 20 | int last = 0, cur = 0, res = 0; 21 | for (int i = 0; i < n; ++i) { 22 | if (i > last) { 23 | res++; 24 | last = cur; 25 | if (cur >= n - 1) return res; 26 | } 27 | cur = Math.max(cur, i + A[i]); 28 | } 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /LRUCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: March 12, 2014 4 | Problem: LRU Cache 5 | Difficulty: Hard 6 | Source: http://oj.leetcode.com/problems/lru-cache/ 7 | Notes: 8 | Design and implement a data structure for Least Recently Used (LRU) cache. 9 | It should support the following operations: get and set. 10 | get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. 11 | set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. 12 | 13 | Solution: Hash + list. 14 | */ 15 | 16 | import java.util.LinkedHashMap; 17 | import java.util.Map; 18 | public class LRUCache { 19 | private Map map; 20 | private int capacity; 21 | public LRUCache(int capacity) { 22 | this.capacity = capacity; 23 | map = new LinkedHashMap(capacity + 1); 24 | } 25 | 26 | public int get(int key) { 27 | Integer val = map.get(key); 28 | if (val == null) return -1; 29 | map.remove(key); 30 | map.put(key, val); 31 | return val; 32 | } 33 | 34 | public void set(int key, int value) { 35 | map.remove(key); 36 | map.put(key, value); 37 | if (map.size() > capacity) 38 | map.remove(map.entrySet().iterator().next().getKey()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /LargestNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, nkuwjg@gmail.com 3 | Date: Jan 13, 2015 4 | Problem: ZigZag Conversion 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/largest-number/ 7 | Notes: 8 | Given a list of non negative integers, arrange them such that they form the largest number. 9 | 10 | For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 11 | 12 | Note: The result may be very large, so you need to return a string instead of an integer. 13 | 14 | Solution: ... 15 | */ 16 | 17 | public class Solution { 18 | public String largestNumber_1(int[] num) { 19 | int size = num.length; 20 | if (size <= 0) return new String(); 21 | if (size == 1) return String.valueOf(num[0]); 22 | Comparator comp = new Comparator(){ 23 | public int compare(Integer a, Integer b) { 24 | String aa = ""+a+b; 25 | String bb = ""+b+a; 26 | return bb.compareTo(aa); 27 | } 28 | }; 29 | Integer[] in = new Integer[size]; 30 | for (int i = 0; i < size; ++i) 31 | in[i] = Integer.valueOf(num[i]); 32 | Arrays.sort(in, comp); 33 | StringBuffer res = new StringBuffer(); 34 | int i = 0; 35 | while ((i < in.length - 1) && (in[i] == 0)) ++i; 36 | while (i < in.length) res.append(in[i++]); 37 | return res.toString(); 38 | } 39 | public String largestNumber_2(int[] num) { 40 | int size = num.length; 41 | if (size <= 0) return new String(); 42 | String[] in = new String[size]; 43 | for (int i = 0; i < size; ++i) 44 | in[i] = String.valueOf(num[i]); 45 | return foo(in); 46 | } 47 | public String foo(String[] in) { 48 | if (in.length == 0) return new String(); 49 | if (in.length == 1) return in[0]; 50 | StringBuffer res = new StringBuffer(); 51 | Comparator comp = new Comparator(){ 52 | public int compare(String a, String b) { 53 | String aa = a+b; 54 | String bb = b+a; 55 | return bb.compareTo(aa); 56 | } 57 | }; 58 | Arrays.sort(in, comp); 59 | int i = 0; 60 | while ((i < in.length - 1) && (in[i].compareTo("0") == 0)) ++i; 61 | while (i < in.length) res.append(in[i++]); 62 | return res.toString(); 63 | } 64 | } -------------------------------------------------------------------------------- /LargestRectangleinHistogram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 6, 2015 4 | Problem: Largest Rectangle in Histogram 5 | Difficulty: Hard 6 | Source: https://oj.leetcode.com/problems/largest-rectangle-in-histogram/ 7 | Notes: 8 | Given n non-negative integers representing the histogram's bar height where the width of each 9 | bar is 1, find the area of largest rectangle in the histogram. 10 | For example, 11 | Given height = [2,1,5,6,2,3], 12 | return 10. 13 | 14 | Solution: 1. Only calucate area when reaching local maximum value. 15 | 2. Keep a non-descending stack. O(n). if the vector height is not allowed to be changed. 16 | */ 17 | public class Solution { 18 | public int largestRectangleArea_1(int[] height) { 19 | int res = 0; 20 | for (int i = 0; i < height.length; ++i) { 21 | if ((i < height.length - 1) && (height[i] <= height[i+1])) { 22 | continue; 23 | } 24 | int minheight = height[i]; 25 | for (int j = i; j >= 0; --j) { 26 | minheight = Math.min(minheight, height[j]); 27 | res = Math.max(res, (i-j+1)*minheight); 28 | } 29 | } 30 | return res; 31 | } 32 | public int largestRectangleArea(int[] height) { 33 | int res = 0; 34 | Stack stk = new Stack(); 35 | int i = 0; 36 | while (i < height.length) { 37 | if (stk.isEmpty() == true || (height[i] >= height[stk.peek()])) { 38 | stk.push(i++); 39 | } else { 40 | int idx = stk.pop(); 41 | int width = stk.isEmpty() ? i : (i - stk.peek() - 1); 42 | res = Math.max(res, width*height[idx]); 43 | } 44 | } 45 | while (stk.isEmpty() == false) { 46 | int idx = stk.pop(); 47 | int width = stk.isEmpty() ? height.length : (height.length - stk.peek() - 1); 48 | res = Math.max(res, width*height[idx]); 49 | } 50 | return res; 51 | } 52 | } -------------------------------------------------------------------------------- /LengthofLastWord.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Dec 25, 2014 4 | Problem: Length of Last Word 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/length-of-last-word/ 7 | Notes: 8 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 9 | If the last word does not exist, return 0. 10 | Note: A word is defined as a character sequence consists of non-space characters only. 11 | For example, 12 | Given s = "Hello World", 13 | return 5. 14 | 15 | Solution: ... 16 | */ 17 | public class Solution { 18 | public int lengthOfLastWord(String s) { 19 | int res = 0, i = s.length() - 1; 20 | while (i >= 0 && s.charAt(i) == ' ') --i; 21 | while (i >= 0 && s.charAt(i) != ' ') { 22 | --i; ++res; 23 | } 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /LetterCombinationsofaPhoneNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Letter Combinations of a Phone Number 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ 7 | Notes: 8 | Given a digit string, return all possible letter combinations that the number could represent. 9 | A mapping of digit to letters (just like on the telephone buttons) is given below. 10 | Input:Digit string "23" 11 | Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 12 | Note: 13 | Although the above answer is in lexicographical order, your answer could be in any order you want. 14 | 15 | Solution: ... 16 | */ 17 | 18 | public class Solution { 19 | public List letterCombinations(String digits) { 20 | ArrayList res = new ArrayList(); 21 | String[] keyboard = new String[]{" ","","abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 22 | letterCombinationsRe(keyboard,res,digits,""); 23 | return res; 24 | } 25 | public void letterCombinationsRe(String[] keyboard, ArrayList res, String digits, String s) { 26 | if (s.length() == digits.length()) { 27 | res.add(s); 28 | return; 29 | } 30 | String letters = keyboard[digits.charAt(s.length()) - '0']; 31 | for (int i = 0; i < letters.length(); ++i) { 32 | letterCombinationsRe(keyboard, res, digits, s+letters.charAt(i)); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 5, 2014 4 | Problem: Linked List Cycle 5 | Difficulty: Easy 6 | Source: http://oj.leetcode.com/problems/linked-list-cycle/ 7 | Notes: 8 | Given a linked list, determine if it has a cycle in it. 9 | Follow up: 10 | Can you solve it without using extra space? 11 | 12 | Solution: two pointers. 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * class ListNode { 18 | * int val; 19 | * ListNode next; 20 | * ListNode(int x) { 21 | * val = x; 22 | * next = null; 23 | * } 24 | * } 25 | */ 26 | public class Solution { 27 | public boolean hasCycle(ListNode head) { 28 | if (head == null || head.next == null) return false; 29 | ListNode slow = head, fast = head; 30 | while (fast != null && fast.next != null) { 31 | slow = slow.next; 32 | fast = fast.next.next; 33 | if (slow == fast) break; 34 | } 35 | if (fast == null || fast.next == null) return false; 36 | return true; 37 | } 38 | } -------------------------------------------------------------------------------- /LinkedListCycleII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 02, 2015 4 | Problem: Linked List Cycle II 5 | Difficulty: Easy 6 | Source: http://oj.leetcode.com/problems/linked-list-cycle-ii/ 7 | Notes: 8 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 9 | Follow up: 10 | Can you solve it without using extra space? 11 | 12 | Solution: ... 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * class ListNode { 18 | * int val; 19 | * ListNode next; 20 | * ListNode(int x) { 21 | * val = x; 22 | * next = null; 23 | * } 24 | * } 25 | */ 26 | public class Solution { 27 | public ListNode detectCycle(ListNode head) { 28 | if (head == null || head.next == null) return null; 29 | ListNode slow = head, fast = head; 30 | while (fast != null && fast.next != null) { 31 | slow = slow.next; 32 | fast = fast.next.next; 33 | if (slow == fast) break; 34 | } 35 | if (fast == null || fast.next == null) return null; 36 | slow = head; 37 | while (slow != fast) { 38 | slow = slow.next; 39 | fast = fast.next; 40 | } 41 | return slow; 42 | } 43 | } -------------------------------------------------------------------------------- /LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Longest Common Prefix 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/longest-common-prefix/ 7 | Notes: 8 | Write a function to find the longest common prefix string amongst an array of strings. 9 | 10 | Solution: ... 11 | */ 12 | public class Solution { 13 | public String longestCommonPrefix(String[] strs) { 14 | if (strs.length == 0) return new String(""); 15 | for(int i = 0;i < strs[0].length(); ++i){ 16 | for(int j = 1;j < strs.length; ++j){ 17 | if(i >= strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)) 18 | return strs[0].substring(0,i); 19 | } 20 | } 21 | return strs[0]; 22 | } 23 | } -------------------------------------------------------------------------------- /LongestConsecutiveSequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jun 18, 2014 4 | Problem: Longest Consecutive Sequence 5 | Difficulty: Hard 6 | Source: https://oj.leetcode.com/problems/longest-consecutive-sequence/ 7 | Notes: 8 | Given an unsorted array of integers, find the length of the longest consecutive 9 | elements sequence. 10 | For example, 11 | Given [100, 4, 200, 1, 3, 2], 12 | The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. 13 | Your algorithm should run in O(n) complexity. 14 | 15 | Solution 1: Update solution. 16 | */ 17 | 18 | public class Solution { 19 | public int longestConsecutive(int[] num) { 20 | int size = num.length; 21 | HashMap unmap = new HashMap(); 22 | int res = 0; 23 | for (int i = 0; i < size; ++i) { 24 | if (unmap.containsKey(num[i]) == true) continue; 25 | int val = num[i]; 26 | if (unmap.containsKey(val - 1) == true && unmap.containsKey(val + 1) == true) { 27 | unmap.put(val, unmap.get(val - 1) + unmap.get(val + 1) + 1); 28 | unmap.put(val - unmap.get(val - 1), unmap.get(val)); 29 | unmap.put(val + unmap.get(val + 1), unmap.get(val)); 30 | } else if (unmap.containsKey(val - 1) == true) { 31 | unmap.put(val, unmap.get(val - 1) + 1); 32 | unmap.put(val - unmap.get(val - 1), unmap.get(val)); 33 | } else if (unmap.containsKey(val + 1) == true) { 34 | unmap.put(val, unmap.get(val + 1) + 1); 35 | unmap.put(val + unmap.get(val + 1), unmap.get(val)); 36 | } else { 37 | unmap.put(val, 1); 38 | } 39 | res = Math.max(res, unmap.get(val)); 40 | } 41 | return res; 42 | } 43 | } -------------------------------------------------------------------------------- /LongestSubstringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Dec 12, 2014 4 | Problem: Longest Substring Without Repeating Characters 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ 7 | Notes: 8 | Given a string, find the length of the longest substring without repeating characters. 9 | For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. 10 | For "bbbbb" the longest substring is "b", with the length of 1. 11 | 12 | Solution: 1. Pay attention when moving the 'start' pointer forward. 13 | 2. More space, but maybe faster. 14 | */ 15 | public class Solution { 16 | public int lengthOfLongestSubstring_1(String s) { 17 | boolean[] hash = new boolean[256]; 18 | Arrays.fill(hash,false); 19 | int n = s.length(); 20 | if (n <= 1) return n; 21 | int start = 0, end = 0, res = 0; 22 | while (end < n && start + res < n) { 23 | if (hash[s.charAt(end)] == false) { 24 | hash[s.charAt(end++)] = true; 25 | } else { 26 | hash[s.charAt(start++)] = false; 27 | } 28 | res = Math.max(res, end - start); 29 | } 30 | return res; 31 | } 32 | public int lengthOfLongestSubstring_2(String s) { 33 | int[] hash = new int[256]; 34 | Arrays.fill(hash, -1); 35 | int n = s.length(); 36 | if (n <= 1) return n; 37 | hash[s.charAt(0)] = 0; 38 | int start = 0, res = 1, cur = 0; 39 | while (++cur < n) { 40 | if (hash[s.charAt(cur)] >= start) { 41 | start = hash[s.charAt(cur)] + 1; 42 | } 43 | res = Math.max(res, cur - start + 1); 44 | hash[s.charAt(cur)] = cur; 45 | } 46 | return res; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /MajorityElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Majority Element 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/majority-element/ 7 | Notes: 8 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 9 | 10 | You may assume that the array is non-empty and the majority element always exist in the array. 11 | 12 | Solution: 1. Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x: 13 | If the counter is 0, we set the current candidate to x and the counter to 1. 14 | If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate. 15 | After one pass, the current candidate is the majority element. Runtime complexity = O(n). 16 | 2. Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count. 17 | */ 18 | 19 | public class Solution { 20 | public int majorityElement_1(int[] num) { 21 | int n = num.length; 22 | if (n == 0) return 0; 23 | if (n == 1) return num[0]; 24 | int res = num[0], cnt = 1; 25 | for (int i = 1; i < n; ++i) { 26 | if (cnt == 0) { 27 | res = num[i]; 28 | ++cnt; 29 | continue; 30 | } 31 | if (res == num[i]) ++cnt; 32 | else --cnt; 33 | } 34 | return res; 35 | } 36 | public int majorityElement_2(int[] num) { 37 | int n = num.length; 38 | if (n == 0) return 0; 39 | if (n == 1) return num[0]; 40 | int res = 0; 41 | for (int i = 0; i < 32; ++i) { 42 | int one = 0, zero = 0; 43 | for (int j = 0; j < n; ++j) { 44 | if (((num[j]>>i) & 1) == 1) ++one; 45 | else ++zero; 46 | } 47 | if (one > zero) res = res | (1< m = new HashMap(); 26 | int ss = 1, sp = 0; 27 | for (int j = i + 1; j < N; ++j) { 28 | double slope = Double.MIN_VALUE; 29 | if (points[i].x != points[j].x) { 30 | slope = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x); 31 | if (slope == -0.0) slope = 0.0; 32 | } else if (points[i].y == points[j].y) { 33 | sp += 1; continue; 34 | } 35 | int tmp = 2; 36 | if (m.containsKey(slope)) { 37 | tmp = m.get(slope) + 1; 38 | } 39 | m.put(slope, tmp); 40 | ss = Math.max(ss, tmp); 41 | } 42 | res = Math.max(res, ss + sp); 43 | } 44 | return res; 45 | } 46 | } -------------------------------------------------------------------------------- /MaximumDepthofBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Maximum Depth of Binary Tree 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/ 7 | Notes: 8 | Given a binary tree, find its maximum depth. 9 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 10 | 11 | Solution: Recursion. 12 | */ 13 | /** 14 | * Definition for binary tree 15 | * public class TreeNode { 16 | * int val; 17 | * TreeNode left; 18 | * TreeNode right; 19 | * TreeNode(int x) { val = x; } 20 | * } 21 | */ 22 | public class Solution { 23 | public int maxDepth(TreeNode root) { 24 | if (root == null) return 0; 25 | int left = maxDepth(root.left); 26 | int right = maxDepth(root.right); 27 | return Math.max(left, right) + 1; 28 | } 29 | } -------------------------------------------------------------------------------- /MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Oct 06, 2014 4 | Problem: Maximum Product Subarray 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/maximum-product-subarray/ 7 | Notes: 8 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 9 | 10 | For example, given the array [2,3,-2,4], 11 | the contiguous subarray [2,3] has the largest product = 6. 12 | */ 13 | 14 | public class Solution { 15 | public int maxProduct(int[] A) { 16 | if (A.length <= 0) { 17 | return 0; 18 | } 19 | int maxVal = A[0], minVal = A[0], res = A[0]; 20 | for (int i = 1; i < A.length; ++i) { 21 | int tmpVal = maxVal; 22 | maxVal = Math.max(Math.max(maxVal * A[i], minVal * A[i]), A[i]); 23 | minVal = Math.min(Math.min(tmpVal * A[i], minVal * A[i]), A[i]); 24 | res = Math.max(res, maxVal); 25 | } 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Maximum Subarray 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/maximum-subarray/ 7 | 8 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 9 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6. 10 | 11 | Solution: dp. 12 | */ 13 | public class Solution { 14 | public int maxSubArray_1(int[] A) { 15 | if (A.length == 0) return 0; 16 | int minVal = Math.min(A[0],0), res = A[0], sum = A[0]; 17 | for (int i = 1; i < A.length; ++i) { 18 | sum += A[i]; 19 | res = Math.max(res, sum - minVal); 20 | minVal = Math.min(minVal, sum); 21 | } 22 | return res; 23 | } 24 | public int maxSubArray_2(int[] A) { 25 | if (A.length == 0) return 0; 26 | int dp = A[0], res = A[0]; 27 | for (int i = 1; i < A.length; ++i) { 28 | dp = Math.max(A[i], dp + A[i]); 29 | res = Math.max(res, dp); 30 | } 31 | return res; 32 | } 33 | } -------------------------------------------------------------------------------- /MedianofTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Median of Two Sorted Arrays 5 | Difficulty: Hard 6 | Source: http://leetcode.com/onlinejudge#question_4 7 | Notes: 8 | There are two sorted arrays A and B of size m and n respectively. 9 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 10 | 11 | Solution: 1. O(m+n) 12 | 2. O(log(m+n)) 13 | */ 14 | 15 | public class Solution { 16 | public double findMedianSortedArrays_1(int A[], int B[]) { 17 | int m = A.length, n = B.length; 18 | int total = n + m, m1=0, m2=0, i=0, j=0; 19 | for (int k = 1; k <= total/2 + 1; ++k) { 20 | int a = (i==m) ? Integer.MAX_VALUE : A[i]; 21 | int b = (j==n) ? Integer.MAX_VALUE : B[j]; 22 | m1 = m2; 23 | m2 = Math.min(a,b); 24 | if (a > b) ++j; 25 | else ++i; 26 | } 27 | if ((total&1) == 1) return m2; 28 | else return (m1+m2)/2.0; 29 | } 30 | public double findMedianSortedArrays_2(int A[], int B[]) { 31 | int m = A.length, n = B.length; 32 | int total = m + n; 33 | int k = total / 2; 34 | if ((total&1) == 1) return findKth(A,B,k+1,0,m-1,0,n-1); 35 | else return (findKth(A,B,k,0,m-1,0,n-1)+findKth(A,B,k+1,0,m-1,0,n-1))/2.0; 36 | } 37 | public double findKth(int A[], int B[], int k, int astart, int aend, int bstart, int bend) { 38 | int alen = aend - astart + 1; 39 | int blen = bend - bstart + 1; 40 | if (alen > blen) return findKth(B,A,k, bstart, bend, astart, aend); 41 | if (alen == 0) return B[bstart + k - 1]; 42 | if (k == 1) return Math.min(A[astart],B[bstart]); 43 | int sa = Math.min(alen, k/2), sb = k- sa; 44 | if (A[astart+sa-1] == B[bstart+sb-1]) return A[astart+sa-1]; 45 | else if (A[astart+sa-1] > B[bstart+sb-1]) return findKth(A,B,k - sb,astart,aend,bstart+sb,bend); 46 | else return findKth(A,B,k - sa,astart+sa,aend,bstart,bend); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /MergeIntervals.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Merge Intervals 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/merge-intervals/ 7 | Notes: 8 | Given a collection of intervals, merge all overlapping intervals. 9 | For example, 10 | Given [1,3],[2,6],[8,10],[15,18], 11 | return [1,6],[8,10],[15,18]. 12 | 13 | Solution: 1. Sort in ascending order of 'start'. 14 | 2. Traverse the 'intervals', merge or push... 15 | */ 16 | 17 | /** 18 | * Definition for an interval. 19 | * public class Interval { 20 | * int start; 21 | * int end; 22 | * Interval() { start = 0; end = 0; } 23 | * Interval(int s, int e) { start = s; end = e; } 24 | * } 25 | */ 26 | public class Solution { 27 | public List merge(List intervals) { 28 | Comparator comp = new Comparator(){ 29 | public int compare(Interval a, Interval b) { 30 | if(a.start < b.start) { 31 | return -1; 32 | }else if(a.start > b.start){ 33 | return 1; 34 | } else { 35 | if (a.end < b.end) return -1; 36 | else if (a.end > b.end) return 1; 37 | return 0; 38 | } 39 | } 40 | }; 41 | ArrayList res = new ArrayList(); 42 | int N = intervals.size(); 43 | if (N <= 1) return intervals; 44 | Collections.sort(intervals, comp); 45 | Interval last = intervals.get(0); 46 | for (int i = 0; i < N; ++i) { 47 | if (intervals.get(i).start > last.end) { 48 | res.add(last); 49 | last = intervals.get(i); 50 | } else { 51 | last.end = Math.max(last.end, intervals.get(i).end); 52 | } 53 | } 54 | res.add(last); 55 | return res; 56 | } 57 | } -------------------------------------------------------------------------------- /MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 7, 2015 4 | Problem: Merge Sorted Array 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/merge-sorted-array/ 7 | Notes: 8 | Given two sorted integer arrays A and B, merge B into A as one sorted array. 9 | Note: 10 | You may assume that A has enough space to hold additional elements from B. 11 | The number of elements initialized in A and B are m and n respectively. 12 | 13 | Solution: From back to forth. 14 | */ 15 | 16 | public class Solution { 17 | public void merge(int A[], int m, int B[], int n) { 18 | int i = m - 1; 19 | int j = n - 1; 20 | int x = m + n - 1; 21 | while (i >= 0 && j >= 0) 22 | if (A[i] >= B[j]) A[x--] = A[i--]; 23 | else A[x--] = B[j--]; 24 | while (j >= 0) A[x--] = B[j--]; 25 | } 26 | } -------------------------------------------------------------------------------- /MergeTwoSortedLists.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 2, 2015 4 | Problem: Merge Two Sorted Lists 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/merge-two-sorted-lists/ 7 | Notes: 8 | Merge two sorted linked lists and return it as a new list. 9 | The new list should be made by splicing together the nodes of the first two lists. 10 | 11 | Solution: ... 12 | */ 13 | 14 | /** 15 | * Definition for singly-linked list. 16 | * public class ListNode { 17 | * int val; 18 | * ListNode next; 19 | * ListNode(int x) { 20 | * val = x; 21 | * next = null; 22 | * } 23 | * } 24 | */ 25 | public class Solution { 26 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 27 | ListNode head = new ListNode(0); 28 | ListNode cur = head; 29 | while (l1 != null && l2 != null) { 30 | if (l1.val < l2.val) { 31 | cur.next = l1; 32 | l1 = l1.next; 33 | } else { 34 | cur.next = l2; 35 | l2 = l2.next; 36 | } 37 | cur = cur.next; 38 | } 39 | if (l1 != null) cur.next = l1; 40 | if (l2 != null) cur.next = l2; 41 | return head.next; 42 | } 43 | } -------------------------------------------------------------------------------- /MinStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Nov 14, 2014 4 | Problem: Min Stack 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/min-stack/ 7 | Notes: 8 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 9 | push(x) -- Push element x onto stack. 10 | pop() -- Removes the element on top of the stack. 11 | top() -- Get the top element. 12 | getMin() -- Retrieve the minimum element in the stack. 13 | */ 14 | 15 | class MinStack { 16 | private Stack stack = new Stack<>(); 17 | private Stack minStack = new Stack<>(); 18 | public void push(int x) { 19 | stack.push(x); 20 | if (minStack.isEmpty() || x <= minStack.peek()) { 21 | minStack.push(x); 22 | } 23 | } 24 | public void pop() { 25 | if (stack.pop().equals(minStack.peek())) minStack.pop(); 26 | } 27 | public int top() { 28 | return stack.peek(); 29 | } 30 | public int getMin() { 31 | return minStack.peek(); 32 | } 33 | } -------------------------------------------------------------------------------- /MinimumDepthofBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Minimum Depth of Binary Tree 5 | Difficulty: easy 6 | Source: https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/ 7 | Notes: 8 | Given a binary tree, find its minimum depth. 9 | The minimum depth is the number of nodes along the shortest path from the root node 10 | down to the nearest leaf node. 11 | 12 | Solution: 1. Recursion. Pay attention to cases when the non-leaf node has only one child. 13 | PS. 2. Iteration + Queue. 14 | */ 15 | 16 | /** 17 | * Definition for binary tree 18 | * public class TreeNode { 19 | * int val; 20 | * TreeNode left; 21 | * TreeNode right; 22 | * TreeNode(int x) { val = x; } 23 | * } 24 | */ 25 | public class Solution { 26 | public int minDepth(TreeNode root) { 27 | if (root == null) return 0; 28 | if (root.left == null) return minDepth(root.right) + 1; 29 | if (root.right == null) return minDepth(root.left) + 1; 30 | return Math.min(minDepth(root.left), minDepth(root.right)) + 1; 31 | } 32 | } -------------------------------------------------------------------------------- /MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 26, 2014 4 | Problem: Minimum Path Sum 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/minimum-path-sum/ 7 | Notes: 8 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right 9 | which minimizes the sum of all numbers along its path. 10 | Note: You can only move either down or right at any point in time. 11 | 12 | Solution: Dynamic Programming. Space O(N). 13 | */ 14 | public class Solution { 15 | public int minPathSum(int[][] grid) { 16 | if (grid.length == 0) return Integer.MIN_VALUE; 17 | int M = grid.length, N = grid[0].length; 18 | int[] dp = new int[N]; 19 | dp[0] = grid[0][0]; 20 | for (int i = 1; i < N; ++i) 21 | dp[i] = grid[0][i] + dp[i-1]; 22 | 23 | for (int i = 1; i < M; ++i) 24 | { 25 | dp[0] += grid[i][0]; 26 | for (int j = 1; j < N; ++j) 27 | dp[j] = Math.min(dp[j-1], dp[j]) + grid[i][j]; 28 | } 29 | 30 | return dp[N-1]; 31 | } 32 | } -------------------------------------------------------------------------------- /MinimumWindowSubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Dec 25, 2014 4 | Problem: Minimum Window Substring 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/minimum-window-substring/ 7 | Notes: 8 | Given a string S and a string T, find the minimum window in S which will contain all the 9 | characters in T in complexity O(n). 10 | For example, 11 | S = "ADOBECODEBANC" 12 | T = "ABC" 13 | Minimum window is "BANC". 14 | Note: 15 | If there is no such window in S that covers all characters in T, return the empty string "". 16 | If there are multiple such windows, you are guaranteed that there will always be only one unique 17 | minimum window in S. 18 | 19 | Solution: 1. Use two pointers: start and end. 20 | First, move 'end'. After finding all the needed characters, move 'start'. 21 | 2. Use array as hashtable. 22 | */ 23 | 24 | public class Solution { 25 | public String minWindow(String S, String T) { 26 | int N = S.length(), M = T.length(); 27 | if (N < M) return new String(""); 28 | int[] need = new int[256]; 29 | int[] find = new int[256]; 30 | for (int i = 0; i < M; ++i) 31 | need[T.charAt(i)]++; 32 | 33 | int count = 0, resStart = -1, resEnd = N; 34 | for (int start = 0, end = 0; end < N; ++end) 35 | { 36 | if (need[S.charAt(end)] == 0) 37 | continue; 38 | if (find[S.charAt(end)] < need[S.charAt(end)]) 39 | count++; 40 | find[S.charAt(end)]++; 41 | if (count != M) continue; 42 | // move 'start' 43 | for (; start < end; ++start) { 44 | if (need[S.charAt(start)] == 0) continue; 45 | if (find[S.charAt(start)] <= need[S.charAt(start)]) break; 46 | find[S.charAt(start)]--; 47 | } 48 | // update result 49 | if (end - start < resEnd - resStart) { 50 | resStart = start; 51 | resEnd = end; 52 | } 53 | } 54 | return (resStart == -1) ? new String("") : S.substring(resStart, resEnd + 1); 55 | } 56 | } -------------------------------------------------------------------------------- /MultiplyStrings.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Multiply Strings 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/multiply-strings/ 7 | Notes: 8 | Given two numbers represented as strings, return multiplication of the numbers as a string. 9 | Note: The numbers can be arbitrarily large and are non-negative. 10 | 11 | Solution: Just like what we do when multiplying integers. 12 | */ 13 | public class Solution { 14 | public String multiply(String num1, String num2) { 15 | int l1 = num1.length(), l2 = num2.length(); 16 | if (l1 == 0 || l2 == 0) return new String(""); 17 | if (num1.charAt(0) == '0' || num2.charAt(0) == '0') return new String("0"); 18 | StringBuffer sb = new StringBuffer(); 19 | int[] res = new int[l1+l2]; 20 | for (int i = 0; i < l1; ++i) { 21 | for (int j = 0; j < l2; ++j) { 22 | res[i+j+1] += (num1.charAt(i)-'0') *(num2.charAt(j)-'0'); 23 | } 24 | } 25 | int c = 0; 26 | for (int i = res.length - 1; i>=1; --i) { 27 | res[i] += c; 28 | c = res[i] / 10; 29 | res[i] = res[i] % 10; 30 | sb.insert(0,res[i]); 31 | } 32 | if (c !=0 || res[0] != 0) { 33 | sb.insert(0,c+res[0]); 34 | } 35 | return sb.toString(); 36 | } 37 | } -------------------------------------------------------------------------------- /N-Queens.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, nkuwjg@gmail.com 3 | Date: Jul 25, 2013 4 | Problem: N-Queens 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/n-queens/ 7 | Notes: 8 | The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other. 9 | Given an integer n, return all distinct solutions to the n-queens puzzle. 10 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. 11 | For example, 12 | There exist two distinct solutions to the 4-queens puzzle: 13 | [ 14 | [".Q..", // Solution 1 15 | "...Q", 16 | "Q...", 17 | "..Q."], 18 | 19 | ["..Q.", // Solution 2 20 | "Q...", 21 | "...Q", 22 | ".Q.."] 23 | ] 24 | 25 | Solution: Recursion (DFS). Use bit-manipulation solution (See N-QueensII for more details). 26 | */ 27 | 28 | 29 | public class Solution { 30 | public List solveNQueens(int n) { 31 | List res = new ArrayList(); 32 | List sol = new ArrayList(); 33 | solveNQueensRe(n, 0, 0, 0, sol, res); 34 | return res; 35 | } 36 | public void solveNQueensRe(int n, int row, int ld, int rd, List sol, List res) { 37 | if (row == (1<= 0; --i) { 46 | int pos = 1 << i; 47 | if ((int)(avail & pos) != 0) { 48 | char[] str = new char[n]; 49 | Arrays.fill(str, '.'); 50 | str[i] = 'Q'; 51 | sol.add(str); 52 | solveNQueensRe(n, row | pos, (ld|pos)<<1, (rd|pos)>>1, sol, res); 53 | sol.remove(sol.size()-1); 54 | } 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Aug 22, 2013 4 | Problem: Palindrome Number 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/palindrome-number/ 7 | Notes: 8 | Determine whether an integer is a palindrome. Do this without extra space. 9 | Some hints: 10 | Could negative integers be palindromes? (ie, -1) (No!) 11 | If you are thinking of converting the integer to string, note the restriction of using extra space. 12 | You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", 13 | you know that the reversed integer might overflow. How would you handle such case? 14 | There is a more generic way of solving this problem. 15 | 16 | Solution: 1. Count the number of digits first (traverse once) then check the digits from both sides to center. 17 | 2. Reverse the number, then check to see if x == reverse(x). 18 | 3. Recursion (interesting but a little hard to understand). -> See C++. 19 | */ 20 | public class Solution { 21 | public boolean isPalindrome(int x) { 22 | return isPalindrome_2(x); 23 | } 24 | public boolean isPalindrome_1(int x) { 25 | if (x < 0) return false; 26 | int d = 1; 27 | while (x / d >= 10) d *= 10; 28 | while (d > 1) { 29 | if (x % 10 != x / d) return false; 30 | x = (x % d) / 10; 31 | d /= 100; 32 | } 33 | return true; 34 | } 35 | public boolean isPalindrome_2(int x) { 36 | if (x < 0) return false; 37 | return x == reverse(x); 38 | } 39 | public int reverse(int x) { 40 | int res = 0; 41 | while (x > 0) { 42 | res = res * 10 + x % 10; 43 | x = x / 10; 44 | } 45 | return res; 46 | } 47 | } -------------------------------------------------------------------------------- /PalindromePartitioning.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 20, 2015 4 | Problem: Palindrome Partitioning 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/palindrome-partitioning/ 7 | Notes: 8 | Given a string s, partition s such that every substring of the partition is a palindrome. 9 | Return all possible palindrome partitioning of s. 10 | For example, given s = "aab", 11 | Return 12 | [ 13 | ["aa","b"], 14 | ["a","a","b"] 15 | ] 16 | 17 | Solution: ... 18 | */ 19 | 20 | public class Solution { 21 | public List> partition(String s) { 22 | List> res = new ArrayList>(); 23 | int n = s.length(); 24 | boolean[][] dp = new boolean[n][n]; 25 | for (int i = n - 1; i >= 0; --i) { 26 | for (int j = i; j < n; ++j) { 27 | dp[i][j]=(s.charAt(i)==s.charAt(j))&&(j path = new ArrayList(); 31 | dfs(s, dp, 0, path, res); 32 | return res; 33 | } 34 | public void dfs(String s, boolean[][] dp, int start, ArrayList path, List> res) { 35 | if (s.length() == start) { 36 | res.add(new ArrayList(path)); 37 | return; 38 | } 39 | for (int i = start; i < s.length(); ++i) { 40 | if (dp[start][i] == false) continue; 41 | path.add(s.substring(start,i+1)); 42 | dfs(s, dp, i+1,path,res); 43 | path.remove(path.size()-1); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /PalindromePartitioningII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 23, 2015 4 | Problem: Palindrome Partitioning II 5 | Difficulty: Hard 6 | Source: https://oj.leetcode.com/problems/palindrome-partitioning-ii/ 7 | Notes: 8 | Given a string s, partition s such that every substring of the partition is a palindrome. 9 | Return the minimum cuts needed for a palindrome partitioning of s. 10 | For example, given s = "aab", 11 | Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 12 | 13 | Solution: dp. 14 | */ 15 | public class Solution { 16 | public int minCut(String s) { 17 | int n = s.length(); 18 | int[] dp = new int[n+1]; 19 | dp[n] = -1; 20 | boolean[][] isP = new boolean[n][n]; 21 | for (int i = n - 1; i >= 0; --i) { 22 | dp[i] = n - 1 - i; 23 | for (int j = i; j < n; ++j) { 24 | if (s.charAt(i) == s.charAt(j) && (j < i + 2 || isP[i+1][j-1])) isP[i][j] = true; 25 | if (isP[i][j] == true) { 26 | dp[i] = Math.min(dp[i], 1 + dp[j+1]); 27 | } 28 | } 29 | } 30 | return dp[0]; 31 | } 32 | } -------------------------------------------------------------------------------- /PartitionList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 7, 2014 4 | Problem: Partition List 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/partition-list/ 7 | Notes: 8 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 9 | You should preserve the original relative order of the nodes in each of the two partitions. 10 | For example, 11 | Given 1->4->3->2->5->2 and x = 3, 12 | return 1->2->2->4->3->5. 13 | 14 | Solution: ... 15 | */ 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * public class ListNode { 20 | * int val; 21 | * ListNode next; 22 | * ListNode(int x) { 23 | * val = x; 24 | * next = null; 25 | * } 26 | * } 27 | */ 28 | public class Solution { 29 | public ListNode partition_1(ListNode head, int x) { 30 | ListNode leftdummy = new ListNode(-1); 31 | ListNode rightdummy = new ListNode(-1); 32 | ListNode lhead = leftdummy; 33 | ListNode rhead = rightdummy; 34 | 35 | for(ListNode cur = head; cur != null; cur=cur.next){ 36 | if(cur.val < x){ 37 | lhead.next = cur; 38 | lhead = lhead.next; 39 | }else{ 40 | rhead.next = cur; 41 | rhead = rhead.next; 42 | } 43 | } 44 | lhead.next = rightdummy.next; 45 | rhead.next = null; 46 | return leftdummy.next; 47 | } 48 | public ListNode partition(ListNode head, int x) { 49 | ListNode dummy = new ListNode(-1); 50 | dummy.next = head; 51 | ListNode cur = dummy; 52 | ListNode ins = dummy; 53 | while (cur.next != null && cur.next.val < x) { 54 | cur = cur.next; 55 | ins = ins.next; 56 | } 57 | while (cur.next != null) { 58 | if (cur.next.val >= x) { 59 | cur = cur.next; 60 | } else { 61 | ListNode node = cur.next; 62 | cur.next = cur.next.next; 63 | node.next = ins.next; 64 | ins.next = node; 65 | ins = ins.next; 66 | } 67 | } 68 | return dummy.next; 69 | } 70 | } -------------------------------------------------------------------------------- /Pascal'sTriangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Apr 16, 2013 4 | Problem: Pascal's Triangle 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_118 7 | Notes: 8 | Given numRows, generate the first numRows of Pascal's triangle. 9 | For example, given numRows = 5, 10 | Return 11 | [ 12 | [1], 13 | [1,1], 14 | [1,2,1], 15 | [1,3,3,1], 16 | [1,4,6,4,1] 17 | ] 18 | 19 | Solution: ..... 20 | */ 21 | public class Solution { 22 | public List> generate(int numRows) { 23 | List> res = new ArrayList>(); 24 | if (numRows < 1) return res; 25 | List temp = new ArrayList(); 26 | temp.add(1); 27 | res.add(temp); 28 | for (int i = 1; i < numRows; ++i) { 29 | List t = new ArrayList(); 30 | t.add(1); 31 | for (int j = 1; j < i; ++j) { 32 | t.add(res.get(i-1).get(j-1) + res.get(i-1).get(j)); 33 | } 34 | t.add(1); 35 | res.add(t); 36 | } 37 | return res; 38 | } 39 | } -------------------------------------------------------------------------------- /Pascal'sTriangleII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Annie Kim, anniekim.pku@gmail.com 3 | Date: Apr 16, 2013 4 | Problem: Pascal's Triangle II 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_119 7 | Notes: 8 | Given an index k, return the kth row of the Pascal's triangle. 9 | For example, given k = 3, 10 | Return [1,3,3,1]. 11 | Note: 12 | Could you optimize your algorithm to use only O(k) extra space? 13 | 14 | Solution: from back to forth... 15 | */ 16 | public class Solution { 17 | public List getRow(int rowIndex) { 18 | List res = new ArrayList(); 19 | res.add(1); 20 | for (int i = 1; i <= rowIndex; ++i) { 21 | for (int j = i - 1; j >= 1; --j) { 22 | res.set(j,res.get(j) + res.get(j-1)); 23 | } 24 | res.add(1); 25 | } 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /PathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Annie Kim, anniekim.pku@gmail.com 3 | Date: Apr 6, 2013 4 | Update: Jul 26, 2013 5 | Problem: Path Sum 6 | Difficulty: easy 7 | Source: http://www.leetcode.com/onlinejudge 8 | Notes: 9 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up 10 | all the values along the path equals the given sum. 11 | 12 | For example: 13 | Given the below binary tree and sum = 22, 14 | 5 15 | / \ 16 | 4 8 17 | / / \ 18 | 11 13 4 19 | / \ \ 20 | 7 2 1 21 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 22 | 23 | Solution: Recursion. 24 | */ 25 | /** 26 | * Definition for binary tree 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 | public boolean hasPathSum(TreeNode root, int sum) { 36 | if (root == null) return false; 37 | if (root.left == null && root.right == null) return sum == root.val; 38 | return hasPathSum(root.left, sum - root.val) || 39 | hasPathSum(root.right, sum - root.val); 40 | } 41 | } -------------------------------------------------------------------------------- /PathSum2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 7, 2014 4 | Problem: Path Sum 2 5 | Difficulty: easy 6 | Source: https://oj.leetcode.com/problems/path-sum-ii/ 7 | Notes: 8 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 9 | 10 | For example: 11 | Given the below binary tree and sum = 22, 12 | 5 13 | / \ 14 | 4 8 15 | / / \ 16 | 11 13 4 17 | / \ / \ 18 | 7 2 5 1 19 | return 20 | [ 21 | [5,4,11,2], 22 | [5,8,4,5] 23 | ] 24 | 25 | Solution: DFS. 26 | */ 27 | 28 | /** 29 | * Definition for binary tree 30 | * public class TreeNode { 31 | * int val; 32 | * TreeNode left; 33 | * TreeNode right; 34 | * TreeNode(int x) { val = x; } 35 | * } 36 | */ 37 | public class Solution { 38 | public List> pathSum(TreeNode root, int sum) { 39 | List> res = new ArrayList>(); 40 | ArrayList path = new ArrayList(); 41 | pathSumRe(root, sum, res, path); 42 | return res; 43 | } 44 | public void pathSumRe(TreeNode root, int sum, List> res, ArrayList path) 45 | { 46 | if (root == null) return; 47 | path.add(root.val); 48 | if (root.left == null && root.right == null && root.val == sum){ 49 | ArrayList tmp = new ArrayList(path); 50 | res.add(tmp); 51 | } 52 | pathSumRe(root.left, sum - root.val, res, path); 53 | pathSumRe(root.right, sum - root.val, res, path); 54 | path.remove(path.size()-1); 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /PermutationSequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Permutation Sequence 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/permutation-sequence/ 7 | Notes: 8 | The set [1,2,3,...,n] contains a total of n! unique permutations. 9 | By listing and labeling all of the permutations in order, 10 | We get the following sequence (ie, for n = 3): 11 | "123" 12 | "132" 13 | "213" 14 | "231" 15 | "312" 16 | "321" 17 | Given n and k, return the kth permutation sequence. 18 | Note: Given n will be between 1 and 9 inclusive. 19 | 20 | Solution: 1. Brute! 21 | 2. combinatorial mathematics. 22 | */ 23 | public class Solution { 24 | public void nextPermutation(char[] num) { 25 | int last = num.length - 1; 26 | int i = last; 27 | while (i > 0 && num[i - 1] >= num [i]) --i; 28 | for (int l = i, r = last; l < r; ++l, --r) { 29 | num[l] = (char) (num[l] ^ num[r]); 30 | num[r] = (char) (num[l] ^ num[r]); 31 | num[l] = (char) (num[l] ^ num[r]); 32 | } 33 | if (i == 0) { 34 | return; 35 | } 36 | int j = i; 37 | while (j <= last && num[i-1] >= num[j]) ++j; 38 | num[i-1] = (char) (num[i-1] ^ num[j]); 39 | num[j] = (char) (num[i-1] ^ num[j]); 40 | num[i-1] = (char) (num[i-1] ^ num[j]); 41 | } 42 | public String getPermutation_1(int n, int k) { 43 | char[] num = new char[n]; 44 | for (int i = 0; i < n; ++i) num[i] = (char) (i + '1'); 45 | System.out.println(String.valueOf(num)); 46 | while (--k != 0) { 47 | nextPermutation(num); 48 | } 49 | return String.valueOf(num); 50 | } 51 | public String getPermutation_2(int n, int k) { 52 | StringBuffer sb = new StringBuffer(); 53 | StringBuffer res = new StringBuffer(); 54 | int total = 1; 55 | for (int i = 1; i <= n; ++i) { 56 | total = total * i; 57 | sb.append(i); 58 | } 59 | k--; 60 | while(n != 0) { 61 | total = total / n; 62 | int idx = k / total; 63 | res.append(sb.charAt(idx)); 64 | k = k % total; 65 | sb.deleteCharAt(idx); 66 | n--; 67 | } 68 | return res.toString(); 69 | } 70 | } -------------------------------------------------------------------------------- /PlusOne.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Plus One 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/plus-one/ 7 | Notes: 8 | Given a number represented as an array of digits, plus one to the number. 9 | 10 | Solution: ... 11 | */ 12 | 13 | public class Solution { 14 | public int[] plusOne(int[] digits) { 15 | if (digits.length == 0) return digits; 16 | int carry = 1; 17 | for (int i = digits.length - 1; i >= 0; --i) { 18 | digits[i] += carry; 19 | carry = digits[i] / 10; 20 | digits[i] = digits[i] % 10; 21 | } 22 | if (carry == 0) return digits; 23 | int[] res = new int[digits.length + 1]; 24 | res[0] = carry; 25 | System.arraycopy(digits, 0, res, 1, digits.length); 26 | return res; 27 | } 28 | } -------------------------------------------------------------------------------- /PopulatingNextRightPointersinEachNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 7, 2014 4 | Problem: Populating Next Right Pointers in Each Node 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_116 7 | Notes: 8 | Given a binary tree 9 | struct TreeLinkNode { 10 | TreeLinkNode *left; 11 | TreeLinkNode *right; 12 | TreeLinkNode *next; 13 | } 14 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 15 | Initially, all next pointers are set to NULL. 16 | Note: 17 | You may only use constant extra space. 18 | You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). 19 | For example, 20 | Given the following perfect binary tree, 21 | 1 22 | / \ 23 | 2 3 24 | / \ / \ 25 | 4 5 6 7 26 | After calling your function, the tree should look like: 27 | 1 -> NULL 28 | / \ 29 | 2 -> 3 -> NULL 30 | / \ / \ 31 | 4->5->6->7 -> NULL 32 | 33 | Solution: 1. Iterative: Two 'while' loops. 34 | 2. Iterative: Queue. Use extra space. 35 | 3. Recursive: DFS. Defect: Use extra stack space for recursion. 36 | */ 37 | 38 | /** 39 | * Definition for binary tree with next pointer. 40 | * public class TreeLinkNode { 41 | * int val; 42 | * TreeLinkNode left, right, next; 43 | * TreeLinkNode(int x) { val = x; } 44 | * } 45 | */ 46 | public class Solution { 47 | public void connect(TreeLinkNode root) { 48 | if (root == null) return; 49 | TreeLinkNode dummy = new TreeLinkNode(-1); 50 | TreeLinkNode pre = dummy; 51 | TreeLinkNode cur = root; 52 | while (cur != null) { 53 | if (cur.left != null) { 54 | pre.next = cur.left; 55 | pre = pre.next; 56 | } 57 | if (cur.right != null) { 58 | pre.next = cur.right; 59 | pre = pre.next; 60 | } 61 | cur = cur.next; 62 | } 63 | connect(dummy.next); 64 | } 65 | } -------------------------------------------------------------------------------- /PopulatingNextRightPointersinEachNodeII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@gmail.com 3 | Date: Oct 7, 2014 4 | Problem: Populating Next Right Pointers in Each Node II 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ 7 | Notes: 8 | Follow up for problem "Populating Next Right Pointers in Each Node". 9 | What if the given tree could be any binary tree? Would your previous solution still work? 10 | Note: 11 | You may only use constant extra space. 12 | For example, 13 | Given the following binary tree, 14 | 1 15 | / \ 16 | 2 3 17 | / \ \ 18 | 4 5 7 19 | After calling your function, the tree should look like: 20 | 1 -> NULL 21 | / \ 22 | 2 -> 3 -> NULL 23 | / \ \ 24 | 4-> 5 -> 7 -> NULL 25 | 26 | Solution: 1. iterative way with CONSTANT extra space. 27 | 2. iterative way + queue. Contributed by SUN Mian(孙冕). 28 | 3. recursive solution. 29 | */ 30 | 31 | /** 32 | * Definition for binary tree with next pointer. 33 | * public class TreeLinkNode { 34 | * int val; 35 | * TreeLinkNode left, right, next; 36 | * TreeLinkNode(int x) { val = x; } 37 | * } 38 | */ 39 | public class Solution { 40 | public void connect(TreeLinkNode root) { 41 | if (root == null) return; 42 | TreeLinkNode dummy = new TreeLinkNode(-1); 43 | TreeLinkNode pre = dummy; 44 | TreeLinkNode cur = root; 45 | while (cur != null) { 46 | if (cur.left != null) { 47 | pre.next = cur.left; 48 | pre = pre.next; 49 | } 50 | if (cur.right != null) { 51 | pre.next = cur.right; 52 | pre = pre.next; 53 | } 54 | cur = cur.next; 55 | } 56 | connect(dummy.next); 57 | } 58 | } -------------------------------------------------------------------------------- /Pow(x,n).java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Pow(x, n) 5 | Difficulty: easy 6 | Source: https://oj.leetcode.com/problems/powx-n/ 7 | Notes: 8 | Implement pow(x, n). 9 | 10 | Solution: recursion. 11 | */ 12 | public class Solution { 13 | public double pow(double x, int n) { 14 | if (x < 0) return (n % 2 == 0) ? pow(-x, n) : -pow(-x, n); 15 | if (x == 0 || x == 1) return x; 16 | if (n < 0) return 1.0 / pow(x,-n); 17 | if (n == 0) return 1.0; 18 | if (n == 1) return x; 19 | double half = pow(x,n/2); 20 | if (n % 2 == 0) return half * half; 21 | else return x * half * half; 22 | } 23 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | LeetCode-Java 2 | ============= 3 | 4 | LeetCode Solutions By Java 5 | -------------------------------------------------------------------------------- /RegularExpressionMatching.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Oct 26, 2014 4 | Problem: Regular Expression Matching 5 | Difficulty: Hard 6 | Source: https://oj.leetcode.com/problems/regular-expression-matching/ 7 | Notes: 8 | Implement regular expression matching with support for '.' and '*'. 9 | '.' Matches any single character. 10 | '*' Matches zero or more of the preceding element. 11 | The matching should cover the entire input string (not partial). 12 | The function prototype should be: 13 | bool isMatch(const char *s, const char *p) 14 | Some examples: 15 | isMatch("aa","a") ? false 16 | isMatch("aa","aa") ? true 17 | isMatch("aaa","aa") ? false 18 | isMatch("aa", "a*") ? true 19 | isMatch("aa", ".*") ? true 20 | isMatch("ab", ".*") ? true 21 | isMatch("aab", "c*a*b") ? true 22 | 23 | Solution: 1. Recursion. 24 | 2. DP. 25 | */ 26 | 27 | public class Solution { 28 | public boolean isMatch_1(String s, String p) { 29 | if (p.length() == 0) return s.length() == 0; 30 | if (p.length() == 1) { 31 | if (s.length() != 1) return false; 32 | return (s.charAt(0) == p.charAt(0)) || (p.charAt(0) == '.'); 33 | } 34 | if (s.length() != 0 && (p.charAt(0) == s.charAt(0) || (p.charAt(0) == '.'))) { 35 | if (p.charAt(1) == '*') 36 | return isMatch(s.substring(1),p) || isMatch(s, p.substring(2)); 37 | return isMatch(s.substring(1), p.substring(1)); 38 | } 39 | return p.charAt(1) == '*' && isMatch(s, p.substring(2)); 40 | } 41 | public boolean isMatch_2(String s, String p) { 42 | if (p.length() == 0) return s.length() == 0; 43 | int sLen = s.length(), pLen = p.length(); 44 | boolean[][] dp = new boolean[sLen + 1][pLen + 1]; 45 | dp[0][0] = true; 46 | for (int i = 2; i <= pLen; ++i) { 47 | dp[0][i] = dp[0][i-2] && p.charAt(i-1) == '*'; 48 | } 49 | for (int i = 1; i <= sLen; ++i) { 50 | for (int j = 1; j <= pLen; ++j) { 51 | char ch1 = s.charAt(i-1), ch2 = p.charAt(j-1); 52 | if (ch2 != '*') dp[i][j] = dp[i-1][j-1] && (ch1 == ch2 || ch2 == '.'); 53 | else { 54 | dp[i][j] = dp[i][j-2]; 55 | if (ch1 == p.charAt(j-2) || p.charAt(j-2) == '.') 56 | dp[i][j] = dp[i][j] | dp[i-1][j]; 57 | } 58 | } 59 | } 60 | return dp[sLen][pLen]; 61 | } 62 | } -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Remove Duplicates from Sorted Array 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ 7 | Notes: 8 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 9 | Do not allocate extra space for another array, you must do this in place with constant memory. 10 | For example, 11 | Given input array A = [1,1,2], 12 | Your function should return length = 2, and A is now [1,2]. 13 | 14 | Solution: Update 7/16/2013: Let j start from 0 for better understanding. 15 | */ 16 | public class Solution { 17 | public int removeDuplicates(int[] A) { 18 | int N = A.length; 19 | int idx = 0; 20 | for (int i = 0; i < N; ++i) { 21 | if (i == 0 || A[i] != A[i - 1]) { 22 | A[idx++] = A[i]; 23 | } 24 | } 25 | return idx; 26 | } 27 | } -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedArrayII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Annie Kim, anniekim.pku@gmail.com 3 | Date: Dec 12, 2014 [Two pointers ('last' and 'lastlast').] 4 | Problem: Remove Duplicates from Sorted Array II 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ 7 | Notes: 8 | Follow up for "Remove Duplicates": 9 | What if duplicates are allowed at most twice? 10 | For example, 11 | Given sorted array A = [1,1,1,2,2,3], 12 | Your function should return length = 5, and A is now [1,1,2,2,3]. 13 | 14 | Solution: ... 15 | */ 16 | public class Solution { 17 | public int removeDuplicates(int[] A) { 18 | int N = A.length; 19 | if (N <= 2) return N; 20 | int idx = 2; 21 | for (int i = 2; i < N; ++i) { 22 | if (A[i] != A[idx-2]) 23 | A[idx++] = A[i]; 24 | } 25 | return idx; 26 | } 27 | } -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Remove Duplicates from Sorted List 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/ 7 | 8 | Notes: 9 | Given a sorted linked list, delete all duplicates such that each element appear only once. 10 | For example, 11 | Given 1->1->2, return 1->2. 12 | Given 1->1->2->3->3, return 1->2->3. 13 | 14 | Solution: 1. Delete duplicates directly. 15 | 2. Copy value first (like Remove Duplicates from Array) and then delete the remaining elements. 16 | */ 17 | /** 18 | * Definition for singly-linked list. 19 | * public class ListNode { 20 | * int val; 21 | * ListNode next; 22 | * ListNode(int x) { 23 | * val = x; 24 | * next = null; 25 | * } 26 | * } 27 | */ 28 | public class Solution { 29 | public ListNode deleteDuplicates_1(ListNode head) { 30 | if(head == null || head.next == null) return head; 31 | ListNode pre = head, cur = head.next; 32 | while(cur != null) { 33 | if(pre.val == cur.val) { 34 | pre.next = cur.next; 35 | } else { 36 | pre = pre.next; 37 | } 38 | cur = cur.next; 39 | } 40 | return head; 41 | } 42 | public ListNode deleteDuplicates(ListNode head) { 43 | if(head == null || head.next == null) return head; 44 | ListNode pre = head, cur = head.next; 45 | while(cur != null) { 46 | if (pre.val != cur.val) { 47 | pre.next.val = cur.val; 48 | pre = pre.next; 49 | } 50 | cur = cur.next; 51 | } 52 | pre.next = null; 53 | return head; 54 | } 55 | } -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedListII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Remove Duplicates from Sorted List II 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 7 | Notes: 8 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 9 | For example, 10 | Given 1->2->3->3->4->4->5, return 1->2->5. 11 | Given 1->1->1->2->3, return 2->3. 12 | 13 | Solution: 1. iterative 2. recursive 14 | */ 15 | /** 16 | * Definition for singly-linked list. 17 | * public class ListNode { 18 | * int val; 19 | * ListNode next; 20 | * ListNode(int x) { 21 | * val = x; 22 | * next = null; 23 | * } 24 | * } 25 | */ 26 | public class Solution { 27 | public ListNode deleteDuplicates_1(ListNode head) { 28 | ListNode dummy = new ListNode(-1); 29 | ListNode cur = dummy; 30 | while (head != null) { 31 | if (head.next != null && head.val == head.next.val) { 32 | while (head.next != null && head.val == head.next.val) 33 | head = head.next; 34 | } else { 35 | cur.next = head; 36 | cur = cur.next; 37 | } 38 | head = head.next; 39 | } 40 | cur.next = null; 41 | return dummy.next; 42 | } 43 | public ListNode deleteDuplicates(ListNode head) { 44 | if (head == null) return null; 45 | if (head.next == null || head.val != head.next.val){ 46 | head.next = deleteDuplicates(head.next); 47 | return head; 48 | } 49 | while (head.next != null && head.val == head.next.val) 50 | head = head.next; 51 | return deleteDuplicates(head.next); 52 | } 53 | } -------------------------------------------------------------------------------- /RemoveElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Remove Element 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/remove-element/ 7 | Notes: 8 | Given an array and a value, remove all instances of that value in place and return the new length. 9 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 10 | 11 | Solution: Refactor: Update solution. Use two pointers. 12 | */ 13 | 14 | public class Solution { 15 | public int removeElement(int[] A, int elem) { 16 | int N = A.length; 17 | int idx = 0; 18 | for (int i = 0; i < N; ++i) { 19 | if (A[i] != elem) { 20 | A[idx++] = A[i]; 21 | } 22 | } 23 | return idx; 24 | } 25 | } -------------------------------------------------------------------------------- /RemoveNthNodeFromEndofList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 12, 2014 4 | Problem: Remove Nth Node From End of List 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ 7 | Notes: 8 | Given a linked list, remove the nth node from the end of list and return its head. 9 | For example, 10 | Given linked list: 1->2->3->4->5, and n = 2. 11 | After removing the second node from the end, the linked list becomes 1->2->3->5. 12 | Note: 13 | Given n will always be valid. 14 | Try to do this in one pass. 15 | 16 | Solution: head---back------front------>NULL 17 | | | 18 | ---> n <---- 19 | */ 20 | 21 | /** 22 | * Definition for singly-linked list. 23 | * public class ListNode { 24 | * int val; 25 | * ListNode next; 26 | * ListNode(int x) { 27 | * val = x; 28 | * next = null; 29 | * } 30 | * } 31 | */ 32 | public class Solution { 33 | public ListNode removeNthFromEnd(ListNode head, int n) { 34 | ListNode dummy = new ListNode(0); 35 | ListNode back = dummy, front = dummy; 36 | dummy.next = head; 37 | while(n-- != 0) front = front.next; 38 | while(front.next != null) { 39 | front = front.next; 40 | back = back.next; 41 | } 42 | back.next = back.next.next; 43 | return dummy.next; 44 | } 45 | } -------------------------------------------------------------------------------- /RepeatedDNASequences.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Feb 3, 2015 4 | Problem: Repeated DNA Sequences 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/repeated-dna-sequences/ 7 | Notes: 8 | All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 9 | 10 | Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 11 | 12 | For example, 13 | 14 | Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", 15 | 16 | Return: 17 | ["AAAAACCCCC", "CCCCCAAAAA"]. 18 | 19 | Solution: ... 20 | */ 21 | 22 | public class Solution { 23 | public List findRepeatedDnaSequences(String s) { 24 | HashMap map = new HashMap(); 25 | HashMap mole = new HashMap(); 26 | mole.put('A',0); mole.put('C',1); mole.put('G',2); mole.put('T',3); 27 | List res = new ArrayList(); 28 | if (s.length() < 11) return res; 29 | int x = 0, i = 0, mask = (1<<20) - 1; 30 | for (; i < 10; ++i) { 31 | x = (x << 2) | mole.get(s.charAt(i)); 32 | } 33 | map.put(x, 1); 34 | for (; i < s.length(); ++i) { 35 | x = (x<<2)|mole.get(s.charAt(i)); 36 | x = x & mask; 37 | if (map.containsKey(x)) { 38 | if (map.get(x) == 1) { 39 | res.add(convert2Str(x)); 40 | map.put(x,-1); 41 | } 42 | } else { 43 | map.put(x,1); 44 | } 45 | } 46 | return res; 47 | } 48 | public String convert2Str(int x) { 49 | String res = new String(); 50 | for (int i = 0; i < 10; ++i) { 51 | int k = x & 3; 52 | if (k == 0) res = 'A' + res; 53 | if (k == 1) res = 'C' + res; 54 | if (k == 2) res = 'G' + res; 55 | if (k == 3) res = 'T' + res; 56 | x = x >> 2; 57 | } 58 | return res; 59 | } 60 | } -------------------------------------------------------------------------------- /RestoreIPAddresses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 16, 2015 4 | Problem: Restore IP Addresses 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/restore-ip-addresses/ 7 | Notes: 8 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 9 | For example: 10 | Given "25525511135", 11 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 12 | 13 | Solution: DFS. 14 | */ 15 | public class Solution { 16 | public List restoreIpAddresses(String s) { 17 | List res = new ArrayList(); 18 | dfs(s, new String(), 0, 0, res); 19 | return res; 20 | } 21 | public void dfs(String s, String ip, int start, int step, List res) { 22 | if (step == 4 && start == s.length()) { 23 | res.add(ip); 24 | } 25 | if (step == 4) return; 26 | if(s.length()-start>(4-step)*3) return ; 27 | if(s.length()-start<4-step) return ; 28 | if (ip.length() != 0) ip+="."; 29 | int num = 0; 30 | for (int i = start; i < start + 3 && i < s.length(); ++i) { 31 | num = num*10 + s.charAt(i) - '0'; 32 | if (num > 255) break; 33 | ip += s.charAt(i); 34 | dfs(s, ip, i + 1, step + 1, res); 35 | if (num == 0) break; 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /ReverseInteger.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 14, 2014 4 | Problem: Reverse Integer 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/reverse-integer/ 7 | Notes: 8 | Reverse digits of an integer. 9 | Example1: x = 123, return 321 10 | Example2: x = -123, return -321 11 | 12 | Have you thought about this? 13 | Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 14 | If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 15 | Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? 16 | Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter). 17 | 18 | Solution: Use % and / iteratively. 19 | */ 20 | 21 | public class Solution { 22 | public int reverse(int x) { 23 | long res = 0; 24 | while (x != 0) { 25 | res = res * 10 + Long.valueOf( x % 10 ); 26 | x = x / 10; 27 | } 28 | if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) return 0; 29 | return (int) res; 30 | } 31 | } -------------------------------------------------------------------------------- /ReverseLinkedListII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 2, 2015 4 | Problem: Reverse Linked List II 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/reverse-linked-list-ii/ 7 | Notes: 8 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 9 | For example: 10 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 11 | return 1->4->3->2->5->NULL. 12 | Note: 13 | Given m, n satisfy the following condition: 14 | 1 <= m <= n <= length of list. 15 | 16 | Solution: in-place & one-pass. 17 | */ 18 | 19 | /** 20 | * Definition for singly-linked list. 21 | * public class ListNode { 22 | * int val; 23 | * ListNode next; 24 | * ListNode(int x) { 25 | * val = x; 26 | * next = null; 27 | * } 28 | * } 29 | */ 30 | public class Solution { 31 | public ListNode reverseBetween(ListNode head, int m, int n) { 32 | ListNode dummy = new ListNode(-1); 33 | dummy.next = head; 34 | ListNode first = dummy; 35 | for (int i = 0; i < m - 1; ++i) first = first.next; 36 | ListNode cur = first.next; 37 | for (int i = 0; i < n - m; ++i) { 38 | ListNode move = cur.next; 39 | cur.next = move.next; 40 | move.next = first.next; 41 | first.next = move; 42 | } 43 | return dummy.next; 44 | } 45 | } -------------------------------------------------------------------------------- /ReverseNodesinkGroup.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 18, 2015 4 | Problem: Reverse Nodes in k-Group 5 | Difficulty: Hard 6 | Source: https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ 7 | Notes: 8 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 9 | If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 10 | You may not alter the values in the nodes, only nodes itself may be changed. 11 | Only constant memory is allowed. 12 | For example, 13 | Given this linked list: 1->2->3->4->5 14 | For k = 2, you should return: 2->1->4->3->5 15 | For k = 3, you should return: 3->2->1->4->5 16 | 17 | Solution: ... 18 | */ 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * public class ListNode { 23 | * int val; 24 | * ListNode next; 25 | * ListNode(int x) { 26 | * val = x; 27 | * next = null; 28 | * } 29 | * } 30 | */ 31 | public class Solution { 32 | public ListNode reverseKGroup(ListNode head, int k) { 33 | if (k <= 1) return head; 34 | int T = GetLength(head) / k; 35 | ListNode dummy = new ListNode(0), cur = head, ins = dummy; 36 | dummy.next = head; 37 | while ((T--) != 0) { 38 | for (int i = 0; i < k - 1; ++i) { 39 | ListNode move = cur.next; 40 | cur.next = move.next; 41 | move.next = ins.next; 42 | ins.next = move; 43 | } 44 | ins = cur; 45 | cur = cur.next; 46 | } 47 | return dummy.next; 48 | } 49 | public int GetLength(ListNode head) { 50 | int length = 0; 51 | while (head != null) { 52 | head = head.next; 53 | length++; 54 | } 55 | return length; 56 | } 57 | } -------------------------------------------------------------------------------- /ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 13, 2014 4 | Problem: Reverse Words in a String 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/reverse-words-in-a-string/ 7 | Notes: 8 | Given an input string, reverse the string word by word. 9 | 10 | For example, 11 | Given s = "the sky is blue", 12 | return "blue is sky the". 13 | 14 | Solution: 1. Reverse the raw string and reverse each word. 15 | 2. Cannot do it In Place by Java. oops~.~ 16 | */ 17 | 18 | public class Solution { 19 | public String reverseWords(String s) { 20 | StringBuffer sb = new StringBuffer(); 21 | for (int i = s.length() - 1; i >= 0;) { 22 | while (i >= 0 && s.charAt(i) == ' ') --i; 23 | StringBuffer temp = new StringBuffer(); 24 | while (i >= 0 && s.charAt(i) != ' ') { 25 | temp.append(s.charAt(i--)); 26 | } 27 | temp.reverse(); 28 | if (sb.length() > 0 && temp.length() > 0) sb.append(" "); 29 | sb.append(temp); 30 | } 31 | return sb.toString(); 32 | } 33 | } -------------------------------------------------------------------------------- /RomantoInteger.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Roman to Integer 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/roman-to-integer/ 7 | Notes: 8 | Given a roman numeral, convert it to an integer. 9 | Input is guaranteed to be within the range from 1 to 3999. 10 | 11 | Solution: use or (clean) 12 | */ 13 | public class Solution { 14 | public int romanToInt(String s) { 15 | HashMap map=new HashMap(); 16 | map.put('M', 1000); 17 | map.put('D', 500); 18 | map.put('C', 100); 19 | map.put('L', 50); 20 | map.put('X', 10); 21 | map.put('V', 5); 22 | map.put('I',1); 23 | int res = 0; 24 | for (int i = 0; i < s.length(); ++i) { 25 | if (i < s.length() - 1 && map.get(s.charAt(i)) < map.get(s.charAt(i+1))) 26 | res -= map.get(s.charAt(i)); 27 | else res += map.get(s.charAt(i)); 28 | } 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /RotateImage.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Rotate Image 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/rotate-image/ 7 | Notes: 8 | You are given an n x n 2D matrix representing an image. 9 | Rotate the image by 90 degrees (clockwise). 10 | Follow up: 11 | Could you do this in-place? 12 | 13 | Solution: 1. 123 -> 147 -> 741 (preferable) 14 | 456 258 852 15 | 789 369 963 16 | 2. Rotate one-fourth of the image clockwise. 17 | */ 18 | public class Solution { 19 | public void rotate_1(int[][] matrix) { 20 | int n = matrix.length; 21 | if (n <= 1) return; 22 | for(int i=0;i2->3->4->5->NULL and k = 2, 12 | return 4->5->1->2->3->NULL. 13 | 14 | Solution: Notice that k can be larger than the list size (k % list_size). 15 | This solution traverses the list twice at most. 16 | */ 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * struct ListNode { 21 | * int val; 22 | * ListNode *next; 23 | * ListNode(int x) : val(x), next(NULL) {} 24 | * }; 25 | */ 26 | /** 27 | * Definition for singly-linked list. 28 | * public class ListNode { 29 | * int val; 30 | * ListNode next; 31 | * ListNode(int x) { 32 | * val = x; 33 | * next = null; 34 | * } 35 | * } 36 | */ 37 | public class Solution { 38 | public ListNode rotateRight(ListNode head, int k) { 39 | if (head == null) return head; 40 | int n = 1; 41 | ListNode tail = head, cur = head; 42 | while (tail.next != null) { 43 | tail = tail.next; 44 | ++n; 45 | } 46 | k = k % n; 47 | if (k == 0) return head; 48 | for (int i = 0; i < n - k - 1; ++i) 49 | cur = cur.next; 50 | ListNode newHead = cur.next; 51 | tail.next = head; 52 | cur.next = null; 53 | return newHead; 54 | } 55 | } -------------------------------------------------------------------------------- /SameTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Same Tree 5 | Difficulty: easy 6 | Source: http://leetcode.com/onlinejudge#question_100 7 | Notes: 8 | Given two binary trees, write a function to check if they are equal or not. 9 | Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 10 | 11 | Solution: recursion. 12 | */ 13 | /** 14 | * Definition for binary tree 15 | * public class TreeNode { 16 | * int val; 17 | * TreeNode left; 18 | * TreeNode right; 19 | * TreeNode(int x) { val = x; } 20 | * } 21 | */ 22 | public class Solution { 23 | public boolean isSameTree(TreeNode p, TreeNode q) { 24 | if (p == null && q == null) return true; 25 | if ((p != null && q == null) || (p == null && q != null)) return false; 26 | if (p.val != q.val) return false; 27 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 28 | } 29 | } -------------------------------------------------------------------------------- /SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Search Insert Position 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_35 7 | Notes: 8 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 9 | You may assume no duplicates in the array. 10 | Here are few examples. 11 | [1,3,5,6], 5 -> 2 12 | [1,3,5,6], 2 -> 1 13 | [1,3,5,6], 7 -> 4 14 | [1,3,5,6], 0 -> 0 15 | 16 | Solution: Binary search. 17 | */ 18 | 19 | public class Solution { 20 | public int searchInsert(int[] A, int target) { 21 | int i = 0, j = A.length - 1; 22 | while (i <= j) { 23 | int mid = (i + j) / 2; 24 | if (A[mid] == target) return mid; 25 | if (A[mid] < target) i = mid + 1; 26 | else j = mid - 1; 27 | } 28 | return i; 29 | } 30 | } -------------------------------------------------------------------------------- /Searcha2DMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 16, 2015 4 | Problem: Search a 2D Matrix 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/search-a-2d-matrix/ 7 | Notes: 8 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 9 | 10 | Integers in each row are sorted from left to right. 11 | The first integer of each row is greater than the last integer of the previous row. 12 | For example, 13 | 14 | Consider the following matrix: 15 | 16 | [ 17 | [1, 3, 5, 7], 18 | [10, 11, 16, 20], 19 | [23, 30, 34, 50] 20 | ] 21 | Given target = 3, return true. 22 | 23 | Solution: Binary-search. 24 | */ 25 | public class Solution { 26 | public boolean searchMatrix(int[][] matrix, int target) { 27 | if (matrix.length == 0 || matrix[0].length == 0) return false; 28 | int N = matrix.length,M = matrix[0].length; 29 | int left = 0, right = M * N - 1; 30 | while (left <= right) { 31 | int mid = left + (right - left) / 2; 32 | int row = mid / M, col = mid % M; 33 | if (matrix[row][col] == target) return true; 34 | if (matrix[row][col] < target) left = mid + 1; 35 | else right = mid - 1; 36 | } 37 | return false; 38 | } 39 | } -------------------------------------------------------------------------------- /SearchforaRange.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Search for a Range 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/search-for-a-range/ 7 | Notes: 8 | Given a sorted array of integers, find the starting and ending position of a given target value. 9 | 10 | Your algorithm's runtime complexity must be in the order of O(log n). 11 | 12 | If the target is not found in the array, return [-1, -1]. 13 | 14 | For example, 15 | Given [5, 7, 7, 8, 8, 10] and target value 8, 16 | return [3, 4]. 17 | 18 | Solution: It takes O(lgN) to find both the lower-bound and upper-bound. 19 | */ 20 | public class Solution { 21 | public int[] searchRange(int[] A, int target) { 22 | int[] res = new int[]{-1,-1}; 23 | int lower = getLowerBound(A, target); 24 | int upper = getUpperBound(A, target); 25 | if (lower <= upper) { 26 | res[0] = lower; 27 | res[1] = upper; 28 | } 29 | return res; 30 | } 31 | public int getLowerBound(int[] A, int target) { 32 | int l = 0, r = A.length - 1; 33 | while (l <= r) { 34 | int mid = (l+r) / 2; 35 | if (A[mid] < target) l = mid + 1; 36 | else r = mid - 1; 37 | } 38 | return l; 39 | } 40 | public int getUpperBound(int[] A, int target) { 41 | int l = 0, r = A.length - 1; 42 | while (l <= r) { 43 | int mid = (l+r) / 2; 44 | if (A[mid] <= target) l = mid + 1; 45 | else r = mid - 1; 46 | } 47 | return r; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /SearchinRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Search in Rotated Sorted Array 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/search-in-rotated-sorted-array/ 7 | Notes: 8 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 9 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | You are given a target value to search. If found in the array return its index, otherwise return -1. 11 | You may assume no duplicate exists in the array. 12 | 13 | Solution: Binary search. O(lgn) eg. [4 5 6] -7- 8 1 2, 5 6 0 -1- [2 3 4] 14 | */ 15 | public class Solution { 16 | public int search(int[] A, int target) { 17 | int i = 0, j = A.length - 1; 18 | while (i <= j) { 19 | int mid = (i + j) / 2; 20 | if (A[mid] == target) 21 | return mid; 22 | if (A[i] <= A[mid]) { 23 | if (A[i] <= target && target < A[mid]) 24 | j = mid - 1; 25 | else 26 | i = mid + 1; 27 | } else { 28 | if (A[mid] < target && target <= A[j]) 29 | i = mid + 1; 30 | else 31 | j = mid - 1; 32 | } 33 | } 34 | return -1; 35 | } 36 | } -------------------------------------------------------------------------------- /SearchinRotatedSortedArrayII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Nov 18, 2014 4 | Problem: Search in Rotated Sorted Array II 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/ 7 | Notes: 8 | Suppose a sorted array is rotated at some pivot unknown to you beforehand. 9 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 10 | What if duplicates are allowed? 11 | Would this affect the run-time complexity? How and why? 12 | Write a function to determine if a given target is in the array. 13 | 14 | Solution: Sequence search. O(n) 15 | Since there are duplicates, it's hard to decide which branch to go if binary-search is deployed. 16 | */ 17 | public class Solution { 18 | public boolean search_1(int[] A, int target) { 19 | for (int i = 0; i < A.length; ++i) { 20 | if (A[i] == target) return true; 21 | } 22 | return false; 23 | } 24 | public boolean search(int[] A, int target) { 25 | int left = 0, right = A.length - 1; 26 | while (left <= right) { 27 | int mid = (left + right) /2; 28 | if (A[mid] == target) return true; 29 | if (A[left] < A[mid]) { 30 | if (A[left] <= target && target < A[mid]) right = mid - 1; 31 | else left = mid + 1; 32 | } else if (A[left] > A[mid]) { 33 | if (A[mid] < target && target <= A[right]) left = mid + 1; 34 | else right = mid - 1; 35 | } else { 36 | if (A[left] == A[right]) { 37 | ++left; --right; 38 | } else left = mid + 1; 39 | } 40 | } 41 | return false; 42 | } 43 | } -------------------------------------------------------------------------------- /SetMatrixZeroes.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Set Matrix Zeroes 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/set-matrix-zeroes/ 7 | Notes: 8 | Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 9 | Follow up: 10 | Did you use extra space? 11 | A straight forward solution using O(mn) space is probably a bad idea. 12 | A simple improvement uses O(m + n) space, but still not the best solution. 13 | Could you devise a constant space solution? 14 | 15 | Solution: Use first row and column as auxiliary spaces instead of newly allocating ones. 16 | */ 17 | public class Solution { 18 | public void setZeroes(int[][] matrix) { 19 | int m = matrix.length; 20 | if(m <= 0) return; 21 | int n = matrix[0].length; 22 | 23 | boolean row_has_zero = false; 24 | boolean col_has_zero = false; 25 | 26 | for(int j=0; j "/home" 12 | path = "/a/./b/../../c/", => "/c" 13 | 14 | Corner Cases: 15 | Did you consider the case where path = "/../"? 16 | In this case, you should return "/". 17 | Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 18 | In this case, you should ignore redundant slashes and return "/home/foo". 19 | 20 | Solution: Add an additional '/' at the end of 'path' for simply detecting the end. 21 | */ 22 | public class Solution { 23 | public String simplifyPath(String path) { 24 | if(path.length()==0) return "/"; 25 | if(path.charAt(0)!='/') return "/"; 26 | ArrayList dirs = new ArrayList(); 27 | String[] str = path.split("/"); 28 | for (int i = 0; i < str.length; ++i) { 29 | if ((i == 0 || i == str.length - 1) && str[i].compareTo("") == 0) continue; 30 | if (str[i].compareTo("..") == 0) { 31 | if (dirs.isEmpty() == false) { 32 | dirs.remove(dirs.size() - 1); 33 | } 34 | } else if ((str[i].compareTo(".") != 0) && (str[i].compareTo("") != 0)) { 35 | dirs.add(str[i]); 36 | } 37 | } 38 | if (dirs.isEmpty() == true) return "/"; 39 | StringBuilder res = new StringBuilder(); 40 | for (int i = 0; i < dirs.size(); ++i) { 41 | res.append("/"); 42 | res.append(dirs.get(i)); 43 | } 44 | return res.toString(); 45 | } 46 | } -------------------------------------------------------------------------------- /SingleNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 3, 2015 4 | Problem: Single Number 5 | Difficulty: Easy 6 | Source: http://oj.leetcode.com/problems/single-number/ 7 | Notes: 8 | Given an array of integers, every element appears twice except for one. 9 | Find that single one. 10 | Your algorithm should have a linear runtime complexity. 11 | Could you implement it without using extra memory? 12 | 13 | Solution: XOR. 14 | */ 15 | public class Solution { 16 | public int singleNumber(int[] A) { 17 | int res = 0; 18 | for (int i : A) { 19 | res = res^i; 20 | } 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /SingleNumberII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 3, 2015 4 | Problem: Single Number II 5 | Difficulty: Easy 6 | Source: http://oj.leetcode.com/problems/single-number-ii/ 7 | Notes: 8 | Given an array of integers, every element appears three times except for one. 9 | Find that single one. 10 | Your algorithm should have a linear runtime complexity. Could you implement it 11 | without using extra memory? 12 | 13 | Solution: 1. Count the number of each bit. 14 | 2. We can improve this based on the previous solution using three bitmask variables. 15 | 3. An excellent answer by @ranmocy in LeetCode Discuss: 16 | https://oj.leetcode.com/discuss/857/constant-space-solution?show=2542#a2542 17 | */ 18 | public class Solution { 19 | public int singleNumber_1(int[] A) { 20 | int res = 0; 21 | for (int i = 0; i < 32; ++i) { 22 | int one = 0; 23 | for (int num : A) { 24 | if (((num >> i) & 1) == 1) ++one; 25 | } 26 | res = res | ((one % 3)<= 1; --i) { 48 | x[i] = (x[i-1] & num) | (x[i] & ~num); 49 | } 50 | x[0] = (t & num) | (x[0] & ~num); 51 | } 52 | return x[k]; 53 | } 54 | } -------------------------------------------------------------------------------- /SortColors.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 24, 2013 4 | Problem: Sort Colors 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/sort-colors/ 7 | Notes: 8 | Given an array with n objects colored red, white or blue, sort them so that objects of the same color 9 | are adjacent, with the colors in the order red, white and blue. 10 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 11 | Note: 12 | You are not suppose to use the library's sort function for this problem. 13 | Follow up: 14 | A rather straight forward solution is a two-pass algorithm using counting sort. 15 | First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with 16 | total number of 0's, then 1's and followed by 2's. 17 | Could you come up with an one-pass algorithm using only constant space? 18 | 19 | Solution: 0 0 0 1 1 1 1 ...... 2 2 2 2 20 | | | | 21 | zero i two 22 | -> -> <- 23 | */ 24 | public class Solution { 25 | public void sortColors(int[] A) { 26 | int n = A.length; 27 | if (n <= 1) return; 28 | for (int i = 0, left = 0, right = n - 1; i <= right;) { 29 | if (A[i] == 0) { 30 | A[i++] = A[left]; 31 | A[left++] = 0; 32 | } else if (A[i] == 2) { 33 | A[i] = A[right]; 34 | A[right--] = 2; 35 | } else i++; 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /SortColorsII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 24, 2013 4 | Problem: Sort Colors 5 | Difficulty: Medium 6 | Source: http://lintcode.com/zh-cn/problem/sort-colors-ii/ 7 | Notes: 8 | Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k. 9 | 10 | Note 11 | You are not suppose to use the library's sort function for this problem. 12 | 13 | Example 14 | GIven colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4]. 15 | 16 | Challenge 17 | A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory. 18 | 19 | Can you do it without using extra memory? 20 | 21 | Solution: Use the first k buckets to store the count. (count sort, two pass). 22 | */ 23 | class Solution { 24 | /** 25 | * @param colors: A list of integer 26 | * @param k: An integer 27 | * @return: nothing 28 | */ 29 | public void sortColors2(int[] A, int k) { 30 | // write your code here 31 | int n = A.length; 32 | if (n <= 1) return; 33 | for (int i = 0; i < n; ++i) { 34 | if(A[i] > 0) { 35 | int c = A[i]; 36 | A[i] = 0; 37 | while(true) { 38 | if (A[c-1] <= 0) { 39 | --A[c-1]; 40 | break; 41 | } else { 42 | int col = A[c-1]; 43 | A[c-1] = -1; 44 | c = col; 45 | } 46 | } 47 | } 48 | } 49 | int idx = n; 50 | for (int i = k; i > 0; --i) { 51 | for (int j = 0; j > A[i-1]; --j) A[--idx] = i; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /SortList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 2, 2015 4 | Problem: Sort List 5 | Difficulty: Medium 6 | Source: http://oj.leetcode.com/problems/sort-list/ 7 | Notes: 8 | Sort a linked list in O(nlogn) time using constant space complexity. 9 | 10 | Solution: merge sort. 11 | */ 12 | /** 13 | * Definition for singly-linked list. 14 | * class ListNode { 15 | * int val; 16 | * ListNode next; 17 | * ListNode(int x) { 18 | * val = x; 19 | * next = null; 20 | * } 21 | * } 22 | */ 23 | public class Solution { 24 | public ListNode sortList(ListNode head) { 25 | if (head == null || head.next == null) return head; 26 | ListNode slow = head, fast = head; 27 | while (fast.next != null && fast.next.next != null) { 28 | fast = fast.next.next; 29 | slow = slow.next; 30 | } 31 | fast = slow.next; 32 | slow.next = null; 33 | ListNode l1 = sortList(head); 34 | ListNode l2 = sortList(fast); 35 | return mergeTwoLists(l1, l2); 36 | } 37 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 38 | ListNode head = new ListNode(0); 39 | ListNode cur = head; 40 | while (l1 != null && l2 != null) { 41 | if (l1.val < l2.val) { 42 | cur.next = l1; 43 | l1 = l1.next; 44 | } else { 45 | cur.next = l2; 46 | l2 = l2.next; 47 | } 48 | cur = cur.next; 49 | } 50 | if (l1 != null) cur.next = l1; 51 | if (l2 != null) cur.next = l2; 52 | return head.next; 53 | } 54 | } -------------------------------------------------------------------------------- /SpiralMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Spiral Matrix 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/spiral-matrix/ 7 | Notes: 8 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 9 | For example, 10 | Given the following matrix: 11 | [ 12 | [ 1, 2, 3 ], 13 | [ 4, 5, 6 ], 14 | [ 7, 8, 9 ] 15 | ] 16 | You should return [1,2,3,6,9,8,7,4,5]. 17 | 18 | Solution: ... 19 | */ 20 | public class Solution { 21 | public List spiralOrder(int[][] matrix) { 22 | ArrayList res = new ArrayList(); 23 | if (matrix.length == 0 || matrix[0].length == 0) return res; 24 | int n = matrix.length, m = matrix[0].length, row = 0, col = -1; 25 | while (true) { 26 | for (int i = 0; i < m; ++i) res.add(matrix[row][++col]); 27 | if (--n == 0) break; 28 | for (int i = 0; i < n; ++i) res.add(matrix[++row][col]); 29 | if (--m == 0) break; 30 | for (int i = 0; i < m; ++i) res.add(matrix[row][--col]); 31 | if (--n == 0) break; 32 | for (int i = 0; i < n; ++i) res.add(matrix[--row][col]); 33 | if (--m == 0) break; 34 | } 35 | return res; 36 | } 37 | } -------------------------------------------------------------------------------- /SpiralMatrixII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Spiral Matrix II 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/spiral-matrix-ii/ 7 | Notes: 8 | Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 9 | For example, 10 | Given n = 3, 11 | You should return the following matrix: 12 | [ 13 | [ 1, 2, 3 ], 14 | [ 8, 9, 4 ], 15 | [ 7, 6, 5 ] 16 | ] 17 | 18 | Solution: ... 19 | */ 20 | public class Solution { 21 | public int[][] generateMatrix(int n) { 22 | if (n <= 0) return new int[0][0]; 23 | int[][] res = new int[n][n]; 24 | int m = n, row = 0, col = -1, num = 0; 25 | while (true) { 26 | for (int i = 0; i < m; ++i) res[row][++col] = ++num; 27 | if (--n == 0) break; 28 | for (int i = 0; i < n; ++i) res[++row][col] = ++num; 29 | if (--m == 0) break; 30 | for (int i = 0; i < m; ++i) res[row][--col] = ++num; 31 | if (--n == 0) break; 32 | for (int i = 0; i < n; ++i) res[--row][col] = ++num; 33 | if (--m == 0) break; 34 | } 35 | return res; 36 | } 37 | } -------------------------------------------------------------------------------- /Sqrt(x).java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Apr 18, 2013 4 | Problem: Sqrt(x) 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_69 7 | Notes: 8 | Implement int sqrt(int x). 9 | Compute and return the square root of x. 10 | 11 | Solution: 1. Binary search in range [0, x / 2 + 1]. 12 | 2. Newton iteration method. x(i+1) = (x(i) + n/x(i)) / 2. 13 | See my blog (http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html) for more explanation (in Chinese). 14 | */ 15 | public class Solution { 16 | public int sqrt(int x) { 17 | int left = 1, right = x/2; 18 | if(x<2) return x; 19 | while (left <= right) { 20 | int mid = (left + right)/2; 21 | if (x/mid == mid) return mid; 22 | if (x/mid > mid) left = mid + 1; 23 | else right = mid - 1; 24 | } 25 | return right; 26 | } 27 | } -------------------------------------------------------------------------------- /Subsets.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Nov 18, 2014 4 | Problem: Subsets 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/subsets/ 7 | Notes: 8 | Given a set of distinct integers, S, return all possible subsets. 9 | Note: 10 | Elements in a subset must be in non-descending order. 11 | The solution set must not contain duplicate subsets. 12 | For example, 13 | If S = [1,2,3], a solution is: 14 | [ 15 | [3], 16 | [1], 17 | [2], 18 | [1,2,3], 19 | [1,3], 20 | [2,3], 21 | [1,2], 22 | [] 23 | ] 24 | 25 | Solution: 1. Updated Iterative solution. 26 | 2. Updated Recursive solution. 27 | */ 28 | public class Solution { 29 | public List> subsets(int[] S) { 30 | return subsets_2(S); 31 | } 32 | public List> subsets_1(int[] S) { 33 | Arrays.sort(S); 34 | List> res = new ArrayList>(); 35 | List path = new ArrayList(); 36 | subsetsRe(S, 0, path, res); 37 | return res; 38 | } 39 | void subsetsRe(int[] S, int start, List path, List> res) { 40 | List sub = new ArrayList(path); 41 | res.add(sub); 42 | for (int i = start; i < S.length; ++i) { 43 | path.add(S[i]); 44 | subsetsRe(S, i + 1, path, res); 45 | path.remove(path.size() - 1); 46 | } 47 | } 48 | public List> subsets_2(int[] S) { 49 | Arrays.sort(S); 50 | List> res = new ArrayList>(); 51 | res.add(new ArrayList()); 52 | for (int i = 0; i < S.length; ++i) { 53 | int sz = res.size(); 54 | for (int j = 0; j < sz; ++j) { 55 | List path = new ArrayList(res.get(j)); 56 | path.add(S[i]); 57 | res.add(path); 58 | } 59 | } 60 | return res; 61 | } 62 | } -------------------------------------------------------------------------------- /SubsetsII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Nov 18, 2014 4 | Problem: Subsets II 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/subsets-ii/ 7 | Notes: 8 | Given a collection of integers that might contain duplicates, S, return all possible subsets. 9 | Note: 10 | Elements in a subset must be in non-descending order. 11 | The solution set must not contain duplicate subsets. 12 | For example, 13 | If S = [1,2,2], a solution is: 14 | [ 15 | [2], 16 | [1], 17 | [1,2,2], 18 | [2,2], 19 | [1,2], 20 | [] 21 | ] 22 | 23 | Solution: ..Similar to Subset I. 24 | */ 25 | public class Solution { 26 | public List> subsetsWithDup(int[] S) { 27 | return subsetsWithDup_2(S); 28 | } 29 | public List> subsetsWithDup_1(int[] S) { 30 | Arrays.sort(S); 31 | List> res = new ArrayList>(); 32 | List path = new ArrayList(); 33 | subsetsRe(S, 0, path, res); 34 | return res; 35 | } 36 | void subsetsRe(int[] S, int start, List path, List> res) { 37 | List sub = new ArrayList(path); 38 | res.add(sub); 39 | for (int i = start; i < S.length; ++i) { 40 | if (i != start && S[i] == S[i-1]) continue; 41 | path.add(S[i]); 42 | subsetsRe(S, i + 1, path, res); 43 | path.remove(path.size() - 1); 44 | } 45 | } 46 | public List> subsetsWithDup_2(int[] S) { 47 | Arrays.sort(S); 48 | List> res = new ArrayList>(); 49 | res.add(new ArrayList()); 50 | int presz = 0; 51 | for (int i = 0; i < S.length; ++i) { 52 | int sz = res.size(); 53 | for (int j = 0; j < sz; ++j) { 54 | if (i == 0 || S[i] != S[i-1] || j >= presz) { 55 | List path = new ArrayList(res.get(j)); 56 | path.add(S[i]); 57 | res.add(path); 58 | } 59 | } 60 | presz = sz; 61 | } 62 | return res; 63 | } 64 | } -------------------------------------------------------------------------------- /SudokuSolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Sudoku Solver 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/sudoku-solver/ 7 | Notes: 8 | Write a program to solve a Sudoku puzzle by filling the empty cells. 9 | Empty cells are indicated by the character '.'. 10 | You may assume that there will be only one unique solution. 11 | 12 | Solution: back-tracking.. 13 | */ 14 | public class Solution { 15 | public void solveSudoku(char[][] board) { 16 | solve(board); 17 | } 18 | boolean solve(char[][] board){ 19 | for(int i = 0;i<9;i++){ 20 | for(int j=0;j<9;j++){ 21 | if(board[i][j]=='.'){ 22 | for(char ch = '1';ch<='9';ch++){ 23 | board[i][j]=ch; 24 | if(isValidSudoKu(board,i,j)&&solve(board)) return true; 25 | board[i][j]='.'; 26 | } 27 | return false; 28 | } 29 | } 30 | } 31 | return true; 32 | } 33 | boolean isValidSudoKu(char[][] board, int x, int y){ 34 | for(int i = 0; i<9; i++){ 35 | if(i!=y&&board[x][i]==board[x][y]) return false; 36 | } 37 | for(int i=0;i<9;i++){ 38 | if(i!=x&&board[i][y]==board[x][y]) return false; 39 | } 40 | for(int i=3*(x/3);i<3*(x/3)+3;i++){ 41 | for(int j=3*(y/3);j<3*(y/3)+3;j++){ 42 | if(i!=x&&j!=y&&board[i][j]==board[x][y]) return false; 43 | } 44 | } 45 | return true; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /SumRoottoLeafNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Jan 02, 2014 4 | Problem: Sum Root to Leaf Numbers 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ 7 | Notes: 8 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 9 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 10 | Find the total sum of all root-to-leaf numbers. 11 | For example, 12 | 1 13 | / \ 14 | 2 3 15 | The root-to-leaf path 1->2 represents the number 12. 16 | The root-to-leaf path 1->3 represents the number 13. 17 | Return the sum = 12 + 13 = 25. 18 | 19 | Solution: 1. Recursion (add to sum when reaching the leaf). 20 | */ 21 | 22 | 23 | /** 24 | * Definition for binary tree 25 | * public class TreeNode { 26 | * int val; 27 | * TreeNode left; 28 | * TreeNode right; 29 | * TreeNode(int x) { val = x; } 30 | * } 31 | */ 32 | public class Solution { 33 | public int sumNumbers(TreeNode root) { 34 | if (root == null) return 0; 35 | return sumNumbersRe(root,0); 36 | } 37 | public int sumNumbersRe(TreeNode root, int last) { 38 | if (root == null) return 0; 39 | int res = last * 10 + root.val; 40 | if (root.left == null && root.right == null) return res; 41 | if (root.left == null) return sumNumbersRe(root.right, res); 42 | if (root.right == null) return sumNumbersRe(root.left, res); 43 | return sumNumbersRe(root.left, res) + sumNumbersRe(root.right, res); 44 | } 45 | } -------------------------------------------------------------------------------- /SurroundedRegions.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 20, 2015 4 | Problem: Surrounded Regions 5 | Difficulty: Easy 6 | Source: http://leetcode.com/onlinejudge#question_130 7 | Notes: 8 | Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. 9 | A region is captured by flipping all 'O's into 'X's in that surrounded region . 10 | For example, 11 | X X X X 12 | X O O X 13 | X X O X 14 | X O X X 15 | After running your function, the board should be: 16 | X X X X 17 | X X X X 18 | X X X X 19 | X O X X 20 | 21 | Solution: Traverse from the boarder to the inside and mark all the 'O's that are not surrounded by 'X' as 'V' (visited). 22 | 1. BFS (queue). 23 | */ 24 | public class Solution { 25 | public void solve(char[][] board) { 26 | if (board.length == 0 || board[0].length == 0) return; 27 | int M = board.length, N = board[0].length; 28 | for (int i = 0; i < M; ++i) { 29 | for (int j = 0; j < N; ++j) { 30 | if (i == 0 || j == 0 || i == M - 1 || j == N -1) { 31 | bfs(board, i, j); 32 | } 33 | } 34 | } 35 | for (int i = 0; i < M; ++i) 36 | for (int j = 0; j < N; ++j) 37 | board[i][j] = (board[i][j] == 'V') ? 'O' : 'X'; 38 | } 39 | public void bfs(char[][] board, int row, int col) { 40 | if (board[row][col] != 'O') return; 41 | int M = board.length, N = board[0].length; 42 | Queue q = new LinkedList(); 43 | q.offer(row); q.offer(col); 44 | while (q.isEmpty() == false) { 45 | int i = q.poll(); int j = q.poll(); 46 | if (i < 0 || i == M || j < 0 || j == N) continue; 47 | if (board[i][j] != 'O') continue;// important to recheck! 48 | board[i][j] = 'V'; 49 | q.offer(i-1); q.offer(j); 50 | q.offer(i+1); q.offer(j); 51 | q.offer(i); q.offer(j-1); 52 | q.offer(i); q.offer(j+1); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /SwapNodesinPairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Swap Nodes in Pairs 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/swap-nodes-in-pairs/ 7 | Notes: 8 | Given a linked list, swap every two adjacent nodes and return its head. 9 | For example, 10 | Given 1->2->3->4, you should return the list as 2->1->4->3. 11 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 12 | 13 | Solution: 1. Iterative solution with constant space. 14 | 2. Recursive solution with O(n) space (for practice). 15 | */ 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * public class ListNode { 20 | * int val; 21 | * ListNode next; 22 | * ListNode(int x) { 23 | * val = x; 24 | * next = null; 25 | * } 26 | * } 27 | */ 28 | public class Solution { 29 | public ListNode swapPairs_1(ListNode head) { 30 | if (head == null || head.next == null) return head; 31 | ListNode dummy = new ListNode(0); 32 | dummy.next = head; 33 | ListNode cur = dummy; 34 | while (cur.next != null && cur.next.next != null) { 35 | ListNode node = cur.next.next; 36 | cur.next.next = node.next; 37 | node.next = cur.next; 38 | cur.next = node; 39 | cur = node.next; 40 | } 41 | return dummy.next; 42 | } 43 | public ListNode swapPairs(ListNode head) { 44 | if (head == null || head.next == null) return head; 45 | ListNode first = head, second = head.next; 46 | first.next = second.next; 47 | second.next = first; 48 | first.next = swapPairs(first.next); 49 | return second; 50 | } 51 | } -------------------------------------------------------------------------------- /SymmetricTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Dec 25, 2014 4 | Problem: Symmetric Tree 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/symmetric-tree/ 7 | Notes: 8 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 9 | For example, this binary tree is symmetric: 10 | 1 11 | / \ 12 | 2 2 13 | / \ / \ 14 | 3 4 4 3 15 | But the following is not: 16 | 1 17 | / \ 18 | 2 2 19 | \ \ 20 | 3 3 21 | Note: 22 | Bonus points if you could solve it both recursively and iteratively. 23 | 24 | Solution: 1. Recursive solution 25 | */ 26 | 27 | /** 28 | * Definition for binary tree 29 | * public class TreeNode { 30 | * int val; 31 | * TreeNode left; 32 | * TreeNode right; 33 | * TreeNode(int x) { val = x; } 34 | * } 35 | */ 36 | public class Solution { 37 | public boolean isSymmetric(TreeNode root) { 38 | if (root == null) return true; 39 | return solve (root.left, root.right); 40 | } 41 | public boolean solve(TreeNode t1, TreeNode t2) { 42 | if (t1 == null && t2 == null) return true; 43 | if (t1 == null && t2 != null || t1 != null && t2 == null || t1.val != t2.val) return false; 44 | return solve(t1.left, t2.right) && solve(t1.right, t2.left); 45 | } 46 | } -------------------------------------------------------------------------------- /TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 07, 2014 4 | Problem: Trapping Rain Water 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/trapping-rain-water/ 7 | Notes: 8 | Given n non-negative integers representing an elevation map where the width of 9 | each bar is 1, compute how much water it is able to trap after raining. 10 | For example, 11 | Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. 12 | 13 | Solution: 1. Find left bound and right bound for each element. O(n). 14 | 2. more space efficiency. Time: O(n), Space: O(1); 15 | */ 16 | public class Solution { 17 | public int trap_1(int[] A) { 18 | int n = A.length; 19 | if (n == 0) return 0; 20 | int[] maxLeft = new int[n]; 21 | int[] maxRight = new int[n]; 22 | maxLeft[0] = A[0]; 23 | maxRight[n - 1] = A[n - 1]; 24 | for (int i = 1; i < n; ++i) { 25 | maxLeft[i] = Math.max(maxLeft[i - 1], A[i]); 26 | maxRight[n - 1 - i] = Math.max(maxRight[n - i], A[n - 1 - i]); 27 | } 28 | 29 | int res = 0; 30 | for (int i = 1; i < n; ++i) { 31 | res += Math.min(maxLeft[i], maxRight[i]) - A[i]; 32 | } 33 | return res; 34 | } 35 | public int trap(int[] A) { 36 | int n = A.length, res = 0; 37 | if (n <= 2) return 0; 38 | int maxLeft = A[0]; 39 | int maxRight = A[n - 1]; 40 | int left = 0, right = n - 1; 41 | while (left <= right) { 42 | if (maxLeft <= maxRight) { 43 | res += Math.max(0, maxLeft - A[left]); 44 | maxLeft = Math.max(maxLeft, A[left]); 45 | ++left; 46 | } else { 47 | res += Math.max(0, maxRight - A[right]); 48 | maxRight = Math.max(maxRight, A[right]); 49 | --right; 50 | } 51 | } 52 | return res; 53 | } 54 | } -------------------------------------------------------------------------------- /Triangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: May 14, 2013 4 | Problem: Triangle 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/triangle/ 7 | Notes: 8 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 9 | For example, given the following triangle 10 | [ 11 | [2], 12 | [3,4], 13 | [6,5,7], 14 | [4,1,8,3] 15 | ] 16 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 17 | Note: 18 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number 19 | of rows in the triangle. 20 | 21 | Solution: Note that there are n elements in the n-th row (n starts from 1). 22 | 1. DP. Do not need additional spaces (happen in-place). 23 | */ 24 | public class Solution { 25 | public int minimumTotal(List> triangle) { 26 | for (int i = triangle.size() - 2; i >= 0; --i) { 27 | List cur = triangle.get(i); 28 | List next = triangle.get(i+1); 29 | for (int j = 0; j < i + 1; ++j) { 30 | cur.set(j, Math.min(next.get(j), next.get(j+1)) + cur.get(j)); 31 | } 32 | } 33 | return triangle == null ? 0 : triangle.get(0).get(0); 34 | } 35 | } -------------------------------------------------------------------------------- /TwoSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Dec 13, 2014 4 | Problem: Two Sum 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/two-sum/ 7 | Notes: 8 | Given an array of integers, find two numbers such that they add up to a specific target number. 9 | 10 | The function twoSum should return indices of the two numbers such that they add up to the target, 11 | where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 12 | 13 | You may assume that each input would have exactly one solution. 14 | 15 | Input: numbers={2, 7, 11, 15}, target=9 16 | Output: index1=1, index2=2 17 | 18 | Solution: 1. Hash table. O(n) 19 | 20 | Note: Hash Table solution has been updated. In case that the two elements are the same, 21 | all the indices should be stored in the map. 22 | */ 23 | 24 | public class Solution { 25 | public int[] twoSum(int[] numbers, int target) { 26 | HashMap map = new HashMap(); 27 | for (int i = 0; i < numbers.length; ++i) { 28 | int b = target - numbers[i]; 29 | if (map.get(b) != null) { 30 | return new int[]{map.get(b),i+1}; 31 | } else map.put(numbers[i],i+1); 32 | } 33 | return null; 34 | } 35 | } -------------------------------------------------------------------------------- /UniqueBinarySearchTrees.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Oct 07, 2014 4 | Problem: Unique Binary Search Trees 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/unique-binary-search-trees/ 7 | Notes: 8 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 9 | For example, 10 | Given n = 3, there are a total of 5 unique BST's. 11 | 1 3 3 2 1 12 | \ / / / \ \ 13 | 3 2 1 1 3 2 14 | / / \ \ 15 | 2 1 2 3 16 | 17 | Solution: dp. 18 | */ 19 | public class Solution { 20 | public int numTrees_1(int n) { 21 | int[] dp = new int[n+1]; 22 | dp[0] = 1; 23 | for (int i = 1; i <= n; ++i) 24 | for (int j = 0; j < i; j++) 25 | dp[i] += dp[j] * dp[i-j-1]; 26 | return dp[n]; 27 | } 28 | public int numTrees(int n) { 29 | if (n < 0) return 0; 30 | int[] dp = new int[n+1]; 31 | dp[0] = 1; dp[1] = 1; 32 | for(int i = 2;i <= n; ++i){ 33 | dp[i] = dp[i-1] * (4 * i - 2)/(i + 1); 34 | } 35 | return dp[n]; 36 | } 37 | } -------------------------------------------------------------------------------- /UniqueBinarySearchTreesII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 25, 2014 4 | Problem: Unique Binary Search Trees II 5 | Difficulty: Medium 6 | Source: https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 7 | Notes: 8 | Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. 9 | For example, 10 | Given n = 3, your program should return all 5 unique BST's shown below. 11 | 1 3 3 2 1 12 | \ / / / \ \ 13 | 3 2 1 1 3 2 14 | / / \ \ 15 | 2 1 2 3 16 | 17 | Solution: 1. DFS directly. (from the Internet) 18 | 2. DP + DFS. (my solution) 19 | a. Generate trees for 'n' from 1 to n. (DP) 20 | b. When generate trees for n = i, get the left and right subtrees 21 | by copying tree structures of dp[1...i-1]. (copy tree uses DFS) 22 | */ 23 | /** 24 | * Definition for binary tree 25 | * public class TreeNode { 26 | * int val; 27 | * TreeNode left; 28 | * TreeNode right; 29 | * TreeNode(int x) { val = x; left = null; right = null; } 30 | * } 31 | */ 32 | public class Solution { 33 | public List generateTrees(int n) { 34 | return generateTreesRe(1, n); 35 | } 36 | public List generateTreesRe(int l, int r) { 37 | ArrayList res = new ArrayList(); 38 | if (l > r) { 39 | res.add(null); 40 | return res; 41 | } 42 | for (int k = l; k <= r; ++k) { 43 | List leftTrees = generateTreesRe(l, k-1); 44 | List rightTrees = generateTreesRe(k+1, r); 45 | for (int i = 0; i < leftTrees.size(); i++) { 46 | for (int j = 0; j < rightTrees.size(); j++) { 47 | TreeNode root = new TreeNode(k); 48 | root.left = leftTrees.get(i); 49 | root.right = rightTrees.get(j); 50 | res.add(root); 51 | } 52 | } 53 | } 54 | return res; 55 | } 56 | } -------------------------------------------------------------------------------- /UniquePaths.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Oct 9, 2014 4 | Problem: Unique Paths 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/unique-paths/ 7 | Notes: 8 | A robot is located at the top-left corner of a m x n grid. 9 | The robot can only move either down or right at any point in time. The robot is trying to reach 10 | the bottom-right corner of the grid (marked 'Finish' in the diagram below). 11 | How many possible unique paths are there? 12 | 13 | Solution: 14 | 1. Use formula C(x,t) = t!/(x!*(t-x)!) (x should be large for calculation). 15 | 2. Dynamic programming. UP(i,j) = UP(i-1,j) + UP(i,j-1). 16 | */ 17 | public class Solution { 18 | public int uniquePaths_1(int m, int n) { 19 | if (m == 1 || n == 1) return 1; 20 | int t = (m-1)+(n-1); 21 | int x = (m > n) ? (m-1) : (n-1); 22 | long res = 1; 23 | for (int i = t; i > x; i--) res *= i; 24 | for (int i = t-x; i > 1; i--) res /= i; 25 | return (int)res; 26 | } 27 | public int uniquePaths_2(int m, int n) { 28 | if (m == 1 || n == 1) return 1; 29 | int[][] dp = new int[m][n]; 30 | for (int i = 0; i < m; i++) 31 | dp[i][0] = 1; 32 | for (int j = 0; j < n; j++) 33 | dp[0][j] = 1; 34 | for (int i = 1; i < m; i++) 35 | for (int j = 1; j < n; j++) 36 | dp[i][j] = dp[i-1][j] + dp[i][j-1]; 37 | return dp[m-1][n-1]; 38 | } 39 | public int uniquePaths(int m, int n) { 40 | if (m == 1 || n == 1) return 1; 41 | int[] dp = new int[n]; 42 | for (int j = 0; j < n; j++) 43 | dp[j] = 1; 44 | for (int i = 1; i < m; i++) 45 | for (int j = 1; j < n; j++) 46 | dp[j] = dp[j] + dp[j-1]; 47 | return dp[n-1]; 48 | } 49 | } -------------------------------------------------------------------------------- /UniquePathsII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, higuige@gmail.com 3 | Date: Dec 25, 2014 4 | Problem: Unique Paths II 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/unique-paths-ii/ 7 | Notes: 8 | Follow up for "Unique Paths": 9 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 10 | An obstacle and empty space is marked as 1 and 0 respectively in the grid. 11 | For example, 12 | There is one obstacle in the middle of a 3x3 grid as illustrated below. 13 | [ 14 | [0,0,0], 15 | [0,1,0], 16 | [0,0,0] 17 | ] 18 | The total number of unique paths is 2. 19 | Note: m and n will be at most 100. 20 | 21 | Solution: Dynamic programming. 22 | */ 23 | 24 | public class Solution { 25 | public int uniquePathsWithObstacles_1(int[][] obstacleGrid) { 26 | int m = obstacleGrid.length; 27 | int n = obstacleGrid[0].length; 28 | int[][] dp = new int[m][n]; 29 | if (obstacleGrid[0][0] == 1) return 0; 30 | dp[0][0] = 1; 31 | for (int i = 1; i < m; i++) 32 | dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i-1][0]; 33 | for (int j = 1; j < n; j++) 34 | dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j-1]; 35 | 36 | for (int i = 1; i < m; i++) 37 | for (int j = 1; j < n; j++) 38 | dp[i][j] = obstacleGrid[i][j] == 1 ? 0: dp[i-1][j] + dp[i][j-1]; 39 | 40 | return dp[m-1][n-1]; 41 | } 42 | public int uniquePathsWithObstacles_2(int[][] obstacleGrid) { 43 | int m = obstacleGrid.length; 44 | if (m == 0) return 0; 45 | int n = obstacleGrid[0].length; 46 | int[] dp = new int[n]; 47 | if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) return 0; 48 | dp[0] = 1; 49 | for (int i = 0; i < m; ++i) { 50 | dp[0] = obstacleGrid[i][0] == 1 ? 0 : dp[0]; 51 | for(int j = 1; j < n; ++j) { 52 | dp[j] = obstacleGrid[i][j] == 1 ? 0: dp[j] + dp[j-1]; 53 | } 54 | } 55 | return dp[n-1]; 56 | } 57 | } -------------------------------------------------------------------------------- /ValidNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 25, 2015 4 | Problem: Valid Number 5 | Difficulty: Hard 6 | Source: https://oj.leetcode.com/problems/valid-number/ 7 | Notes: 8 | Validate if a given string is numeric. 9 | Some examples: 10 | "0" => true 11 | " 0.1 " => true 12 | "abc" => false 13 | "1 a" => false 14 | "2e10" => true 15 | Note: It is intended for the problem statement to be ambiguous. You should gather all 16 | requirements up front before implementing one. 17 | 18 | Solution: This finite-state machine solution. Learn from fuwutu & snakeDling. 19 | */ 20 | 21 | public class Solution { 22 | public boolean isNumber(String s) { 23 | int start = 0, end = s.length() -1; 24 | boolean dot = false, exp = false, digit = false; 25 | while (start <= end && (s.charAt(start) == ' ')) ++start; 26 | while (start <= end && (s.charAt(end) == ' ')) --end; 27 | if (start <= end && (s.charAt(start) == '+' || s.charAt(start) == '-')) ++start; 28 | if (start > end) return false; 29 | for ( ; start <= end; ++start) { 30 | if (Character.isDigit(s.charAt(start))) digit = true; 31 | else if (s.charAt(start) == 'e' || s.charAt(start) == 'E') { 32 | if (exp == true || digit == false || start == end) return false; 33 | exp = true; 34 | } else if (s.charAt(start) == '.') { 35 | if (dot == true || exp == true) return false; 36 | if (digit == false && start == end) return false; 37 | dot = true; 38 | } else if (s.charAt(start) == '+' || s.charAt(start) == '-') { 39 | if (start == end) return false; 40 | if (s.charAt(start-1) != 'e' && s.charAt(start-1) != 'E') return false; 41 | } else return false; 42 | } 43 | return true; 44 | } 45 | } -------------------------------------------------------------------------------- /ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 17, 2015 4 | Problem: Valid Palindrome 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/valid-palindrome/ 7 | Notes: 8 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 9 | For example, 10 | "A man, a plan, a canal: Panama" is a palindrome. 11 | "race a car" is not a palindrome. 12 | Note: 13 | Have you consider that the string might be empty? This is a good question to ask during an interview. 14 | For the purpose of this problem, we define empty string as valid palindrome. 15 | 16 | Solution: traverse from both side. 17 | */ 18 | public class Solution { 19 | public boolean isPalindrome(String s) { 20 | s = s.toLowerCase().replaceAll("\\W", ""); 21 | System.out.println(s); 22 | for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { 23 | if (s.charAt(i) != s.charAt(j)) 24 | return false; 25 | } 26 | return true; 27 | } 28 | } -------------------------------------------------------------------------------- /ValidParentheses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Valid Parentheses 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/valid-parentheses/ 7 | Notes: 8 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 9 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 10 | 11 | Solution: stack. 12 | */ 13 | public class Solution { 14 | public boolean isValid(String s) { 15 | Stack stk = new Stack(); 16 | for (int i = 0; i < s.length(); ++i) { 17 | char ch = s.charAt(i); 18 | if (ch == '(' || ch == '[' || ch== '{') { 19 | stk.push(ch); 20 | } 21 | else { 22 | if (stk.empty() || Math.abs(stk.pop() - ch) > 2) 23 | return false; 24 | } 25 | } 26 | return stk.empty(); 27 | } 28 | } -------------------------------------------------------------------------------- /ValidSudoku.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Valid Sudoku 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/valid-sudoku/ 7 | Notes: 8 | Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules (http://sudoku.com.au/TheRules.aspx). 9 | The Sudoku board could be partially filled, where empty cells are filled with the character '.'. 10 | 11 | Solution: 1. Traverse the Sudoku only once. 12 | 2. Bit manipulation. Use only one bit to represent a number. Space: sizeof(int) * (1+9+9). 13 | */ 14 | public class Solution { 15 | public boolean isValidSudoku(char[][] board) { 16 | boolean[] used = new boolean[9]; 17 | 18 | for(int i=0;i<9;i++){ 19 | Arrays.fill(used,false); 20 | for(int j = 0; j<9;j++){ 21 | if(check(board[i][j],used)==false) return false; 22 | } 23 | Arrays.fill(used,false); 24 | for(int j = 0; j<9;j++){ 25 | if(check(board[j][i],used)==false) return false; 26 | } 27 | } 28 | 29 | for(int r = 0; r<3;r++){ 30 | for(int c = 0; c<3;c++){ 31 | Arrays.fill(used,false); 32 | for(int i = r*3;i dict) { 20 | int n = s.length(); 21 | boolean[] dp = new boolean[n+1]; 22 | dp[n] = true; 23 | for (int i = n - 1; i >= 0; --i) { 24 | for (int j = i; j < n; ++j) { 25 | if (dict.contains(s.substring(i,j+1)) && dp[j+1]) { 26 | dp[i] = true; 27 | break; 28 | } 29 | } 30 | } 31 | return dp[0]; 32 | } 33 | } -------------------------------------------------------------------------------- /WordBreakII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Andy, nkuwjg@gmail.com 3 | Date: Jan 29, 2015 4 | Problem: Word Break II 5 | Difficulty: Easy 6 | Source: http://oj.leetcode.com/problems/word-break-ii/ 7 | Notes: 8 | Given a string s and a dictionary of words dict, add spaces in s to 9 | construct a sentence where each word is a valid dictionary word. 10 | Return all such possible sentences. 11 | For example, given 12 | s = "catsanddog", 13 | dict = ["cat", "cats", "and", "sand", "dog"]. 14 | A solution is ["cats and dog", "cat sand dog"]. 15 | 16 | Solution: check before constructing the sentences. 17 | */ 18 | 19 | public class Solution { 20 | public List wordBreak(String s, Set dict) { 21 | List res = new ArrayList(); 22 | int n = s.length(); 23 | boolean[] canBreak = new boolean[n+1]; 24 | canBreak[n] = true; 25 | for (int i = n - 1; i >= 0; --i) { 26 | for (int j = i; j < n; ++j) { 27 | if (dict.contains(s.substring(i,j+1)) && canBreak[j+1]) { 28 | canBreak[i] = true; 29 | break; 30 | } 31 | } 32 | } 33 | if (canBreak[0] == false) return res; 34 | wordBreakRe(s, dict, "", 0, res); 35 | return res; 36 | } 37 | public void wordBreakRe(String s, Set dict, String path, int start, List res) { 38 | if (start == s.length()) { 39 | res.add(path); 40 | return; 41 | } 42 | if (path.length() != 0) path = path + " "; 43 | for (int i = start; i < s.length(); ++i) { 44 | String word = s.substring(start, i + 1); 45 | if (dict.contains(word) == false) continue; 46 | wordBreakRe(s, dict, path + word, i + 1, res); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /WordLadder.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Word Ladder 5 | Difficulty: High 6 | Source: https://oj.leetcode.com/problems/word-ladder/ 7 | Notes: 8 | Given two words (start and end), and a dictionary, find the length of shortest transformation 9 | sequence from start to end, such that: 10 | Only one letter can be changed at a time 11 | Each intermediate word must exist in the dictionary 12 | For example, 13 | Given: 14 | start = "hit" 15 | end = "cog" 16 | dict = ["hot","dot","dog","lot","log"] 17 | As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", 18 | return its length 5. 19 | Note: 20 | Return 0 if there is no such transformation sequence. 21 | All words have the same length. 22 | All words contain only lowercase alphabetic characters. 23 | 24 | Solution: BFS. 25 | */ 26 | public class Solution { 27 | public int ladderLength(String start, String end, Set dict) { 28 | Queue cur = new LinkedList(); 29 | if(start.compareTo(end) == 0) return 0; 30 | cur.offer(start); 31 | int depth = 1; 32 | Set visited = new HashSet(); 33 | while (cur.isEmpty() == false) { 34 | Queue queue = new LinkedList(); 35 | while(cur.isEmpty() == false) { 36 | String str = cur.poll(); 37 | char[] word = str.toCharArray(); 38 | for (int i = 0; i < word.length; ++i) { 39 | char before = word[i]; 40 | for (char ch = 'a'; ch <= 'z'; ++ch) { 41 | word[i] = ch; 42 | String temp = new String(word); 43 | if (end.compareTo(temp) == 0) return depth + 1; 44 | if (dict.contains(temp) == true && visited.contains(temp) == false) { 45 | queue.offer(temp); 46 | visited.add(temp); 47 | } 48 | } 49 | word[i] = before; 50 | } 51 | } 52 | cur = queue; 53 | ++depth; 54 | } 55 | return 0; 56 | } 57 | } -------------------------------------------------------------------------------- /WordSearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 20, 2014 4 | Problem: Word Search 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/word-search/ 7 | Notes: 8 | Given a 2D board and a word, find if the word exists in the grid. 9 | The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are 10 | those horizontally or vertically neighboring. The same letter cell may not be used more than once. 11 | For example, 12 | Given board = 13 | [ 14 | ["ABCE"], 15 | ["SFCS"], 16 | ["ADEE"] 17 | ] 18 | word = "ABCCED", -> returns true, 19 | word = "SEE", -> returns true, 20 | word = "ABCB", -> returns false. 21 | 22 | Solution: DFS. 23 | */ 24 | public class Solution { 25 | public boolean exist(char[][] board, String word) { 26 | int m = board.length; 27 | if (m == 0) return false; 28 | int n = board[0].length; 29 | if (n == 0) return false; 30 | if (word.length() == 0) return true; 31 | boolean[][] visited = new boolean[m][n]; 32 | for (int i = 0; i < m; ++i) { 33 | for (int j = 0; j < n; ++j) { 34 | if (board[i][j] == word.charAt(0) && existRe(board, i, j, word, 0, visited)) { 35 | return true; 36 | } 37 | } 38 | } 39 | return false; 40 | } 41 | public boolean existRe(char[][] board, int i, int j, String word, int cur, boolean[][] visited) { 42 | if (cur == word.length()) return true; 43 | int m = board.length; 44 | int n = board[0].length; 45 | if (i < 0 || i >= m || j < 0 || j >= n) return false; 46 | if (visited[i][j] == true || (board[i][j] != word.charAt(cur))) return false; 47 | visited[i][j] = true; 48 | if (existRe(board, i+1, j, word, cur+1,visited)) return true; 49 | if (existRe(board, i-1, j, word, cur+1,visited)) return true; 50 | if (existRe(board, i, j+1, word, cur+1,visited)) return true; 51 | if (existRe(board, i, j-1, word, cur+1,visited)) return true; 52 | visited[i][j] = false; 53 | return false; 54 | } 55 | } -------------------------------------------------------------------------------- /ZigZagConversion.java: -------------------------------------------------------------------------------- 1 | /* 2 | Author: King, wangjingui@outlook.com 3 | Date: Dec 13, 2014 4 | Problem: ZigZag Conversion 5 | Difficulty: Easy 6 | Source: https://oj.leetcode.com/problems/zigzag-conversion/ 7 | Notes: 8 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 9 | 10 | P A H N 11 | A P L S I I G 12 | Y I R 13 | And then read line by line: "PAHNAPLSIIGYIR" 14 | Write the code that will take a string and make this conversion given a number of rows: 15 | 16 | string convert(string text, int nRows); 17 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 18 | 19 | Solution: ... 20 | */ 21 | 22 | public class Solution { 23 | public String convert(String s, int nRows) { 24 | int n = s.length(); 25 | if (n <= 1 || nRows <= 1) return s; 26 | StringBuffer res = new StringBuffer(); 27 | for (int i = 0; i < nRows; ++i) { 28 | for (int j = 0; j + i < n; j += 2*nRows - 2) { 29 | res.append(s.charAt(j+i)); 30 | if (i == 0 || i == nRows - 1) continue; 31 | if (j + 2*nRows - 2 - i < n) 32 | res.append(s.charAt(j + 2*nRows - 2 - i)); 33 | } 34 | } 35 | return res.toString(); 36 | } 37 | } --------------------------------------------------------------------------------