├── README ├── Valid Number.java ├── Sqrt(x).java ├── Remove Element.java ├── Reverse Integer.java ├── Best Time to Buy and Sell Stock II.java ├── Remove Duplicates from Sorted Array.java ├── Maximum Subarray.java ├── Pow(x, n).java ├── Length of Last Word.java ├── Remove Duplicates from Sorted Array II.java ├── Pascal's Triangle II.java ├── Triangle.java ├── Gray Code.java ├── Unique Binary Search Trees.java ├── Merge Sorted Array.java ├── Palindrome Number.java ├── Gas Station.java ├── Maximum Depth of Binary Tree.java ├── Best Time to Buy and Sell Stock.java ├── Search Insert Position.java ├── Sort Colors.java ├── First Missing Positive.java ├── Pascal's Triangle.java ├── Same Tree.java ├── Valid Palindrome.java ├── Path Sum.java ├── Count and Say.java ├── Trapping Rain Water.java ├── Simplify Path.java ├── Swap Nodes in Pairs.java ├── Linked List Cycle.java ├── Shortest Palindrome.java ├── Container With Most Water.java ├── Distinct Subsequences.java ├── Implement strStr().java ├── Convert Sorted Array to Binary Search Tree.java ├── Sum Root to Leaf Numbers.java ├── Remove Nth Node From End of List.java ├── Roman to Integer.java ├── Rotate Image.java ├── Candy.java ├── Divide Two Integers.java ├── Valid Parentheses.java ├── Insertion Sort List.java ├── Linked List Cycle II.java ├── ZigZag Conversion.java ├── Subsets.java ├── Validate Binary Search Tree.java ├── Binary Tree Preorder Traversal.java ├── Longest Common Prefix.java ├── Longest Consecutive Sequence.java ├── Symmetric Tree.java ├── Search a 2D Matrix.java ├── Balanced Binary Tree.java ├── LRU Cache.java ├── Binary Tree Inorder Traversal.java ├── Unique Paths II.java ├── Partition List.java ├── Two Sum.java ├── Minimum Path Sum.java ├── Combination Sum.java ├── Combination Sum II.java ├── Construct Binary Tree from Preorder and Inorder Traversal.java ├── N-Queens II.java ├── Jump Game.java ├── Construct Binary Tree from Inorder and Postorder Traversal.java ├── Merge Intervals.java ├── Reverse Linked List II.java ├── Largest Rectangle in Histogram.java ├── Permutation Sequence.java ├── Longest Palindromic Substring.java ├── Climbing Stairs.java ├── String to Integer (atoi).java ├── Path Sum II.java ├── Jump Game II.java ├── Longest Substring Without Repeating Characters.java ├── Rotate List.java ├── Remove Duplicates from Sorted List.java ├── Evaluate Reverse Polish Notation.java ├── Edit Distance.java ├── Next Permutation.java ├── Word Search.java ├── Unique Binary Search Trees II.java ├── Sudoku Solver.java ├── Plus One.java ├── Letter Combinations of a Phone Number.java ├── Merge k Sorted Lists.java ├── Binary Tree Postorder Traversal.java ├── Minimum Depth of Binary Tree.java ├── Reverse Words in a String.java ├── Reverse Nodes in k-Group.java ├── Unique Paths.java ├── Search in Rotated Sorted Array.java ├── Clone Graph.java ├── Convert Sorted List to Binary Search Tree.java ├── N-Queens.java ├── Palindrome Partitioning II.java ├── Max Points on a Line.java ├── Search for a Range.java ├── Search in Rotated Sorted Array II.java ├── Permutations.java ├── Permutations II.java ├── Subsets II.java ├── Substring with Concatenation of All Words.java ├── Valid Sudoku.java ├── Flatten Binary Tree to Linked List.java ├── Set Matrix Zeroes.java ├── Single Number II.java ├── Generate Parentheses.java ├── Maximal Rectangle.java ├── Copy List with Random Pointer.java ├── Remove Duplicates from Sorted List II.java ├── Reorder List.java ├── Text Justification.java ├── Spiral Matrix II.java ├── Restore IP Addresses.java ├── Palindrome Partitioning.java ├── Surrounded Regions.java ├── Merge Two Sorted Lists.java ├── Single Number.java ├── Word Break.java ├── Insert Interval.java ├── Binary Tree Level Order Traversal.java ├── Binary Tree Level Order Traversal II.java ├── Add Two Numbers.java ├── Combinations.java ├── Populating Next Right Pointers in Each Node II.java ├── Binary Tree Maximum Path Sum.java ├── Word Break II.java ├── Decode Ways.java ├── Populating Next Right Pointers in Each Node.java ├── Wildcard Matching.java ├── Minimum Window Substring.java ├── Spiral Matrix.java ├── Integer to Roman.java ├── Binary Tree Zigzag Level Order Traversal.java ├── Longest Valid Parentheses.java ├── Recover Binary Search Tree.java ├── Median of Two Sorted Arrays.java ├── Interleaving String.java ├── Best Time to Buy and Sell Stock III.java ├── Scramble String.java ├── Add Binary.java ├── Multiply Strings.java ├── Regular Expression Matching.java ├── 3Sum Closest.java ├── Anagrams.java ├── 3Sum.java ├── Word Ladder.java └── Word Ladder II.java /README: -------------------------------------------------------------------------------- 1 | leetcode practise. 2 | -------------------------------------------------------------------------------- /Valid Number.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rffffffff007/leetcode/HEAD/Valid Number.java -------------------------------------------------------------------------------- /Sqrt(x).java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int sqrt(int x) { 3 | double x0 = 1; 4 | // Newton's method 5 | for(int i = 0; i < 100; i++){ 6 | x0 = (x0 + x / x0) / 2; 7 | } 8 | return (int)x0; 9 | } 10 | } -------------------------------------------------------------------------------- /Remove Element.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeElement(int[] A, int elem) { 3 | int len = 0; 4 | for (int i = 0; i < A.length; i++) 5 | if (A[i] != elem) 6 | A[len++] = A[i]; 7 | return len; 8 | } 9 | } -------------------------------------------------------------------------------- /Reverse Integer.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int reverse(int x) { 3 | int sum = 0; 4 | while (x != 0) { 5 | sum *= 10; 6 | sum += x % 10; 7 | x /= 10; 8 | } 9 | return sum; 10 | } 11 | } -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | int len = prices.length; 4 | int profit = 0; 5 | for(int i = 0; i < len - 1; i++) 6 | if(prices[i + 1] > prices[i]) 7 | profit += prices[i + 1] - prices[i]; 8 | return profit; 9 | } 10 | } -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] A) { 3 | int n = A.length; 4 | int distinctCount = 0; 5 | for(int i = 0; i < n; i++) 6 | if(distinctCount == 0 || A[i] != A[distinctCount - 1]) 7 | A[distinctCount++] = A[i]; 8 | return distinctCount; 9 | } 10 | } -------------------------------------------------------------------------------- /Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxSubArray(int[] A) { 3 | int n = A.length; 4 | int sum = 0; 5 | int max = Integer.MIN_VALUE; 6 | for(int i = 0; i < n; i++){ 7 | sum += A[i]; 8 | max = Math.max(max, sum); 9 | if(sum < 0) 10 | sum = 0; 11 | } 12 | return max; 13 | } 14 | } -------------------------------------------------------------------------------- /Pow(x, n).java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public double pow(double x, int n) { 3 | if (n == 0){ 4 | return 1; 5 | } else if( n == 1){ 6 | return x; 7 | } else if (n == -1){ 8 | return 1 / x; 9 | } else{ 10 | double half = pow(x, n / 2); 11 | return half * half * pow(x, n % 2); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Length of Last Word.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLastWord(String s) { 3 | char[] cs = s.toCharArray(); 4 | int lastSpace = -1; 5 | int len = cs.length; 6 | for(; len > 0 && cs[len - 1] == ' '; len--); 7 | for(int i = 0; i < len; i++) 8 | if(cs[i] == ' ') 9 | lastSpace = i; 10 | return len - lastSpace - 1; 11 | } 12 | } -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] A) { 3 | int n = A.length; 4 | int distinctCount = 0; 5 | for(int i = 0; i < n; i++) 6 | if(distinctCount == 0 || A[i] != A[distinctCount - 1] || distinctCount == 1 || A[i] != A[distinctCount - 2]) 7 | A[distinctCount++] = A[i]; 8 | return distinctCount; 9 | } 10 | } -------------------------------------------------------------------------------- /Pascal's Triangle II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList getRow(int rowIndex) { 3 | Integer[] row = new Integer[rowIndex + 1]; 4 | row[0] = 1; 5 | for(int i = 1; i <= rowIndex; i++){ 6 | row[i] = 1; 7 | for(int j = i - 1; j > 0; j--) 8 | row[j] = row[j] + row[j - 1]; 9 | } 10 | return new ArrayList(Arrays.asList(row)); 11 | } 12 | } -------------------------------------------------------------------------------- /Triangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minimumTotal(ArrayList> triangle) { 3 | int n = triangle.size(); 4 | int[] min = new int[n + 1]; 5 | for(int i = n - 1; i >= 0; i--){ 6 | for(int j = 0; j <= i; j++){ 7 | min[j] = Math.min(min[j], min[j + 1]); 8 | min[j] += triangle.get(i).get(j); 9 | } 10 | } 11 | return min[0]; 12 | } 13 | } -------------------------------------------------------------------------------- /Gray Code.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList grayCode(int n) { 3 | ArrayList result = new ArrayList(); 4 | result.add(0); 5 | for (int i = 1; i <= n; i++) { 6 | for (int j = result.size() - 1; j >= 0; j--) { 7 | int val = result.get(j); 8 | result.add(val | (1 << (i - 1))); 9 | } 10 | } 11 | return result; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Unique Binary Search Trees.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numTrees(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int[] sum = new int[n + 1]; 6 | sum[0] = 1; 7 | for(int i = 1; i <= n; i++){ 8 | for(int j = 0; j < i; j++){ 9 | sum[i] += sum[j] * sum[i - 1 - j]; 10 | } 11 | } 12 | return sum[n]; 13 | } 14 | } -------------------------------------------------------------------------------- /Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void merge(int A[], int m, int B[], int n) { 3 | for(int i = m - 1; i >= 0; i--) 4 | A[i + n] = A[i]; 5 | 6 | int pa = n; 7 | int pb = 0; 8 | int pc = 0; 9 | 10 | while(pb < n || pa < n + m){ 11 | if(pb == n || pa < n + m && A[pa] < B[pb]) 12 | A[pc++] = A[pa++]; 13 | else 14 | A[pc++] = B[pb++]; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Palindrome Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(int x) { 3 | int y = 0; 4 | if (x == 0) 5 | return true; 6 | if (x < 0 || x % 10 == 0) 7 | return false; 8 | while (x >= y) { 9 | y *= 10; 10 | y += x % 10; 11 | if (x == y) 12 | return true; 13 | x /= 10; 14 | if (x == y) 15 | return true; 16 | } 17 | return false; 18 | } 19 | } -------------------------------------------------------------------------------- /Gas Station.java: -------------------------------------------------------------------------------- 1 | public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int sum = 0; int n = gas.length; int index = -1; for (int i = 0; i < 2 * n; i++) { int j = i % n; sum += gas[j] - cost[j]; if (sum >= 0 && index == -1) index = i; if (sum < 0) { sum = 0; index = -1; } } if (index >= 0 && index < n) return index % n; else return -1; } } -------------------------------------------------------------------------------- /Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int maxDepth(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if(root == null){ 15 | return 0; 16 | } 17 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 18 | } 19 | } -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | int[] min = new int[prices.length]; 4 | int max = 0; 5 | for (int i = 0; i < prices.length; i++) { 6 | if (i == 0) { 7 | min[i] = prices[i]; 8 | } else { 9 | min[i] = prices[i] < min[i - 1] ? prices[i] : min[i - 1]; 10 | } 11 | int profit = prices[i] - min[i]; 12 | max = profit > max ? profit : max; 13 | } 14 | return max; 15 | } 16 | } -------------------------------------------------------------------------------- /Search Insert Position.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int searchInsert(int[] A, int target) { 3 | return bsearch(A, 0, A.length, target); 4 | } 5 | 6 | private int bsearch(int[] a, int s, int e, int target){ 7 | if(s == e) 8 | return s; 9 | int mid = (s + e) / 2; 10 | int val = a[mid]; 11 | if(val == target) 12 | return mid; 13 | else if(target > val) 14 | return bsearch(a, mid + 1, e, target); 15 | else 16 | return bsearch(a, s, mid, target); 17 | } 18 | } -------------------------------------------------------------------------------- /Sort Colors.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void sortColors(int[] A) { 3 | int n = A.length; 4 | int i0 = 0, i1 = 0; 5 | int i2 = n - 1; 6 | while(i1 <= i2){ 7 | int val = A[i1]; 8 | if(val == 0){ 9 | swap(A, i0++, i1++); 10 | }else if(val == 1){ 11 | i1++; 12 | }else{ 13 | swap(A, i1, i2--); 14 | } 15 | } 16 | } 17 | 18 | private void swap(int[] a, int i, int j){ 19 | int tmp = a[i]; 20 | a[i] = a[j]; 21 | a[j] = tmp; 22 | } 23 | } -------------------------------------------------------------------------------- /First Missing Positive.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int firstMissingPositive(int[] A) { 3 | int n = A.length; 4 | // similar with count sort, use A as the hash table. 5 | for(int i = 0; i < n; i++){ 6 | int val = A[i]; 7 | while(val > 0 && val <= n && val != A[val - 1]){ 8 | int tmp = A[val - 1]; 9 | A[val - 1] = val; 10 | val = tmp; 11 | } 12 | } 13 | int i; 14 | for(i = 0; i < n; i++) 15 | if(A[i] != i + 1) 16 | break; 17 | return i + 1; 18 | } 19 | } -------------------------------------------------------------------------------- /Pascal's Triangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> generate(int numRows) { 3 | ArrayList> res = new ArrayList>(); 4 | for(int i = 0; i < numRows; i++){ 5 | Integer[] row = new Integer[i + 1]; 6 | row[0] = row[i] = 1; 7 | if(i > 0){ 8 | ArrayList last = res.get(i - 1); 9 | for(int j = 1; j < i; j++) 10 | row[j] = last.get(j) + last.get(j - 1); 11 | } 12 | res.add(new ArrayList(Arrays.asList(row))); 13 | } 14 | return res; 15 | } 16 | } -------------------------------------------------------------------------------- /Same Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isSameTree(TreeNode p, TreeNode q) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if(p == null && q == null){ 15 | return true; 16 | } else if(p == null || q == null){ 17 | return false; 18 | } 19 | return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 20 | } 21 | } -------------------------------------------------------------------------------- /Valid Palindrome.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(String s) { 3 | char[] cs = s.toLowerCase().toCharArray(); 4 | int a = 0; 5 | int b = cs.length - 1; 6 | while(a < b){ 7 | while(a < b && !isLetter(cs[a])) 8 | a++; 9 | while(a < b && !isLetter(cs[b])) 10 | b--; 11 | if(cs[a] != cs[b]) 12 | return false; 13 | a++; 14 | b--; 15 | } 16 | return true; 17 | } 18 | 19 | private boolean isLetter(char c){ 20 | return c >= 'a' && c <= 'z' || c >= '0' && c <= '9'; 21 | } 22 | } -------------------------------------------------------------------------------- /Path Sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean hasPathSum(TreeNode root, int sum) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if(root == null){ 15 | return false; 16 | } else if(root.left == null && root.right == null){ 17 | return root.val == sum; 18 | } 19 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); 20 | } 21 | } -------------------------------------------------------------------------------- /Count and Say.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String countAndSay(int n) { 3 | char[] ori = new char[] { '1' }; 4 | StringBuffer sb = null; 5 | for (int i = 1; i < n; i++) { 6 | sb = new StringBuffer(); 7 | int len = ori.length; 8 | int begin = 0; 9 | for (int j = 1; j <= len; j++) 10 | if (j == len || ori[j] != ori[begin]) { 11 | sb.append("" + (j - begin)); 12 | sb.append(ori[begin]); 13 | begin = j; 14 | } 15 | ori = sb.toString().toCharArray(); 16 | } 17 | return new String(ori); 18 | } 19 | } -------------------------------------------------------------------------------- /Trapping Rain Water.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int trap(int[] A) { 3 | int n = A.length; 4 | int[] maxL = new int[n]; 5 | int[] maxR = new int[n]; 6 | for (int i = 0; i < n; i++) 7 | maxL[i] = i == 0 ? A[i] : Math.max(maxL[i - 1], A[i]); 8 | for (int i = n - 1; i >= 0; i--) 9 | maxR[i] = i == n - 1 ? A[i] : Math.max(maxR[i + 1], A[i]); 10 | 11 | int aSum = 0; 12 | for (int i = 0; i < n; i++) 13 | aSum += A[i]; 14 | 15 | int waterSum = 0; 16 | for (int i = 0; i < n; i++) 17 | waterSum += Math.min(maxL[i], maxR[i]); 18 | return waterSum - aSum; 19 | } 20 | } -------------------------------------------------------------------------------- /Simplify Path.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String simplifyPath(String path) { 3 | String[] paths = path.split("/"); 4 | Stack stack = new Stack(); 5 | for (String s : paths) { 6 | if (s.equals(".")) { 7 | } else if (s.equals("..")) { 8 | if (!stack.isEmpty()) 9 | stack.pop(); 10 | } else if (s.length() > 0) { 11 | stack.push(s); 12 | } 13 | } 14 | StringBuilder sb = new StringBuilder(); 15 | for (String s : stack) 16 | sb.append("/" + s); 17 | if (sb.length() == 0) 18 | sb.append("/"); 19 | return sb.toString(); 20 | } 21 | } -------------------------------------------------------------------------------- /Swap Nodes in Pairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode swapPairs(ListNode head) { 14 | ListNode dummy = new ListNode(0); 15 | dummy.next = head; 16 | ListNode p = dummy; 17 | while(p.next != null && p.next.next != null){ 18 | ListNode q = p.next.next; 19 | p.next.next = q.next; 20 | q.next = p.next; 21 | p.next = q; 22 | p = p.next.next; 23 | } 24 | return dummy.next; 25 | } 26 | } -------------------------------------------------------------------------------- /Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | if(head == null) 15 | return false; 16 | ListNode p = head; 17 | ListNode q = head; 18 | while(q != null){ 19 | p = p.next; 20 | q = q.next; 21 | if(q == null) 22 | return false; 23 | q = q.next; 24 | if(p == q) 25 | return true; 26 | } 27 | return false; 28 | } 29 | } -------------------------------------------------------------------------------- /Shortest Palindrome.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isValidPalindrome(char[] cs, int start, int end) { 3 | while (start < end) { 4 | if (cs[start++] != cs[end--]) return false; 5 | } 6 | return true; 7 | } 8 | 9 | public String shortestPalindrome(String s) { 10 | char[] cs = s.toCharArray(); 11 | int len = cs.length; 12 | int end = len - 1; 13 | for (; end >= 0; --end) { 14 | if (isValidPalindrome(cs, 0, end)) 15 | break; 16 | } 17 | StringBuilder sb = new StringBuilder(); 18 | sb.append(cs, end + 1, len - 1 - end); 19 | sb.reverse(); 20 | sb.append(cs, 0, end + 1); 21 | sb.append(cs, end + 1, len - 1 - end); 22 | return sb.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Container With Most Water.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxArea(int[] height) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int i = 0; 6 | int j = height.length - 1; 7 | int max = 0; 8 | while(j >= i){ 9 | int area = calArea(height, i, j); 10 | if(area > max){ 11 | max = area; 12 | } 13 | if(height[i] < height[j]){ 14 | i++; 15 | }else{ 16 | j--; 17 | } 18 | } 19 | return max; 20 | } 21 | 22 | private int calArea(int[] h, int i, int j){ 23 | return (j - i) * Math.min(h[i], h[j]); 24 | } 25 | } -------------------------------------------------------------------------------- /Distinct Subsequences.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numDistinct(String S, String T) { 3 | int m = S.length(); 4 | int n = T.length(); 5 | int[][] num = new int[m][n]; 6 | for(int i = 0; i < m; i++){ 7 | for(int j = 0; j < n; j++){ 8 | num[i][j] += getNum(num, i - 1, j); 9 | if(S.charAt(i) == T.charAt(j)) 10 | num[i][j] += getNum(num, i - 1, j - 1); 11 | } 12 | } 13 | return getNum(num, m - 1, n - 1); 14 | } 15 | 16 | private int getNum(int[][] num, int i, int j){ 17 | if(j < 0) 18 | return 1; 19 | if(i < 0) 20 | return 0; 21 | return num[i][j]; 22 | } 23 | } -------------------------------------------------------------------------------- /Implement strStr().java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String strStr(String haystack, String needle) { 3 | int index = 0; 4 | String s1 = haystack; 5 | String s2 = needle; 6 | int len1 = s1.length(); 7 | int len2 = s2.length(); 8 | int p = 0; 9 | int q = 0; 10 | boolean founded = false; 11 | while(index <= len1 - len2 && q < len2){ 12 | if(s1.charAt(p) != s2.charAt(q)){ 13 | p = ++index; 14 | q = 0; 15 | }else{ 16 | p++; 17 | q++; 18 | } 19 | } 20 | if(index >= 0 && q == len2) 21 | return haystack.substring(index); 22 | return null; 23 | } 24 | } -------------------------------------------------------------------------------- /Convert Sorted Array to Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode sortedArrayToBST(int[] num) { 12 | return buildTree(num, 0, num.length); 13 | } 14 | 15 | public TreeNode buildTree(int[] num, int start, int end){ 16 | if(end <= start) 17 | return null; 18 | int mid = (start + end) / 2; 19 | TreeNode node = new TreeNode(num[mid]); 20 | node.left = buildTree(num, start, mid); 21 | node.right = buildTree(num, mid + 1, end); 22 | return node; 23 | } 24 | } -------------------------------------------------------------------------------- /Sum Root to Leaf Numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int sumNumbers(TreeNode root) { 12 | return sumNumbers(root, 0); 13 | } 14 | 15 | private int sumNumbers(TreeNode root, int parentSum){ 16 | if(root == null) 17 | return 0; 18 | int nodeSum = parentSum * 10 + root.val; 19 | if(root.left == null && root.right == null) 20 | return nodeSum; 21 | else{ 22 | return sumNumbers(root.left, nodeSum) + sumNumbers(root.right, nodeSum); 23 | } 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /Remove Nth Node From End of List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode removeNthFromEnd(ListNode head, int n) { 14 | ListNode dummy = new ListNode(0); 15 | dummy.next = head; 16 | ListNode p = dummy, q = dummy; 17 | int count = 0; 18 | while(p.next != null){ 19 | if(count >= n) 20 | q = q.next; 21 | p = p.next; 22 | count++; 23 | } 24 | if(q.next != null) 25 | q.next = q.next.next; 26 | return dummy.next; 27 | } 28 | } -------------------------------------------------------------------------------- /Roman to Integer.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int romanToInt(String s) { 3 | Map romans = new HashMap(); 4 | romans.put('I', 1); 5 | romans.put('V', 5); 6 | romans.put('X', 10); 7 | romans.put('L', 50); 8 | romans.put('C', 100); 9 | romans.put('D', 500); 10 | romans.put('M', 1000); 11 | char[] cs = s.toCharArray(); 12 | int num = 0; 13 | int val; 14 | for (int i = 0; i < cs.length; i++) { 15 | val = romans.get(cs[i]); 16 | if (i == cs.length - 1 || romans.get(cs[i + 1]) <= val) { 17 | num += val; 18 | } else { 19 | num -= val; 20 | } 21 | } 22 | return num; 23 | } 24 | } -------------------------------------------------------------------------------- /Rotate Image.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void rotate(int[][] matrix) { 3 | // b[x][y] = a[n-1-y][x] 4 | int n = matrix.length; 5 | int ni = n / 2; 6 | int nj = n / 2; 7 | if(n % 2 == 1) 8 | ni++; 9 | for(int i = 0; i < ni; i++){ 10 | for(int j = 0; j < nj; j++){ 11 | int x = i; 12 | int y = j; 13 | int tmp = matrix[y][x]; 14 | for(int k = 0; k < 3; k++){ 15 | int nx = y; 16 | int ny = n - 1 - x; 17 | matrix[y][x] = matrix[ny][nx]; 18 | x = nx; 19 | y = ny; 20 | } 21 | matrix[y][x] = tmp; 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Candy.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int candy(int[] ratings) { 3 | // min value of the left point of current descending sequence. 4 | int minLeft = 1; 5 | int end = ratings.length; 6 | int sum = 0; 7 | int k = 1; 8 | for (int i = 0; i < end; i++, k++) { 9 | if (i == end - 1 || ratings[i] <= ratings[i + 1]) { 10 | // reach the end of a descending sequence. 11 | sum += Math.max(k, minLeft); 12 | if (i < end - 1 && ratings[i + 1] > ratings[i]) 13 | minLeft = (k == 1 ? minLeft : 1) + 1; 14 | else 15 | minLeft = 1; 16 | k = 0; 17 | } else { 18 | sum += k; 19 | } 20 | } 21 | return sum; 22 | } 23 | } -------------------------------------------------------------------------------- /Divide Two Integers.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private long negative(long a) { 3 | return (a ^ -1) + 1; 4 | } 5 | 6 | public int divide(int dividend, int divisor) { 7 | long a = Math.abs((long) dividend); 8 | long b = Math.abs((long) divisor); 9 | while ((b << 1) <= a) 10 | b <<= 1; 11 | long c = 0; 12 | long absDivisor = Math.abs((long) divisor); 13 | 14 | while (b >= absDivisor) { 15 | c <<= 1; 16 | while (a >= b) { 17 | a -= b; 18 | c += 1; 19 | } 20 | b >>= 1; 21 | } 22 | c = dividend < 0 ? negative(c) : c; 23 | c = divisor < 0 ? negative(c) : c; 24 | c = c > Integer.MAX_VALUE ? Integer.MAX_VALUE : c; 25 | return (int) c; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isValid(String s) { 3 | char[] cs = s.toCharArray(); 4 | Map paraMap = new HashMap(); 5 | paraMap.put('(', ')'); 6 | paraMap.put('[', ']'); 7 | paraMap.put('{', '}'); 8 | 9 | Stack stack = new Stack(); 10 | for(Character c : cs){ 11 | if(paraMap.keySet().contains(c)){ 12 | stack.push(c); 13 | } else if(paraMap.values().contains(c)){ 14 | if(!stack.isEmpty() && paraMap.get(stack.peek()) == c){ 15 | stack.pop(); 16 | } else{ 17 | return false; 18 | } 19 | } 20 | } 21 | return stack.isEmpty(); 22 | } 23 | } -------------------------------------------------------------------------------- /Insertion Sort List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode insertionSortList(ListNode head) { 14 | ListNode dummy = new ListNode(Integer.MIN_VALUE); 15 | 16 | ListNode node = head; 17 | while(node != null){ 18 | ListNode next = node.next; 19 | ListNode prev = dummy; 20 | while(prev.next != null && node.val > prev.next.val){ 21 | prev = prev.next; 22 | } 23 | node.next = prev.next; 24 | prev.next = node; 25 | node = next; 26 | } 27 | return dummy.next; 28 | } 29 | } -------------------------------------------------------------------------------- /Linked List Cycle II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode detectCycle(ListNode head) { 14 | ListNode p = head; 15 | ListNode q = head; 16 | while(q != null){ 17 | p = p.next; 18 | q = q.next; 19 | if(q == null) 20 | return null; 21 | q = q.next; 22 | if(p == q) 23 | break; 24 | } 25 | if(q == null) 26 | return null; 27 | p = head; 28 | while(p != q){ 29 | p = p.next; 30 | q = q.next; 31 | } 32 | return p; 33 | } 34 | } -------------------------------------------------------------------------------- /ZigZag Conversion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String convert(String s, int nRows) { 3 | if (nRows == 1) 4 | return s; 5 | int lens = s.length(); 6 | int blockSize = 2 * nRows - 2; 7 | int blockCount = (lens + blockSize - 1) / blockSize; 8 | StringBuffer buf = new StringBuffer(); 9 | for (int i = 0; i < nRows; i++) { 10 | for (int j = 0; j < blockCount; j++) { 11 | int start = j * blockSize; 12 | int i1 = start + i; 13 | if (i1 < lens) 14 | buf.append(s.charAt(i1)); 15 | int i2 = start + blockSize - i; 16 | if (i2 < lens && i2 < start + blockSize && i2 > i1) 17 | buf.append(s.charAt(i2)); 18 | } 19 | } 20 | return buf.toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /Subsets.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-09-02 3 | */ 4 | public class Solution { 5 | public ArrayList> subsets(int[] S) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | Arrays.sort(S); 9 | ArrayList> result = new ArrayList>(); 10 | allSubsets(S, 0, new LinkedList(), result); 11 | return result; 12 | } 13 | 14 | private void allSubsets(int[] s, int k, LinkedList list, ArrayList> result){ 15 | if(k == s.length){ 16 | result.add(new ArrayList(list)); 17 | return; 18 | } 19 | allSubsets(s, k + 1, list, result); 20 | list.addLast(s[k]); 21 | allSubsets(s, k + 1, list, result); 22 | list.removeLast(); 23 | } 24 | } -------------------------------------------------------------------------------- /Validate Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isValidBST(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | return isValidBst(root, Integer.MIN_VALUE, Integer.MAX_VALUE); 15 | } 16 | 17 | private boolean isValidBst(TreeNode root, int min, int max){ 18 | if(root == null){ 19 | return true; 20 | } else if(root.val <= min || root.val >= max){ 21 | return false; 22 | } else{ 23 | return isValidBst(root.left, min, root.val) && isValidBst(root.right, root.val, max); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Binary Tree Preorder Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList preorderTraversal(TreeNode root) { 12 | ArrayList list = new ArrayList(); 13 | Stack stack = new Stack(); 14 | TreeNode node = root; 15 | while(node != null || !stack.isEmpty()){ 16 | if(node != null){ 17 | list.add(node.val); 18 | if(node.right != null) 19 | stack.push(node.right); 20 | node = node.left; 21 | }else{ 22 | node = stack.pop(); 23 | } 24 | } 25 | return list; 26 | } 27 | } -------------------------------------------------------------------------------- /Longest Common Prefix.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Could also use Trie for longest common prefix in n string. Time is also O(n * m). 3 | * Trie could also used for finding the longest common prefix between any 2 pairs in n strings, cost O(n * m) 4 | */ 5 | public class Solution { 6 | public String longestCommonPrefix(String[] strs) { 7 | if(strs.length == 0) 8 | return ""; 9 | int len = strs[0].length(); 10 | int i = 0; 11 | for(; i < len; i++){ 12 | char c = strs[0].charAt(i); 13 | boolean allSame = true; 14 | for(String s : strs) 15 | if(s.length() <= i || s.charAt(i) != c){ 16 | allSame = false; 17 | break; 18 | } 19 | if(!allSame) 20 | break; 21 | } 22 | return strs[0].substring(0, i); 23 | } 24 | } -------------------------------------------------------------------------------- /Longest Consecutive Sequence.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestConsecutive(int[] num) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | Set set = new HashSet(); 6 | for (int i : num) { 7 | set.add(i); 8 | } 9 | int max = 0; 10 | for (int i : num) { 11 | max = Math.max(max, getCount(set, i)); 12 | } 13 | return max; 14 | } 15 | 16 | private int getCount(Set set, int i) { 17 | int count = 1; 18 | int k = i; 19 | while (set.contains(--k)) { 20 | set.remove(k); 21 | count++; 22 | } 23 | k = i; 24 | while (set.contains(++k)) { 25 | set.remove(k); 26 | count++; 27 | } 28 | return count; 29 | } 30 | } -------------------------------------------------------------------------------- /Symmetric Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isSymmetric(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | if(root == null) 15 | return true; 16 | return isSymmtric(root.left, root.right); 17 | } 18 | 19 | private boolean isSymmtric(TreeNode n1, TreeNode n2){ 20 | if(n1 == null && n2 == null) 21 | return true; 22 | else if(n1 == null || n2 == null) 23 | return false; 24 | else{ 25 | return n1.val == n2.val && isSymmtric(n1.left, n2.right) & isSymmtric(n1.right, n2.left); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /Search a 2D Matrix.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int n = matrix.length; 6 | int m = n > 0 ? matrix[0].length : 0; 7 | return bsearch(matrix, target, 0, n * m); 8 | } 9 | 10 | private boolean bsearch(int[][] matrix, int target, int s, int e){ 11 | if(s == e){ 12 | return false; 13 | } 14 | int n = matrix.length; 15 | int m = n > 0 ? matrix[0].length : 0; 16 | int mid = (s + e) / 2; 17 | int val = matrix[mid / m][mid % m]; 18 | if(target == val) 19 | return true; 20 | else if(target > val) 21 | return bsearch(matrix, target, mid + 1, e); 22 | else 23 | return bsearch(matrix, target, s, mid); 24 | } 25 | } -------------------------------------------------------------------------------- /Balanced Binary Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isBalanced(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | return balanceHeight(root) >= 0; 15 | } 16 | 17 | private int balanceHeight(TreeNode root) { 18 | if (root == null) 19 | return 0; 20 | int left = balanceHeight(root.left); 21 | if (left == -1) 22 | return -1; 23 | int right = balanceHeight(root.right); 24 | if (right == -1) 25 | return -1; 26 | if (Math.abs(right - left) <= 1) { 27 | return Math.max(right, left) + 1; 28 | } else 29 | return -1; 30 | } 31 | } -------------------------------------------------------------------------------- /LRU Cache.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LRUCache { 3 | 4 | private LRUMap mMap; 5 | 6 | public LRUCache(int capacity) { 7 | mMap = new LRUMap(capacity); 8 | } 9 | 10 | public int get(int key) { 11 | if (mMap.containsKey(key)) 12 | return mMap.get(key); 13 | else 14 | return -1; 15 | } 16 | 17 | public void set(int key, int value) { 18 | mMap.put(key, value); 19 | } 20 | 21 | private class LRUMap extends LinkedHashMap { 22 | private int mCapacity; 23 | 24 | public LRUMap(int capacity) { 25 | super(capacity, 0.75f, true); 26 | mCapacity = capacity; 27 | } 28 | 29 | @Override 30 | protected boolean removeEldestEntry( 31 | java.util.Map.Entry eldest) { 32 | return size() > mCapacity; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Binary Tree Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList inorderTraversal(TreeNode root) { 12 | // Start typing your Java solution below 13 | // DO NOT write main() function 14 | ArrayList inorder = new ArrayList(); 15 | Stack stack = new Stack(); 16 | while (!stack.isEmpty() || root != null) { 17 | if (root != null) { 18 | stack.push(root); 19 | root = root.left; 20 | } else { 21 | root = stack.pop(); 22 | inorder.add(root.val); 23 | root = root.right; 24 | } 25 | } 26 | return inorder; 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /Unique Paths II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int[][] grid = obstacleGrid; 6 | int m = grid.length; 7 | int n = m > 0 ? grid[0].length : 0; 8 | int[][] sum = new int[m][n]; 9 | for(int i = 0; i < m; i++){ 10 | for(int j = 0; j < n; j++){ 11 | if(grid[i][j] == 0){ 12 | if(i == 0 && j == 0){ 13 | sum[i][j] = 1; 14 | }else{ 15 | sum[i][j] = (i > 0 ? sum[i - 1][j] : 0) + (j > 0 ? sum[i][j - 1] : 0); 16 | } 17 | } 18 | } 19 | } 20 | if(m == 0 || n == 0){ 21 | return 0; 22 | }else{ 23 | return sum[m - 1][n - 1]; 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Partition List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-31 3 | * Definition for singly-linked list. 4 | * public class ListNode { 5 | * int val; 6 | * ListNode next; 7 | * ListNode(int x) { 8 | * val = x; 9 | * next = null; 10 | * } 11 | * } 12 | */ 13 | public class Solution { 14 | public ListNode partition(ListNode head, int x) { 15 | ListNode left = new ListNode(0); 16 | ListNode right = new ListNode(0); 17 | ListNode lp = left; 18 | ListNode rp = right; 19 | while (head != null) { 20 | if (head.val < x) { 21 | lp.next = head; 22 | lp = lp.next; 23 | } else { 24 | rp.next = head; 25 | rp = rp.next; 26 | } 27 | head = head.next; 28 | lp.next = rp.next = null; 29 | } 30 | 31 | lp.next = right.next; 32 | return left.next; 33 | } 34 | } -------------------------------------------------------------------------------- /Two Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] twoSum(int[] numbers, int target) { 3 | int n = numbers.length; 4 | Map> map = new HashMap>(); 5 | for(int i = 0; i < n; i++){ 6 | int num = numbers[i]; 7 | if(!map.containsKey(num)) 8 | map.put(num, new ArrayList()); 9 | map.get(num).add(i); 10 | } 11 | for(int i = 0; i < n; i++){ 12 | int num = numbers[i]; 13 | if(map.containsKey(target - num)){ 14 | List list = map.get(target - num); 15 | if(num == target - num && list.size() < 2) 16 | continue; 17 | int[] res = new int[]{i + 1, list.get(list.size() - 1) + 1}; 18 | Arrays.sort(res); 19 | return res; 20 | } 21 | } 22 | return null; 23 | } 24 | } -------------------------------------------------------------------------------- /Minimum Path Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minPathSum(int[][] grid) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int leni = grid.length; 6 | if(leni == 0){ 7 | return 0; 8 | } 9 | int lenj = grid[0].length; 10 | int[][] min = new int[leni][lenj]; 11 | 12 | int left; 13 | int top; 14 | for(int i = 0; i < leni; i++){ 15 | for(int j = 0; j < lenj; j++){ 16 | if(i == 0 && j == 0){ 17 | min[i][j] = grid[i][j]; 18 | }else{ 19 | left = i > 0 ? min[i - 1][j] : Integer.MAX_VALUE; 20 | top = j > 0 ? min[i][j - 1] : Integer.MAX_VALUE; 21 | min[i][j] = Math.min(left, top) + grid[i][j]; 22 | } 23 | } 24 | } 25 | return min[leni - 1][lenj - 1]; 26 | } 27 | } -------------------------------------------------------------------------------- /Combination Sum.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> combinationSum(int[] candidates, int target) { 3 | Arrays.sort(candidates); 4 | ArrayList> res = new ArrayList>(); 5 | combination(candidates, 0, target, new ArrayList(), res); 6 | return res; 7 | } 8 | 9 | private void combination(int[] nums, int index, int target, List list, List> res){ 10 | int n = nums.length; 11 | if(index == n){ 12 | if(target == 0) 13 | res.add(new ArrayList(list)); 14 | return; 15 | } 16 | combination(nums, index + 1, target, list, res); 17 | if(target >= nums[index]){ 18 | list.add(nums[index]); 19 | combination(nums, index, target - nums[index], list, res); 20 | list.remove(list.size() - 1); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Combination Sum II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> combinationSum2(int[] num, int target) { 3 | Arrays.sort(num); 4 | Set> set = new HashSet>(); 5 | combination(num, 0, target, new ArrayList(), set); 6 | return new ArrayList>(set); 7 | } 8 | 9 | private void combination(int[] nums, int index, int target, List list, Set> res){ 10 | int n = nums.length; 11 | if(index == n){ 12 | if(target == 0) 13 | res.add(new ArrayList(list)); 14 | return; 15 | } 16 | combination(nums, index + 1, target, list, res); 17 | if(target >= nums[index]){ 18 | list.add(nums[index]); 19 | combination(nums, index + 1, target - nums[index], list, res); 20 | list.remove(list.size() - 1); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Construct Binary Tree from Preorder and Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode buildTree(int[] preorder, int[] inorder) { 12 | return buildTree(inorder, 0, preorder, 0, inorder.length); 13 | } 14 | 15 | private TreeNode buildTree(int[] in, int is, int[] pre, int ps, int len){ 16 | if(len == 0) 17 | return null; 18 | int val = pre[ps]; 19 | int lenLeft = 0; 20 | for(;lenLeft < len; lenLeft++) 21 | if(in[is + lenLeft] == val) 22 | break; 23 | TreeNode node = new TreeNode(val); 24 | node.left = buildTree(in, is, pre, ps + 1, lenLeft); 25 | node.right = buildTree(in, is + lenLeft + 1, pre, ps + 1 + lenLeft, len - 1 - lenLeft); 26 | return node; 27 | } 28 | } -------------------------------------------------------------------------------- /N-Queens II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-30 3 | */ 4 | public class Solution { 5 | public int totalNQueens(int n) { 6 | return solveNQ(n, 0, new int[n]); 7 | } 8 | 9 | private int solveNQ(int n, int row, int[] queens) { 10 | if (row == n) 11 | return 1; 12 | int sum = 0; 13 | for (int col = 0; col < n; col++) 14 | if (fit(n, queens, row, col)) { 15 | queens[row] = col; 16 | sum += solveNQ(n, row + 1, queens); 17 | } 18 | return sum; 19 | } 20 | 21 | private boolean fit(int n, int[] queens, int row, int col) { 22 | int leftTop = col; 23 | int rightTop = col; 24 | for (int i = row - 1; i >= 0; i--) { 25 | leftTop--; 26 | rightTop++; 27 | if (queens[i] == col || queens[i] == leftTop 28 | || queens[i] == rightTop) 29 | return false; 30 | } 31 | return true; 32 | } 33 | } -------------------------------------------------------------------------------- /Jump Game.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time:2013-08-28 3 | */ 4 | public class Solution { 5 | public boolean canJump(int[] A) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | int n = A.length; 9 | int maxStep = 0; 10 | for(int i = 0; i < n; i++){ 11 | if(maxStep >= n - 1) 12 | return true; 13 | if(i > maxStep) 14 | return false; 15 | maxStep = Math.max(i + A[i], maxStep); 16 | } 17 | return true; 18 | } 19 | } 20 | 21 | public class Solution { 22 | public boolean canJump(int[] A) { 23 | // Start typing your Java solution below 24 | // DO NOT write main() function 25 | int len = A.length; 26 | int minJump = len - 1; 27 | for (int i = len - 2; i >= 0; i--) { 28 | if (A[i] >= minJump - i) { 29 | minJump = i; 30 | } 31 | } 32 | return minJump == 0; 33 | } 34 | } -------------------------------------------------------------------------------- /Construct Binary Tree from Inorder and Postorder Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public TreeNode buildTree(int[] inorder, int[] postorder) { 12 | return buildTree(inorder, 0, postorder, 0, inorder.length); 13 | } 14 | 15 | private TreeNode buildTree(int[] in, int is, int[] post, int ps, int len){ 16 | if(len == 0) 17 | return null; 18 | int val = post[ps + len - 1]; 19 | int lenLeft = 0; 20 | for(;lenLeft < len; lenLeft++) 21 | if(in[is + lenLeft] == val) 22 | break; 23 | TreeNode node = new TreeNode(val); 24 | node.left = buildTree(in, is, post, ps, lenLeft); 25 | node.right = buildTree(in, is + lenLeft + 1, post, ps + lenLeft, len - 1 - lenLeft); 26 | return node; 27 | } 28 | } -------------------------------------------------------------------------------- /Merge Intervals.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * public class Interval { 4 | * int start; 5 | * int end; 6 | * Interval() { start = 0; end = 0; } 7 | * Interval(int s, int e) { start = s; end = e; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList merge(ArrayList intervals) { 12 | Collections.sort(intervals, new Comparator(){ 13 | public int compare(Interval a, Interval b){ 14 | return a.start - b.start; 15 | } 16 | }); 17 | 18 | ArrayList result = new ArrayList(); 19 | Interval cur = null; 20 | for(Interval i : intervals){ 21 | if(cur == null || cur.end < i.start){ 22 | cur = new Interval(i.start, i.end); 23 | result.add(cur); 24 | } else { 25 | cur.end = Math.max(cur.end, i.end); 26 | } 27 | } 28 | return result; 29 | } 30 | } -------------------------------------------------------------------------------- /Reverse Linked List II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode reverseBetween(ListNode head, int m, int n) { 14 | ListNode dummy = new ListNode(0); 15 | dummy.next = head; 16 | ListNode p = dummy; 17 | for(int i = 1; i < m; i++) 18 | p = p.next; 19 | 20 | p.next = reverse(p.next, n - m + 1); 21 | return dummy.next; 22 | } 23 | 24 | private ListNode reverse(ListNode head, int n){ 25 | ListNode node = head, prev = null, next = null; 26 | for(int i = 0; i < n; i++){ 27 | next = node.next; 28 | node.next = prev; 29 | prev = node; 30 | node = next; 31 | } 32 | head.next = node; 33 | return prev; 34 | } 35 | } -------------------------------------------------------------------------------- /Largest Rectangle in Histogram.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int largestRectangleArea(int[] height) { 3 | int n = height.length; 4 | int stackTop = 0; 5 | int[] hStack = new int[n]; 6 | int[] bStack = new int[n]; 7 | 8 | int maxArea = 0; 9 | for(int i = 0; i <= n; i++){ 10 | int bigItemsCount = 0; 11 | while(stackTop > 0 &&(i == n || hStack[stackTop - 1] >= height[i])){ 12 | // pop the stack top to main the ascending order in hStack. 13 | stackTop--; 14 | int h = hStack[stackTop]; 15 | bigItemsCount += bStack[stackTop]; 16 | maxArea = Math.max(maxArea, h * bigItemsCount); 17 | } 18 | if(i < n){ 19 | // insert the new item to stack 20 | hStack[stackTop] = height[i]; 21 | bStack[stackTop++] = bigItemsCount + 1; 22 | } 23 | } 24 | 25 | return maxArea; 26 | } 27 | } -------------------------------------------------------------------------------- /Permutation Sequence.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-31 3 | */ 4 | public class Solution { 5 | public String getPermutation(int n, int k) { 6 | k = k - 1; 7 | StringBuffer result = new StringBuffer(); 8 | List nums = new ArrayList(); 9 | for (int i = 1; i <= n; i++) 10 | nums.add(i); 11 | int[] fac = getFacArray(n); 12 | for (int i = 0; i < n; i++) { 13 | // choose one digit in each iteration. 14 | int d = k / fac[n - 1 - i]; 15 | k = k % fac[n - 1 - i]; 16 | result.append(nums.get(d)); 17 | nums.remove(d); 18 | } 19 | return result.toString(); 20 | } 21 | 22 | private int[] getFacArray(int n) { 23 | int[] fac = new int[n]; 24 | for (int i = 0; i < n; i++) { 25 | if (i == 0) 26 | fac[i] = 1; 27 | else { 28 | fac[i] = fac[i - 1] * i; 29 | } 30 | } 31 | return fac; 32 | } 33 | } -------------------------------------------------------------------------------- /Longest Palindromic Substring.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-29 3 | * time cost: O(n^2) 4 | */ 5 | public class Solution { 6 | public String longestPalindrome(String s) { 7 | char[] cs = s.toCharArray(); 8 | int n = cs.length; 9 | 10 | int maxLen = 0; 11 | int maxI = 0; 12 | 13 | for(int i = 0; i < n; i++){ 14 | for(int offset = 0; offset <= 1; offset++){ 15 | int left = i; 16 | int right = i + offset; 17 | 18 | while(left >= 0 && right < n && cs[left] == cs[right]){ 19 | left--; 20 | right++; 21 | } 22 | left++; 23 | right--; 24 | int len = right - left + 1; 25 | if(len > maxLen){ 26 | maxLen = len; 27 | maxI = left; 28 | } 29 | } 30 | } 31 | return s.substring(maxI, maxI + maxLen); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int climbStairs(int n) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | if(n < 2){ 6 | return 1; 7 | } 8 | 9 | int[] steps = new int[n + 1]; 10 | steps[0] = 1; 11 | steps[1] = 1; 12 | for(int i = 2; i <= n; i++){ 13 | steps[i] = steps[i - 1] + steps[i - 2]; 14 | } 15 | return steps[n]; 16 | } 17 | } 18 | /** 19 | * @time: 2013-08-27 20 | */ 21 | public class Solution { 22 | public int climbStairs(int n) { 23 | // Start typing your Java solution below 24 | // DO NOT write main() function 25 | if(n == 0) 26 | return 0; 27 | else if(n == 1) 28 | return 1; 29 | int a0 = 1; 30 | int a1 = 1; 31 | for(int i = 2; i <= n; i++){ 32 | int a = a0 + a1; 33 | a0 = a1; 34 | a1 = a; 35 | } 36 | return a1; 37 | } 38 | } -------------------------------------------------------------------------------- /String to Integer (atoi).java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int atoi(String str) { 3 | if (str == null) 4 | return 0; 5 | str = str.trim(); 6 | char[] cs = str.toCharArray(); 7 | int n = cs.length; 8 | int index = 0; 9 | int flag = 1; 10 | if (n > 0 && (cs[0] == '-' || cs[0] == '+')) { 11 | flag = cs[0] == '-' ? -1 : 1; 12 | index++; 13 | } 14 | long val = 0; 15 | for (; index < n; index++) { 16 | if (!Character.isDigit(cs[index])) { 17 | break; 18 | } else { 19 | val *= 10; 20 | val += cs[index] - '0'; 21 | if (flag == 1 && val > Integer.MAX_VALUE) { 22 | return Integer.MAX_VALUE; 23 | } else if (flag == -1 && val * flag < Integer.MIN_VALUE) { 24 | return Integer.MIN_VALUE; 25 | } 26 | } 27 | } 28 | return (int) (val * flag); 29 | } 30 | } -------------------------------------------------------------------------------- /Path Sum II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList> pathSum(TreeNode root, int sum) { 12 | ArrayList> res = new ArrayList>(); 13 | pathSum(root, sum, res, new ArrayList()); 14 | return res; 15 | } 16 | 17 | private void pathSum(TreeNode root, int sum, ArrayList> res, ArrayList list){ 18 | if(root == null) 19 | return; 20 | list.add(root.val); 21 | sum -= root.val; 22 | if(root.left == null && root.right == null && sum == 0) 23 | res.add(new ArrayList(list)); 24 | else{ 25 | pathSum(root.left, sum, res, list); 26 | pathSum(root.right, sum, res, list); 27 | } 28 | list.remove(list.size() - 1); 29 | } 30 | } -------------------------------------------------------------------------------- /Jump Game II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int jump(int[] A) { 3 | int n = A.length; 4 | int start = 0; 5 | int end = 0; 6 | int step = 0; 7 | while(start <= end){ 8 | if(end >= n - 1) 9 | break; 10 | step++; 11 | int maxReach = 0; 12 | for(int i = start; i <= end; i++) 13 | maxReach = Math.max(maxReach, i + A[i]); 14 | start = end + 1; 15 | end = maxReach; 16 | } 17 | return step; 18 | } 19 | } 20 | 21 | public class Solution { 22 | public int jump(int[] A) { 23 | int len = A.length; 24 | if(len == 0) 25 | return 0; 26 | int[] n = new int[len]; 27 | n[0] = 0; 28 | int min; 29 | int maxL = 0; 30 | for(int i = 0; i < len; i++){ 31 | for(int j = maxL + 1; j <= i + A[i] && j < len; j++) 32 | n[j] = n[i] + 1; 33 | maxL = Math.max(maxL, i + A[i]); 34 | } 35 | return n[len - 1]; 36 | } 37 | } -------------------------------------------------------------------------------- /Longest Substring Without Repeating Characters.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-29 3 | * time complexity: O(n) 4 | */ 5 | public class Solution { 6 | public int lengthOfLongestSubstring(String s) { 7 | int n = s.length(); 8 | Map posMap = new HashMap(); 9 | // subStart[i] = the start pos of longest substring end at i 10 | int[] subStart = new int[n]; 11 | int maxLen = 0; 12 | for(int i = 0; i < n; i++){ 13 | char c = s.charAt(i); 14 | if(!posMap.containsKey(c)){ 15 | subStart[i] = i > 0 ? subStart[i - 1] : 0; 16 | } else { 17 | int lastPos = posMap.get(c); 18 | subStart[i] = lastPos + 1; 19 | // Clear removed character. 20 | for(int j = subStart[i - 1]; j < subStart[i]; j++) 21 | posMap.remove(s.charAt(j)); 22 | } 23 | posMap.put(c, i); 24 | maxLen = Math.max(maxLen, i - subStart[i] + 1); 25 | } 26 | return maxLen; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Rotate List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode rotateRight(ListNode head, int n) { 14 | if(head == null) 15 | return null; 16 | ListNode dummy = new ListNode(0); 17 | dummy.next = head; 18 | int len = listLen(head); 19 | n %= len; 20 | ListNode p = dummy, q = dummy; 21 | int i = 0; 22 | while(q.next != null){ 23 | if(i >= n) 24 | p = p.next; 25 | q = q.next; 26 | i++; 27 | } 28 | q.next = dummy.next; 29 | dummy.next = p.next; 30 | p.next = null; 31 | return dummy.next; 32 | } 33 | 34 | private int listLen(ListNode p){ 35 | int len = 0; 36 | while(p != null){ 37 | len++; 38 | p = p.next; 39 | } 40 | return len; 41 | } 42 | } -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode deleteDuplicates(ListNode head) { 14 | ListNode p1; 15 | p1 = head; 16 | while (p1 != null) { 17 | if (p1.next != null && p1.val == p1.next.val) { 18 | p1.next = p1.next.next; 19 | } else { 20 | p1 = p1.next; 21 | } 22 | } 23 | return head; 24 | } 25 | } 26 | 27 | 28 | public class Solution { 29 | public ListNode deleteDuplicates(ListNode head) { 30 | ListNode p1 = head; 31 | ListNode p2 = head; 32 | while(p2 != null){ 33 | if(p2.val != p1.val){ 34 | p1.next = p2; 35 | p1 = p1.next; 36 | } 37 | p2 = p2.next; 38 | p1.next = null; 39 | } 40 | return head; 41 | } 42 | } -------------------------------------------------------------------------------- /Evaluate Reverse Polish Notation.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | static String[] ARITHS = new String[]{"+", "-", "*", "/"}; 3 | public int evalRPN(String[] tokens) { 4 | Stack stack = new Stack(); 5 | for(String token : tokens){ 6 | if(isArith(token)){ 7 | int y = Integer.parseInt(stack.pop()); 8 | int x = Integer.parseInt(stack.pop()); 9 | int z = 0; 10 | if(token.equals("+")) 11 | z = x + y; 12 | else if(token.equals("-")) 13 | z = x - y; 14 | else if(token.equals("*")) 15 | z = x * y; 16 | else 17 | z = x / y; 18 | stack.push("" + z); 19 | } else{ 20 | stack.push(token); 21 | } 22 | } 23 | return Integer.parseInt(stack.pop()); 24 | } 25 | 26 | private boolean isArith(String s){ 27 | for(String arith : ARITHS) 28 | if(arith.equals(s)) 29 | return true; 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Edit Distance.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minDistance(String word1, String word2) { 3 | char[] cs1 = word1.toCharArray(); 4 | char[] cs2 = word2.toCharArray(); 5 | int len1 = cs1.length; 6 | int len2 = cs2.length; 7 | int[][] minDis = new int[len1][len2]; 8 | for(int i = 0; i < len1; i++){ 9 | for(int j = 0; j < len2; j++){ 10 | int dis = Integer.MAX_VALUE; 11 | // Delete cs1[i] 12 | dis = Math.min(dis, dist(minDis, i - 1, j) + 1); 13 | // Insert cs2[j] to cs1[i + 1] 14 | dis = Math.min(dis, dist(minDis, i, j - 1) + 1); 15 | // Replace cs1[i] to cs2[j] 16 | dis = Math.min(dis, dist(minDis, i - 1, j - 1) + (cs1[i] == cs2[j] ? 0 : 1)); 17 | minDis[i][j] = dis; 18 | } 19 | } 20 | return dist(minDis, len1 - 1, len2 - 1); 21 | } 22 | 23 | private int dist(int[][] min, int i, int j){ 24 | if(i < 0) 25 | return j + 1; 26 | else if(j < 0) 27 | return i + 1; 28 | else 29 | return min[i][j]; 30 | } 31 | } -------------------------------------------------------------------------------- /Next Permutation.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void nextPermutation(int[] num) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int n = num.length; 6 | int descI = n - 1; 7 | // find the top index of the last desc sub array . 8 | for (; descI > 0 && num[descI - 1] >= num[descI]; descI--) 9 | ; 10 | // find the min value in sub array which is bigger than num[descI - 1] 11 | // and swap them. 12 | if (descI > 0) { 13 | for (int i = n - 1; i >= descI; i--) { 14 | if (num[i] > num[descI - 1]) { 15 | swap(num, i, descI - 1); 16 | break; 17 | } 18 | } 19 | } 20 | 21 | // reverse the sub array. 22 | reverse(num, descI, n - 1); 23 | } 24 | 25 | private void reverse(int[] n, int a, int b) { 26 | while (a < b) { 27 | swap(n, a++, b--); 28 | } 29 | } 30 | 31 | private void swap(int[] n, int a, int b) { 32 | int tmp; 33 | tmp = n[b]; 34 | n[b] = n[a]; 35 | n[a] = tmp; 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /Word Search.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean exist(char[][] board, String word) { 3 | int n = board.length; 4 | int m = n > 0 ? board[0].length : 0; 5 | for(int x = 0; x < n; x++){ 6 | for(int y = 0; y < m; y++){ 7 | if(searchWord(board, x, y, word, 0)) 8 | return true; 9 | } 10 | } 11 | return false; 12 | } 13 | 14 | private static final int[][] DIRS = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 15 | 16 | private boolean searchWord(char[][] board, int x, int y, String word, int wi){ 17 | if(wi == word.length()) 18 | return true; 19 | int n = board.length; 20 | int m = n > 0 ? board[0].length : 0; 21 | if(x < 0 || y < 0 || x >= n || y >= m) 22 | return false; 23 | if(board[x][y] != word.charAt(wi)) 24 | return false; 25 | board[x][y] = 0; 26 | for(int[] dir : DIRS){ 27 | if(searchWord(board, x + dir[0], y + dir[1], word, wi + 1)) 28 | return true; 29 | } 30 | board[x][y] = word.charAt(wi); 31 | return false; 32 | } 33 | } -------------------------------------------------------------------------------- /Unique Binary Search Trees II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; left = null; right = null; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList generateTrees(int n) { 12 | return generateTrees(n, 1); 13 | } 14 | 15 | public ArrayList generateTrees(int n, int start) { 16 | ArrayList result = new ArrayList(); 17 | if(n == 0){ 18 | result.add(null); 19 | return result; 20 | } 21 | for(int i = start; i < start + n; i++){ 22 | List left = generateTrees(i - start, start); 23 | List right = generateTrees(n + start - i - 1, i + 1); 24 | for(TreeNode l : left){ 25 | for(TreeNode r : right){ 26 | TreeNode root = new TreeNode(i); 27 | root.left = l; 28 | root.right = r; 29 | result.add(root); 30 | } 31 | } 32 | } 33 | return result; 34 | } 35 | } -------------------------------------------------------------------------------- /Sudoku Solver.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | static final int N = 9; 3 | 4 | public void solveSudoku(char[][] board) { 5 | solveSudoku(board, 0); 6 | } 7 | 8 | private boolean solveSudoku(char[][] board, int n) { 9 | if (n == N * N) 10 | return true; 11 | int x = n / N; 12 | int y = n % N; 13 | if (board[x][y] != '.') 14 | return solveSudoku(board, n + 1); 15 | int xi, yi; 16 | int[] choices = new int[N]; 17 | for (int i = 0; i < N; i++) { 18 | if (board[x][i] != '.') 19 | choices[board[x][i] - '1'] = 1; 20 | if (board[i][y] != '.') 21 | choices[board[i][y] - '1'] = 1; 22 | xi = x / 3 * 3 + i / 3; 23 | yi = y / 3 * 3 + i % 3; 24 | if (board[xi][yi] != '.') 25 | choices[board[xi][yi] - '1'] = 1; 26 | } 27 | for (int i = 0; i < N; i++) 28 | if (choices[i] == 0) { 29 | board[x][y] = (char) ('1' + i); 30 | if (solveSudoku(board, n + 1)) 31 | return true; 32 | board[x][y] = '.'; 33 | } 34 | return false; 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /Plus One.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] plusOne(int[] digits) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | int len = digits.length; 6 | int[] res = new int[len + 1]; 7 | reverse(digits, 0, len - 1); 8 | int[] one = new int[]{1}; 9 | 10 | plus(digits, one, res); 11 | reverse(res, 0, res.length - 1); 12 | if(res[0] == 0){ 13 | int[] tmp = new int[len]; 14 | System.arraycopy(res, 1, tmp, 0, len); 15 | res = tmp; 16 | } 17 | return res; 18 | } 19 | 20 | public void plus(int[] a, int[] b, int[] c){ 21 | int lena = a.length; 22 | int lenb = b.length; 23 | for(int i = 0; i < lena; i++){ 24 | c[i] += a[i] + (i < lenb ? b[i] : 0); 25 | c[i + 1] += c[i] / 10; 26 | c[i] %= 10; 27 | } 28 | } 29 | 30 | public void reverse(int[] n, int s, int e){ 31 | for(; s < e; s++, e--){ 32 | swap(n, s, e); 33 | } 34 | } 35 | 36 | public void swap(int[] n, int i, int j){ 37 | int tmp = n[i]; 38 | n[i] = n[j]; 39 | n[j] = tmp; 40 | } 41 | } -------------------------------------------------------------------------------- /Letter Combinations of a Phone Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | static Map letterMap = new HashMap(); 3 | static{ 4 | letterMap.put('1', ""); 5 | letterMap.put('2', "abc"); 6 | letterMap.put('3', "def"); 7 | letterMap.put('4', "ghi"); 8 | letterMap.put('5', "jkl"); 9 | letterMap.put('6', "mno"); 10 | letterMap.put('7', "pqrs"); 11 | letterMap.put('8', "tuv"); 12 | letterMap.put('9', "wxyz"); 13 | } 14 | 15 | public ArrayList letterCombinations(String digits) { 16 | char[] cs = new char[digits.length()]; 17 | ArrayList res = new ArrayList(); 18 | appendDigits(digits, 0, cs, res); 19 | return res; 20 | } 21 | 22 | private void appendDigits(String digits, int i, char[] cs, ArrayList res){ 23 | if(i == digits.length()){ 24 | res.add(new String(cs)); 25 | return; 26 | } 27 | String letters = letterMap.get(digits.charAt(i)); 28 | for(int j = 0; j < letters.length(); j++){ 29 | cs[i] = letters.charAt(j); 30 | appendDigits(digits, i + 1, cs, res); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Merge k Sorted Lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Use a PriorityQueue(a min heap) to solve this. O(n * k * log(k)) 3 | * 4 | * Definition for singly-linked list. 5 | * public class ListNode { 6 | * int val; 7 | * ListNode next; 8 | * ListNode(int x) { 9 | * val = x; 10 | * next = null; 11 | * } 12 | * } 13 | */ 14 | public class Solution { 15 | public ListNode mergeKLists(ArrayList lists) { 16 | int n = Math.max(lists.size(), 1); 17 | PriorityQueue pq = new PriorityQueue(n, 18 | new Comparator() { 19 | public int compare(ListNode a, ListNode b) { 20 | return a.val - b.val; 21 | } 22 | }); 23 | 24 | for (ListNode node : lists) 25 | if (node != null) 26 | pq.offer(node); 27 | 28 | ListNode dummy = new ListNode(0); 29 | ListNode p = dummy; 30 | while (!pq.isEmpty()) { 31 | ListNode minNode = pq.poll(); 32 | if (minNode.next != null) 33 | pq.offer(minNode.next); 34 | p.next = minNode; 35 | p = p.next; 36 | } 37 | return dummy.next; 38 | } 39 | } -------------------------------------------------------------------------------- /Binary Tree Postorder Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList postorderTraversal(TreeNode root) { 12 | TreeNode last = null; 13 | TreeNode node = null; 14 | ArrayList list = new ArrayList(); 15 | Stack stack = new Stack(); 16 | if(root != null) 17 | stack.push(root); 18 | while(!stack.isEmpty()){ 19 | node = stack.peek(); 20 | if(last == null || last.left == node || last.right == node){ 21 | if(node.left != null) 22 | stack.push(node.left); 23 | else if(node.right != null) 24 | stack.push(node.right); 25 | } else if(node.left == last){ 26 | if(node.right != null) 27 | stack.push(node.right); 28 | } else{ 29 | node = stack.pop(); 30 | list.add(node.val); 31 | } 32 | last = node; 33 | } 34 | return list; 35 | } 36 | } -------------------------------------------------------------------------------- /Minimum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int minDepth(TreeNode root) { 12 | if(root == null) 13 | return 0; 14 | if(root.left == null && root.right == null) 15 | return 1; 16 | int minD = Integer.MAX_VALUE; 17 | if(root.left != null) 18 | minD = Math.min(minD, minDepth(root.left) + 1); 19 | if(root.right != null) 20 | minD = Math.min(minD, minDepth(root.right) + 1); 21 | return minD; 22 | } 23 | } 24 | 25 | public class Solution { 26 | public int minDepth(TreeNode root) { 27 | if(root == null){ 28 | return 0; 29 | }else{ 30 | return depth(root); 31 | } 32 | } 33 | 34 | private int depth(TreeNode root){ 35 | if (root == null) { 36 | return Integer.MAX_VALUE; 37 | } else if (root.left == null && root.right == null) { 38 | return 1; 39 | } else { 40 | return Math.min(depth(root.left), depth(root.right)) + 1; 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Reverse Words in a String.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private void swap(char[] cs, int i, int j) { 3 | char tmp = cs[i]; 4 | cs[i] = cs[j]; 5 | cs[j] = tmp; 6 | } 7 | 8 | private void reverse(char[] cs, int start, int end) { 9 | int i = start; 10 | int j = end - 1; 11 | for (;i < j; i++, j--) { 12 | swap(cs, i, j); 13 | } 14 | } 15 | 16 | private int removeSpace (char[] cs) { 17 | int j = 0; 18 | for (int i = 0; i < cs.length; i++) { 19 | if (cs[i] == ' ' && (i == 0 || cs[i - 1] == ' ')) { 20 | continue; 21 | } else { 22 | cs[j] = cs[i]; 23 | j++; 24 | } 25 | } 26 | return j; 27 | } 28 | 29 | public String reverseWords(String s) { 30 | char[] cs = s.toCharArray(); 31 | int len = removeSpace(cs); 32 | reverse(cs, 0, len); 33 | int wordStart = 0; 34 | for (int i = 0; i <= len; i++) { 35 | if (i == len || cs[i] == ' ') { 36 | reverse(cs, wordStart, i); 37 | wordStart = i + 1; 38 | } 39 | } 40 | String res = new String(cs, 0, len); 41 | return res.trim(); 42 | } 43 | } 44 | 45 | -------------------------------------------------------------------------------- /Reverse Nodes in k-Group.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode reverseKGroup(ListNode head, int k) { 14 | int len = listLen(head); 15 | ListNode dummy = new ListNode(0); 16 | dummy.next = head; 17 | ListNode p = dummy; 18 | for(int i = 0; i < len / k; i++){ 19 | ListNode q = reverse(p.next, k); 20 | ListNode next = p.next; 21 | p.next = q; 22 | p = next; 23 | } 24 | return dummy.next; 25 | } 26 | 27 | private int listLen(ListNode p){ 28 | int len = 0; 29 | while(p != null){ 30 | len++; 31 | p = p.next; 32 | } 33 | return len; 34 | } 35 | 36 | private ListNode reverse(ListNode head, int n){ 37 | ListNode node = head, prev = null, next = null; 38 | for(int i = 0; i < n; i++){ 39 | next = node.next; 40 | node.next = prev; 41 | prev = node; 42 | node = next; 43 | } 44 | head.next = node; 45 | return prev; 46 | } 47 | } -------------------------------------------------------------------------------- /Unique Paths.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-09-02 3 | */ 4 | public class Solution { 5 | public int uniquePaths(int m, int n) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | long x = Math.min(m, n) - 1; 9 | long y = Math.max(m, n) - 1; 10 | 11 | long ways = 1; 12 | // return (x+y)! / x! / y! 13 | for(long i = y + 1; i <= x + y; i++){ 14 | ways *= i; 15 | } 16 | for(long i = 1; i <= x; i++){ 17 | ways /= i; 18 | } 19 | return (int)ways; 20 | } 21 | } 22 | 23 | public class Solution { 24 | public int uniquePaths(int m, int n) { 25 | // Start typing your Java solution below 26 | // DO NOT write main() function 27 | int[][] sum = new int[m][n]; 28 | for(int i = 0; i < m; i++){ 29 | for(int j = 0; j < n; j++){ 30 | if(i == 0 && j == 0){ 31 | sum[i][j] = 1; 32 | }else{ 33 | sum[i][j] = (i > 0 ? sum[i - 1][j] : 0) + (j > 0 ? sum[i][j - 1] : 0); 34 | } 35 | } 36 | } 37 | if(m == 0 || n == 0){ 38 | return 0; 39 | }else{ 40 | return sum[m - 1][n - 1]; 41 | } 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Search in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-09-01 3 | * O(log(n)) 4 | */ 5 | public class Solution { 6 | public int search(int[] A, int target) { 7 | int n = A.length; 8 | int offset = searchOffset(A, 0, n); 9 | int res = bsearch(A, target, 0, n, offset); 10 | if(res != -1) 11 | res = (res + offset) % n; 12 | return res; 13 | } 14 | 15 | private int searchOffset(int[] a, int s, int e) { 16 | int len = e - s; 17 | if (len <= 1 || a[s] < a[e - 1]) 18 | return s; 19 | 20 | int mid = (s + e - 1) / 2; 21 | if (a[s] > a[mid]) 22 | return searchOffset(a, s, mid + 1); 23 | else 24 | // a[mid] >= a[e - 1] 25 | return searchOffset(a, mid + 1, e); 26 | } 27 | 28 | private int bsearch(int[] a, int target, int s, int e, int offset) { 29 | if (s == e) 30 | return - 1; 31 | int n = a.length; 32 | int mid = (s + e) / 2; 33 | int midVal = a[(mid + offset) % n]; 34 | if (midVal == target) { 35 | return mid; 36 | } else if (target > midVal) { 37 | return bsearch(a, target, mid + 1, e, offset); 38 | } else { 39 | return bsearch(a, target, s, mid, offset); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Clone Graph.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for undirected graph. 3 | * class UndirectedGraphNode { 4 | * int label; 5 | * ArrayList neighbors; 6 | * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); } 7 | * }; 8 | */ 9 | public class Solution { 10 | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { 11 | // Note: The Solution object is instantiated only once and is reused by each test case. 12 | if(node == null) 13 | return null; 14 | Map map = new HashMap(); 15 | return cloneGraph(node, map); 16 | } 17 | 18 | private UndirectedGraphNode cloneGraph(UndirectedGraphNode node, Map map){ 19 | if(node == null) 20 | return null; 21 | if(map.containsKey(node)){ 22 | return map.get(node); 23 | } else { 24 | UndirectedGraphNode cloneNode = new UndirectedGraphNode(node.label); 25 | map.put(node, cloneNode); 26 | for(UndirectedGraphNode nei : node.neighbors){ 27 | cloneNode.neighbors.add(cloneGraph(nei, map)); 28 | } 29 | return cloneNode; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Convert Sorted List to Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; next = null; } 7 | * } 8 | */ 9 | /** 10 | * Definition for binary tree 11 | * public class TreeNode { 12 | * int val; 13 | * TreeNode left; 14 | * TreeNode right; 15 | * TreeNode(int x) { val = x; } 16 | * } 17 | */ 18 | public class Solution { 19 | public TreeNode sortedListToBST(ListNode head) { 20 | int len = length(head); 21 | ListNode dummy = new ListNode(0); 22 | dummy.next = head; 23 | return buildTree(dummy, len); 24 | } 25 | 26 | private TreeNode buildTree(ListNode dummy, int len){ 27 | if(dummy.next == null || len <= 0) 28 | return null; 29 | int leftLen = len / 2; 30 | TreeNode node = new TreeNode(0); 31 | node.left = buildTree(dummy, leftLen); 32 | node.val = dummy.next.val; 33 | dummy.next = dummy.next.next; 34 | node.right = buildTree(dummy, len - leftLen - 1); 35 | return node; 36 | } 37 | 38 | private int length(ListNode root){ 39 | int len = 0; 40 | while(root != null){ 41 | len++; 42 | root = root.next; 43 | } 44 | return len; 45 | } 46 | } -------------------------------------------------------------------------------- /N-Queens.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList solveNQueens(int n) { 3 | ArrayList res = new ArrayList(); 4 | solveNQ(n, 0, new int[n], res); 5 | return res; 6 | } 7 | 8 | private void solveNQ(int n, int row, int[] queens, ArrayList res){ 9 | if(row == n){ 10 | String[] strs = new String[n]; 11 | char[] arr = new char[n]; 12 | Arrays.fill(arr, '.'); 13 | for(int i = 0; i < n; i++){ 14 | arr[queens[i]] = 'Q'; 15 | strs[i] = new String(arr); 16 | arr[queens[i]] = '.'; 17 | } 18 | res.add(strs); 19 | return; 20 | } 21 | for(int col = 0; col < n; col++){ 22 | if(fit(n, queens, row, col)){ 23 | queens[row] = col; 24 | solveNQ(n, row + 1, queens, res); 25 | } 26 | } 27 | } 28 | 29 | private boolean fit(int n, int[] queens, int row, int col){ 30 | int leftTop = col; 31 | int rightTop = col; 32 | for(int i = row - 1; i >= 0; i--){ 33 | leftTop--; 34 | rightTop++; 35 | if(queens[i] == col || queens[i] == leftTop || queens[i] == rightTop) 36 | return false; 37 | } 38 | return true; 39 | } 40 | } -------------------------------------------------------------------------------- /Palindrome Partitioning II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minCut(String s) { 3 | int n = s.length(); 4 | // Use dp to get all the palindrome 5 | ArrayList> prevsList = new ArrayList>(); 6 | for (int i = 0; i < n; i++) { 7 | ArrayList curPrevs = new ArrayList(); 8 | prevsList.add(curPrevs); 9 | curPrevs.add(i); 10 | if (i > 0) { 11 | if (s.charAt(i - 1) == s.charAt(i)) 12 | curPrevs.add(i - 1); 13 | for (int prev : prevsList.get(i - 1)) { 14 | if (prev > 0 && s.charAt(prev - 1) == s.charAt(i)) 15 | curPrevs.add(prev - 1); 16 | } 17 | } 18 | } 19 | // Use dp to get the min dist. could also use bfs. 20 | int[] minCuts = new int[n]; 21 | int min; 22 | for (int i = 0; i < n; i++) { 23 | min = Integer.MAX_VALUE; 24 | for (int prevIndex : prevsList.get(i)) { 25 | if (prevIndex > 0) { 26 | min = Math.min(min, minCuts[prevIndex - 1] + 1); 27 | } else { 28 | min = 0; 29 | } 30 | } 31 | minCuts[i] = min; 32 | } 33 | return minCuts[n - 1]; 34 | } 35 | } -------------------------------------------------------------------------------- /Max Points on a Line.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a point. 3 | * class Point { 4 | * int x; 5 | * int y; 6 | * Point() { x = 0; y = 0; } 7 | * Point(int a, int b) { x = a; y = b; } 8 | * } 9 | */ 10 | public class Solution { 11 | public int maxPoints(Point[] points) { 12 | int maxCount = 0; 13 | int sameCount = 0; 14 | Map map = new HashMap(); 15 | for(Point pi : points){ 16 | map.clear(); 17 | sameCount = 0; 18 | for(Point pj : points){ 19 | if(pi.x == pj.x && pi.y == pj.y){ 20 | sameCount++; 21 | continue; 22 | } 23 | double slope = Double.NaN; 24 | if(pi.x != pj.x) 25 | slope = (pi.y - pj.y) * 1d / (pi.x - pj.x); 26 | increase(map, slope); 27 | } 28 | maxCount = Math.max(maxCount, sameCount); 29 | for(int v : map.values()) 30 | maxCount = Math.max(maxCount, v + sameCount); 31 | } 32 | return maxCount; 33 | } 34 | 35 | private int increase(Map map, double d){ 36 | int val = 1; 37 | if(map.containsKey(d)){ 38 | val = map.get(d) + 1; 39 | } 40 | map.put(d, val); 41 | return val; 42 | } 43 | } -------------------------------------------------------------------------------- /Search for a Range.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] searchRange(int[] A, int target) { 3 | int n = A.length; 4 | int left = bsearchCeil(A, target, 0, n); 5 | int right = bsearchFloor(A, target, 0, n); 6 | if(left >= n || A[left] != target) 7 | left = -1; 8 | if(right < 0 || A[right] != target) 9 | right = -1; 10 | int[] res = new int[2]; 11 | res[0] = left; 12 | res[1] = right; 13 | return res; 14 | } 15 | 16 | // return the min index, that a[index] >= target 17 | private int bsearchCeil(int[] a, int target, int s, int e){ 18 | if(s == e) 19 | return e; 20 | int mid = (s + e) / 2; 21 | int val = a[mid]; 22 | if(target > val){ 23 | return bsearchCeil(a, target, mid + 1, e); 24 | } else { 25 | return bsearchCeil(a, target, s, mid); 26 | } 27 | } 28 | 29 | // return the max index that a[index] <= target 30 | private int bsearchFloor(int[] a, int target, int s, int e){ 31 | if(s == e) 32 | return s - 1; 33 | int mid = (s + e) / 2; 34 | int val = a[mid]; 35 | if(target >= val){ 36 | return bsearchFloor(a, target, mid + 1, e); 37 | } else { 38 | return bsearchFloor(a, target, s, mid); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Search in Rotated Sorted Array II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean search(int[] A, int target) { 3 | int n = A.length; 4 | int offset = searchOffset(A, 0, n); 5 | int res = bsearch(A, target, 0, n, offset); 6 | return res != -1; 7 | } 8 | 9 | private int searchOffset(int[] a, int s, int e) { 10 | int len = e - s; 11 | if (len <= 1 || a[s] < a[e - 1]) 12 | return s; 13 | 14 | int mid = (s + e - 1) / 2; 15 | if (a[s] > a[mid]) 16 | return searchOffset(a, s, mid + 1); 17 | else if (a[s] < a[mid]) 18 | return searchOffset(a, mid + 1, e); 19 | else { 20 | int res = searchOffset(a, s + 1, e); 21 | if (res == s + 1 && a[s] == a[s + 1]) 22 | res = s; 23 | return res; 24 | } 25 | } 26 | 27 | private int bsearch(int[] a, int target, int s, int e, int offset) { 28 | if (s == e) 29 | return -1; 30 | int n = a.length; 31 | int mid = (s + e) / 2; 32 | int midVal = a[(mid + offset) % n]; 33 | if (midVal == target) { 34 | return mid; 35 | } else if (target > midVal) { 36 | return bsearch(a, target, mid + 1, e, offset); 37 | } else { 38 | return bsearch(a, target, s, mid, offset); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Permutations.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> permute(int[] num) { 3 | ArrayList> result = new ArrayList>(); 4 | Arrays.sort(num); 5 | do { 6 | ArrayList list = new ArrayList(); 7 | for (int i : num) 8 | list.add(i); 9 | result.add(list); 10 | } while (nextPermutation(num)); 11 | return result; 12 | } 13 | 14 | private boolean nextPermutation(int[] num) { 15 | int n = num.length; 16 | int descStart = 0; 17 | for (int i = n - 1; i > 0; i--) 18 | if (num[i] > num[i - 1]) { 19 | descStart = i; 20 | break; 21 | } 22 | if (descStart == 0) 23 | return false; 24 | for (int i = n - 1; i >= descStart; i--) 25 | if (num[i] > num[descStart - 1]){ 26 | swap(num, i, descStart - 1); 27 | break; 28 | } 29 | reverse(num, descStart, n - 1); 30 | return true; 31 | } 32 | 33 | private void reverse(int[] n, int s, int e) { 34 | for (; s < e; s++, e--) 35 | swap(n, s, e); 36 | } 37 | 38 | private void swap(int[] n, int i, int j) { 39 | int tmp = n[i]; 40 | n[i] = n[j]; 41 | n[j] = tmp; 42 | } 43 | } -------------------------------------------------------------------------------- /Permutations II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> permuteUnique(int[] num) { 3 | ArrayList> result = new ArrayList>(); 4 | Arrays.sort(num); 5 | do { 6 | ArrayList list = new ArrayList(); 7 | for (int i : num) 8 | list.add(i); 9 | result.add(list); 10 | } while (nextPermutation(num)); 11 | return result; 12 | } 13 | 14 | private boolean nextPermutation(int[] num) { 15 | int n = num.length; 16 | int descStart = 0; 17 | for (int i = n - 1; i > 0; i--) 18 | if (num[i] > num[i - 1]) { 19 | descStart = i; 20 | break; 21 | } 22 | if (descStart == 0) 23 | return false; 24 | for (int i = n - 1; i >= descStart; i--) 25 | if (num[i] > num[descStart - 1]){ 26 | swap(num, i, descStart - 1); 27 | break; 28 | } 29 | reverse(num, descStart, n - 1); 30 | return true; 31 | } 32 | 33 | private void reverse(int[] n, int s, int e) { 34 | for (; s < e; s++, e--) 35 | swap(n, s, e); 36 | } 37 | 38 | private void swap(int[] n, int i, int j) { 39 | int tmp = n[i]; 40 | n[i] = n[j]; 41 | n[j] = tmp; 42 | } 43 | } -------------------------------------------------------------------------------- /Subsets II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> subsetsWithDup(int[] num) { 3 | Arrays.sort(num); 4 | Map freqMap = new TreeMap(); 5 | for (int n : num) { 6 | if (freqMap.containsKey(n)) { 7 | freqMap.put(n, freqMap.get(n) + 1); 8 | } else { 9 | freqMap.put(n, 1); 10 | } 11 | } 12 | ArrayList> result = new ArrayList>(); 13 | List freqKeys = new ArrayList(); 14 | freqKeys.addAll(freqMap.keySet()); 15 | allSubsets(freqMap, freqKeys, 0, new ArrayList(), result); 16 | return result; 17 | } 18 | 19 | private void allSubsets(Map freqMap, List keys, 20 | int k, List list, ArrayList> result) { 21 | if (k == keys.size()) { 22 | result.add(new ArrayList(list)); 23 | return; 24 | } 25 | int num = keys.get(k); 26 | int freq = freqMap.get(num); 27 | for (int i = 0; i <= freq; i++) { 28 | if (i > 0) 29 | list.add(num); 30 | allSubsets(freqMap, keys, k + 1, list, result); 31 | } 32 | for (int i = 0; i < freq; i++) { 33 | list.remove(list.size() - 1); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Substring with Concatenation of All Words.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList findSubstring(String S, String[] L) { 3 | int lens = S.length(); 4 | int lenl = L.length; 5 | ArrayList subPos = new ArrayList(); 6 | if (lenl == 0) 7 | return subPos; 8 | int wordLen = L[0].length(); 9 | int totalLen = wordLen * lenl; 10 | Map lMap = new HashMap(); 11 | Map sMap = new HashMap(); 12 | for (String l : L) 13 | addMap(lMap, l); 14 | for (int i = 0; i <= lens - totalLen; i++) { 15 | sMap.clear(); 16 | int j = i; 17 | for (; j < i + totalLen; j += wordLen) { 18 | String sub = S.substring(j, j + wordLen); 19 | if (lMap.containsKey(sub)) { 20 | addMap(sMap, sub); 21 | if (sMap.get(sub) > lMap.get(sub)) 22 | break; 23 | } else 24 | break; 25 | } 26 | if (j == i + totalLen) 27 | subPos.add(i); 28 | } 29 | return subPos; 30 | } 31 | 32 | private void addMap(Map map, String key) { 33 | if (map.containsKey(key)) 34 | map.put(key, map.get(key) + 1); 35 | else 36 | map.put(key, 1); 37 | } 38 | } -------------------------------------------------------------------------------- /Valid Sudoku.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | static final int N = 9; 3 | 4 | public boolean isValidSudoku(char[][] board) { 5 | return validSudoku(board); 6 | } 7 | 8 | private boolean validSudoku(char[][] board) { 9 | Set set1 = new HashSet(); 10 | Set set2 = new HashSet(); 11 | Set set3 = new HashSet(); 12 | char c; 13 | int xi, yi; 14 | for (int i = 0; i < N; i++) { 15 | set1.clear(); 16 | set2.clear(); 17 | set3.clear(); 18 | for (int j = 0; j < N; j++) { 19 | c = board[i][j]; 20 | if (Character.isDigit(c)) 21 | if (!set1.contains(c)) 22 | set1.add(c); 23 | else 24 | return false; 25 | 26 | c = board[j][i]; 27 | if (Character.isDigit(c)) 28 | if (!set2.contains(c)) 29 | set2.add(c); 30 | else 31 | return false; 32 | 33 | xi = i / 3 * 3 + j / 3; 34 | yi = i % 3 * 3 + j % 3; 35 | c = board[xi][yi]; 36 | if (Character.isDigit(c)) 37 | if (!set3.contains(c)) 38 | set3.add(c); 39 | else 40 | return false; 41 | } 42 | } 43 | return true; 44 | } 45 | } -------------------------------------------------------------------------------- /Flatten Binary Tree to Linked List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public void flatten(TreeNode root) { 12 | Stack stack = new Stack(); 13 | TreeNode cur = root; 14 | TreeNode tail = null; 15 | while (stack.size() > 0 || cur != null) { 16 | if(cur == null) 17 | cur = stack.pop(); 18 | 19 | // visit cur 20 | if(tail == null) 21 | tail = cur; 22 | else{ 23 | tail.right = cur; 24 | tail.left = null; 25 | tail = cur; 26 | } 27 | 28 | if(cur.right != null) 29 | stack.push(cur.right); 30 | cur = cur.left; 31 | } 32 | } 33 | } 34 | 35 | public class Solution { 36 | public void flatten(TreeNode root) { 37 | getTailAndFlatten(root); 38 | } 39 | 40 | private TreeNode getTailAndFlatten(TreeNode tail){ 41 | if(tail == null) 42 | return null; 43 | TreeNode right = tail.right; 44 | tail.right = tail.left; 45 | tail.left = null; 46 | if(tail.right != null) 47 | tail = getTailAndFlatten(tail.right); 48 | tail.right = right; 49 | if(tail.right != null) 50 | tail = getTailAndFlatten(tail.right); 51 | return tail; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Set Matrix Zeroes.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void setZeroes(int[][] matrix) { 3 | int n = matrix.length; 4 | int m = n > 0 ? matrix[0].length : 0; 5 | // whether the first row/col should be set to zero. 6 | boolean firstRowZero = false; 7 | boolean firstColZero = false; 8 | for(int i = 0; i < n; i++) 9 | if(matrix[i][0] == 0){ 10 | firstColZero = true; 11 | break; 12 | } 13 | for(int j = 0; j < m; j++) 14 | if(matrix[0][j] == 0){ 15 | firstRowZero = true; 16 | break; 17 | } 18 | // use the first row/col to restore which row/col is zero. 19 | for(int i = 1; i < n; i++){ 20 | for(int j = 1; j < m; j++){ 21 | if(matrix[i][j] == 0){ 22 | matrix[0][j] = 0; 23 | matrix[i][0] = 0; 24 | } 25 | } 26 | } 27 | for(int i = 1; i < n; i++){ 28 | if(matrix[i][0] == 0){ 29 | for(int j = 1; j < m; j++) 30 | matrix[i][j] = 0; 31 | } 32 | } 33 | for(int j = 1; j < m; j++){ 34 | if(matrix[0][j] == 0){ 35 | for(int i = 1; i < n; i++) 36 | matrix[i][j] = 0; 37 | } 38 | } 39 | if(firstRowZero) 40 | for(int j = 0; j < m; j++) 41 | matrix[0][j] = 0; 42 | if(firstColZero) 43 | for(int i = 0; i < n; i++) 44 | matrix[i][0] = 0; 45 | } 46 | } -------------------------------------------------------------------------------- /Single Number II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private static final int DUPLICATE_SIZE = 3; 3 | public int singleNumber(int[] A) { 4 | return singleNumber(A, 0, A.length); 5 | } 6 | 7 | // 3-way partition 8 | private int[] partition(int[] A, int start, int end){ 9 | int pval = A[start]; 10 | int s = start; 11 | int p = start; 12 | int q = end - 1; 13 | while(p <= q){ 14 | if(A[p] == pval){ 15 | p++; 16 | } else if(A[p] > pval){ 17 | swap(A, p, q); 18 | q--; 19 | } else { 20 | swap(A, p, s); 21 | s++; 22 | p++; 23 | } 24 | } 25 | int[] res = new int[2]; 26 | res[0] = s; 27 | res[1] = p; 28 | return res; 29 | } 30 | 31 | private void swap(int[] A, int x, int y){ 32 | int tmp = A[x]; 33 | A[x] = A[y]; 34 | A[y] = tmp; 35 | } 36 | 37 | private int singleNumber(int[] A, int start, int end){ 38 | if(start == end) 39 | return 0; 40 | int[] pivots = partition(A, start, end); 41 | if(pivots[1] - pivots[0] < DUPLICATE_SIZE){ 42 | // middle val is the single val. 43 | return A[pivots[0]]; 44 | } else if((pivots[0] - start) % DUPLICATE_SIZE == 0){ 45 | // single number located in right part 46 | return singleNumber(A, pivots[1], end); 47 | } else{ 48 | // single number located in left part 49 | return singleNumber(A, start, pivots[0]); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Generate Parentheses.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-23 3 | */ 4 | public class Solution { 5 | public ArrayList generateParenthesis(int n) { 6 | ArrayList result = new ArrayList(); 7 | generate(n, 0, 0, new char[2 * n], result); 8 | return result; 9 | } 10 | 11 | private void generate(int n, int left, int right, char[] array, 12 | ArrayList result) { 13 | int k = left + right; 14 | if (k == n * 2) { 15 | result.add(new String(array)); 16 | return; 17 | } 18 | if (left < n) { 19 | array[k] = '('; 20 | generate(n, left + 1, right, array, result); 21 | } 22 | if (right < left) { 23 | array[k] = ')'; 24 | generate(n, left, right + 1, array, result); 25 | } 26 | 27 | } 28 | } 29 | 30 | /** 31 | * @time: 2013-09-13 32 | * It's a application of Catalan Number. 33 | */ 34 | public class Solution { 35 | public ArrayList generateParenthesis(int n) { 36 | ArrayList> results = new ArrayList>(); 37 | ArrayList empty = new ArrayList(); 38 | empty.add(""); 39 | results.add(empty); 40 | for(int i = 1; i <= n; i++){ 41 | ArrayList next = new ArrayList(); 42 | results.add(next); 43 | for(int j = 0; j < i; j++) 44 | for(String left : results.get(j)) 45 | for(String right : results.get(i - 1 - j)){ 46 | next.add('(' + left + ')' + right); 47 | } 48 | return results.get(n); 49 | } 50 | } -------------------------------------------------------------------------------- /Maximal Rectangle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maximalRectangle(char[][] matrix) { 3 | int n = matrix.length; 4 | if(n == 0) 5 | return 0; 6 | int m = matrix[0].length; 7 | if(m == 0) 8 | return 0; 9 | 10 | int[] height = new int[m]; 11 | int maxArea = 0; 12 | for(int i = 0; i < n; i++){ 13 | for(int j = 0; j < m; j++){ 14 | if(matrix[i][j] == '0') 15 | height[j] = 0; 16 | else 17 | height[j] += 1; 18 | } 19 | int area = maxAreaInHistogram(height); 20 | maxArea = Math.max(maxArea, area); 21 | } 22 | return maxArea; 23 | } 24 | 25 | private int maxAreaInHistogram(int[] height){ 26 | int n = height.length; 27 | int[] hStack = new int[n]; 28 | int[] wStack = new int[n]; 29 | int top = 0; 30 | 31 | int maxArea = 0; 32 | for(int i = 0; i <= n; i++){ 33 | // when i == n, we just want to clean the stack. 34 | int widthSum = 0; 35 | while(top > 0 && (i == n || hStack[top - 1] >= height[i])){ 36 | // pop the stack top to keep the hStack in ascending order. 37 | top--; 38 | int h = hStack[top]; 39 | widthSum += wStack[top]; 40 | maxArea = Math.max(maxArea, widthSum * h); 41 | } 42 | if(i < n){ 43 | // push to stack. 44 | hStack[top] = height[i]; 45 | wStack[top++] = widthSum + 1; 46 | } 47 | } 48 | return maxArea; 49 | } 50 | } -------------------------------------------------------------------------------- /Copy List with Random Pointer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list with a random pointer. 3 | * class RandomListNode { 4 | * int label; 5 | * RandomListNode next, random; 6 | * RandomListNode(int x) { this.label = x; } 7 | * }; 8 | */ 9 | public class Solution { 10 | 11 | public RandomListNode copyRandomList(RandomListNode head) { 12 | RandomListNode dummyHead = new RandomListNode(0); 13 | RandomListNode p = head, q = dummyHead; 14 | RandomListNode pnext, qnext; 15 | // create clone list. 16 | while (p != null) { 17 | q.next = new RandomListNode(p.label); 18 | p = p.next; 19 | q = q.next; 20 | } 21 | 22 | p = head; 23 | q = dummyHead.next; 24 | // create connections between the two lists. 25 | // p.next <-> q.random 26 | while (p != null) { 27 | pnext = p.next; 28 | p.next = q; 29 | q.random = p; 30 | p = pnext; 31 | q = q.next; 32 | } 33 | 34 | p = head; 35 | q = dummyHead.next; 36 | // clone random link. 37 | while (p != null) { 38 | q.random = p.random != null ? p.random.next : null; 39 | qnext = q.next; 40 | p = qnext != null ? qnext.random : null; 41 | q.next = p; 42 | q = qnext; 43 | } 44 | 45 | // restore original list 46 | p = head; 47 | q = dummyHead.next; 48 | while (p != null) { 49 | p.next = q.next; 50 | q.next = q.next != null ? q.next.next : null; 51 | p = p.next; 52 | q = q.next; 53 | } 54 | return dummyHead.next; 55 | } 56 | } -------------------------------------------------------------------------------- /Remove Duplicates from Sorted List II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode deleteDuplicates(ListNode head) { 14 | ListNode cur = head, pre = null; 15 | ListNode duplicate = null; 16 | while (cur != null) { 17 | if (cur.next != null && cur.val == cur.next.val) { 18 | duplicate = cur; 19 | cur.next = cur.next.next; 20 | } else if (duplicate != null && cur.val == duplicate.val) { 21 | cur = cur.next; 22 | if (pre != null) { 23 | pre.next = cur; 24 | } else { 25 | head = cur; 26 | } 27 | } else { 28 | duplicate = null; 29 | pre = cur; 30 | cur = cur.next; 31 | } 32 | } 33 | return head; 34 | } 35 | } 36 | 37 | /** 38 | * @time: 2013-08-31 39 | */ 40 | public class Solution { 41 | public ListNode deleteDuplicates(ListNode head) { 42 | ListNode empty = new ListNode(Integer.MIN_VALUE); 43 | empty.next = head; 44 | ListNode p = empty; 45 | ListNode q = empty; 46 | while(p != null && p.next != null){ 47 | q = p.next; 48 | while(q.next != null && q.val == q.next.val){ 49 | q = q.next; 50 | } 51 | if(q != p.next){ 52 | p.next = q.next; 53 | } else 54 | p = p.next; 55 | } 56 | 57 | return empty.next; 58 | } 59 | } -------------------------------------------------------------------------------- /Reorder List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public void reorderList(ListNode head) { 14 | ListNode l1 = head; 15 | ListNode l2 = seperate(head); 16 | l2 = reverse(l2); 17 | interleave(l1, l2); 18 | } 19 | 20 | private ListNode seperate(ListNode head){ 21 | ListNode p = head; 22 | ListNode q = head; 23 | while (q != null && q.next != null && q.next.next != null) { 24 | q = q.next.next; 25 | p = p.next; 26 | } 27 | ListNode l2 = null; 28 | if(p != null){ 29 | l2 = p.next; 30 | p.next = null; 31 | } 32 | return l2; 33 | } 34 | 35 | private ListNode reverse(ListNode head){ 36 | ListNode p = null; 37 | ListNode q = head; 38 | while(q != null){ 39 | ListNode tmp = q.next; 40 | q.next = p; 41 | p = q; 42 | q = tmp; 43 | } 44 | return p; 45 | } 46 | 47 | private ListNode interleave(ListNode h1, ListNode h2){ 48 | ListNode dummy = new ListNode(0); 49 | ListNode cur = dummy; 50 | while(h1 != null || h2 != null){ 51 | if(h1 != null){ 52 | cur.next = h1; 53 | h1 = h1.next; 54 | cur = cur.next; 55 | } 56 | if(h2 != null){ 57 | cur.next = h2; 58 | h2 = h2.next; 59 | cur = cur.next; 60 | } 61 | } 62 | return dummy.next; 63 | } 64 | } -------------------------------------------------------------------------------- /Text Justification.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList fullJustify(String[] words, int L) { 3 | int wordsCount = words.length; 4 | ArrayList result = new ArrayList(); 5 | int curLen = 0; 6 | int lastI = 0; 7 | for (int i = 0; i <= wordsCount; i++) { 8 | if (i == wordsCount || curLen + words[i].length() + i - lastI > L) { 9 | StringBuffer buf = new StringBuffer(); 10 | int spaceCount = L - curLen; 11 | int spaceSlots = i - lastI - 1; 12 | if (spaceSlots == 0 || i == wordsCount) { 13 | for(int j = lastI; j < i; j++){ 14 | buf.append(words[j]); 15 | if(j != i - 1) 16 | appendSpace(buf, 1); 17 | } 18 | appendSpace(buf, L - buf.length()); 19 | } else { 20 | int spaceEach = spaceCount / spaceSlots; 21 | int spaceExtra = spaceCount % spaceSlots; 22 | for (int j = lastI; j < i; j++) { 23 | buf.append(words[j]); 24 | if (j != i - 1) 25 | appendSpace(buf, spaceEach + (j - lastI < spaceExtra ? 1 : 0)); 26 | } 27 | } 28 | result.add(buf.toString()); 29 | lastI = i; 30 | curLen = 0; 31 | } 32 | if (i < wordsCount) 33 | curLen += words[i].length(); 34 | } 35 | return result; 36 | } 37 | 38 | private void appendSpace(StringBuffer sb, int count) { 39 | for (int i = 0; i < count; i++) 40 | sb.append(' '); 41 | } 42 | } -------------------------------------------------------------------------------- /Spiral Matrix II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private static int[][] DIRS = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 3 | public int[][] generateMatrix(int n) { 4 | int[][] res = new int[n][n]; 5 | int[] border = new int[]{0, n - 1, n - 1, 0}; 6 | int x = 0; 7 | int y = 0; 8 | int dir = 0; 9 | for(int i = 0; i < n * n; i++){ 10 | res[x][y] = i + 1; 11 | int nextDir = (dir + 1) % 4; 12 | if(dir % 2 == 0 && y == border[nextDir] || dir % 2 == 1 && x == border[nextDir]){ 13 | // change direction 14 | border[dir] += DIRS[nextDir][0] + DIRS[nextDir][1]; 15 | dir = nextDir; 16 | } 17 | x += DIRS[dir][0]; 18 | y += DIRS[dir][1]; 19 | } 20 | return res; 21 | } 22 | } 23 | 24 | public class Solution { 25 | public int[][] generateMatrix(int n) { 26 | int[][] matrix = new int[n][n]; 27 | fillSpiral(matrix, 0, 1); 28 | return matrix; 29 | } 30 | 31 | private void fillSpiral(int[][] matrix, int index, int val) { 32 | int n = matrix.length; 33 | if (index * 2 >= n) 34 | return; 35 | int i, j; 36 | for (i = index, j = index; j < n - index; j++) 37 | matrix[i][j] = val++; 38 | for (i = index + 1, j = n - 1 - index; i < n - index; i++) 39 | matrix[i][j] = val++; 40 | if (index != n - 1 - index) { 41 | for (i = n - 1 - index, j = n - 2 - index; j >= index; j--) 42 | matrix[i][j] = val++; 43 | for (i = n - 2 - index, j = index; i > index; i--) 44 | matrix[i][j] = val++; 45 | } 46 | fillSpiral(matrix, index + 1, val); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Restore IP Addresses.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | static final int IP_COUNT = 4; 3 | static final int IP_LEN = 3; 4 | 5 | public ArrayList restoreIpAddresses(String s) { 6 | ArrayList res = new ArrayList(); 7 | char[] cs = s.toCharArray(); 8 | searchIp(cs, 0, new int[4], res); 9 | return res; 10 | } 11 | 12 | private void searchIp(char[] cs, int index, int[] ipIndexs, 13 | ArrayList res) { 14 | int n = cs.length; 15 | if (index == IP_COUNT) { 16 | if (ipIndexs[IP_COUNT - 1] != n) 17 | return; 18 | StringBuilder sb = new StringBuilder(); 19 | for (int i = 0; i < IP_COUNT; i++) { 20 | int s = i == 0 ? 0 : ipIndexs[i - 1]; 21 | int e = ipIndexs[i]; 22 | sb.append(cs, s, e - s); 23 | if (i != IP_COUNT - 1) 24 | sb.append('.'); 25 | } 26 | res.add(sb.toString()); 27 | return; 28 | } 29 | 30 | int start = index == 0 ? 0 : ipIndexs[index - 1]; 31 | for (int i = 0; i < IP_LEN && start + i < n; i++) { 32 | if (isValid(cs, start, start + i + 1)) { 33 | ipIndexs[index] = start + i + 1; 34 | searchIp(cs, index + 1, ipIndexs, res); 35 | } 36 | } 37 | } 38 | 39 | private boolean isValid(char[] cs, int s, int e) { 40 | int n = e - s; 41 | if (n == 0 || n > IP_LEN) 42 | return false; 43 | if (cs[s] == '0') 44 | return n == 1; 45 | int sum = 0; 46 | for (int i = s; i < e; i++) { 47 | sum *= 10; 48 | sum += cs[i] - '0'; 49 | } 50 | return sum <= 255; 51 | } 52 | } -------------------------------------------------------------------------------- /Palindrome Partitioning.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> partition(String s) { 3 | int n = s.length(); 4 | // Use dp to get all the palindrome 5 | ArrayList> prevsList = new ArrayList>(); 6 | for (int i = 0; i < n; i++) { 7 | ArrayList curPrevs = new ArrayList(); 8 | prevsList.add(curPrevs); 9 | curPrevs.add(i); 10 | if (i > 0) { 11 | if (s.charAt(i - 1) == s.charAt(i)) 12 | curPrevs.add(i - 1); 13 | for (int prev : prevsList.get(i - 1)) { 14 | if (prev > 0 && s.charAt(prev - 1) == s.charAt(i)) 15 | curPrevs.add(prev - 1); 16 | } 17 | } 18 | } 19 | // Use backtracking to get the results. 20 | ArrayList> res = new ArrayList>(); 21 | searchResult(s, n - 1, prevsList, res, new ArrayList()); 22 | return res; 23 | } 24 | 25 | private void searchResult(String s, int curIndex, 26 | ArrayList> prevsList, 27 | ArrayList> res, ArrayList list) { 28 | if (curIndex < 0) { 29 | ArrayList curList = new ArrayList(); 30 | curList.addAll(list); 31 | Collections.reverse(curList); 32 | res.add(curList); 33 | return; 34 | } 35 | ArrayList prevs = prevsList.get(curIndex); 36 | for (Integer prev : prevs) { 37 | list.add(s.substring(prev, curIndex + 1)); 38 | searchResult(s, prev - 1, prevsList, res, list); 39 | list.remove(list.size() - 1); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Surrounded Regions.java: -------------------------------------------------------------------------------- 1 | public class Solution { static final char C_O = 'O'; static final char C_X = 'X'; static final char C_Z = 'Z'; public void solve(char[][] board) { int m = board.length; if (m == 0) { return; } int n = board[0].length; Node[][] nodes = new Node[m][n]; Stack stack = new Stack(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { nodes[i][j] = new Node(i, j); if (i == 0 || j == 0 || i == m - 1 || j == n - 1) { if (board[i][j] == C_O) { stack.push(nodes[i][j]); } } } } int ni, nj; Node node; while (!stack.isEmpty()) { node = stack.pop(); board[node.x][node.y] = C_Z; for (int[] dir : DIRECTIONS) { ni = node.x + dir[0]; nj = node.y + dir[1]; if (isValid(ni, nj, m, n) && board[ni][nj] == C_O) { stack.push(nodes[ni][nj]); } } } fillChar(board, C_O, C_X); fillChar(board, C_Z, C_O); } class Node { int x; int y; public Node(int x, int y) { this.x = x; this.y = y; } } static int[][] DIRECTIONS = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; private boolean isValid(int x, int y, int m, int n) { return x >= 0 && x < m && y >= 0 && y < n; } private void fillChar(char[][] board, char findChar, char fillChar) { int m = board.length; int n = board[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == findChar) board[i][j] = fillChar; } } } } -------------------------------------------------------------------------------- /Merge Two Sorted Lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-30 3 | * Definition for singly-linked list. 4 | * public class ListNode { 5 | * int val; 6 | * ListNode next; 7 | * ListNode(int x) { 8 | * val = x; 9 | * next = null; 10 | * } 11 | * } 12 | */ 13 | public class Solution { 14 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 15 | // Start typing your Java solution below 16 | // DO NOT write main() function 17 | if(l1 == null && l2 == null) 18 | return null; 19 | if(l1 == null) 20 | return l2; 21 | if(l2 == null) 22 | return l1; 23 | 24 | ListNode node = null; 25 | if(l1.val < l2.val){ 26 | node = l1; 27 | node.next = mergeTwoLists(l1.next, l2); 28 | } else { 29 | node = l2; 30 | node.next = mergeTwoLists(l1, l2.next); 31 | } 32 | return node; 33 | } 34 | } 35 | 36 | public class Solution { 37 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 38 | // Start typing your Java solution below 39 | // DO NOT write main() function 40 | ListNode root = new ListNode(0); 41 | ListNode tail = root; 42 | while(l1 != null || l2 != null){ 43 | if (l1 == null) { 44 | tail.next = l2; 45 | l2 = null; 46 | } else if (l2 == null){ 47 | tail.next = l1; 48 | l1 = null; 49 | } else { 50 | if (l1.val < l2.val) { 51 | tail.next = l1; 52 | l1 = l1.next; 53 | } else { 54 | tail.next = l2; 55 | l2 = l2.next; 56 | } 57 | tail = tail.next; 58 | } 59 | } 60 | return root.next; 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /Single Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int singleNumber(int[] A) { 3 | // Note: The Solution object is instantiated only once and is reused by each test case. 4 | int xor = 0; 5 | for(int a : A) 6 | xor ^= a; 7 | return xor; 8 | } 9 | } 10 | 11 | public class Solution { 12 | private static final int DUPLICATE_SIZE = 2; 13 | public int singleNumber(int[] A) { 14 | return singleNumber(A, 0, A.length); 15 | } 16 | 17 | // 3-way partition 18 | private int[] partition(int[] A, int start, int end){ 19 | int pval = A[start]; 20 | int s = start; 21 | int p = start; 22 | int q = end - 1; 23 | while(p <= q){ 24 | if(A[p] == pval){ 25 | p++; 26 | } else if(A[p] > pval){ 27 | swap(A, p, q); 28 | q--; 29 | } else { 30 | swap(A, p, s); 31 | s++; 32 | p++; 33 | } 34 | } 35 | int[] res = new int[2]; 36 | res[0] = s; 37 | res[1] = p; 38 | return res; 39 | } 40 | 41 | private void swap(int[] A, int x, int y){ 42 | int tmp = A[x]; 43 | A[x] = A[y]; 44 | A[y] = tmp; 45 | } 46 | 47 | private int singleNumber(int[] A, int start, int end){ 48 | if(start == end) 49 | return 0; 50 | int[] pivots = partition(A, start, end); 51 | if(pivots[1] - pivots[0] < DUPLICATE_SIZE){ 52 | // middle val is the single val. 53 | return A[pivots[0]]; 54 | } else if((pivots[0] - start) % DUPLICATE_SIZE == 0){ 55 | // single number located in right part 56 | return singleNumber(A, pivots[1], end); 57 | } else{ 58 | // single number located in left part 59 | return singleNumber(A, start, pivots[0]); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /Word Break.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean wordBreak(String s, Set dict) { 3 | Set dictSet = new HashSet(); 4 | for (String word : dict) 5 | for (int i = 0; i < word.length(); i++) 6 | dictSet.add(word.charAt(i)); 7 | for (int i = 0; i < s.length(); i++) 8 | if (!dictSet.contains(s.charAt(i))) 9 | return false; 10 | 11 | TrieNode root = null; 12 | for (String word : dict) 13 | root = insert(root, word); 14 | 15 | return dfsWord(s, "", root, root); 16 | } 17 | 18 | private boolean dfsWord(String s, String word, TrieNode curNode, 19 | TrieNode root) { 20 | if (curNode == null) 21 | return false; 22 | if (s.length() == 0) 23 | return word.length() == 0; 24 | char c = s.charAt(0); 25 | int ci = c - 'a'; 26 | TrieNode nextNode = curNode.children[ci]; 27 | word += c; 28 | boolean res = false; 29 | if (nextNode != null) { 30 | res = dfsWord(s.substring(1), word, nextNode, root); 31 | if (!res && nextNode.isKey) 32 | res = dfsWord(s.substring(1), "", root, root); 33 | } 34 | return res; 35 | } 36 | 37 | private class TrieNode { 38 | private static final int R = 26; 39 | TrieNode[] children; 40 | boolean isKey; 41 | 42 | public TrieNode() { 43 | children = new TrieNode[R]; 44 | } 45 | } 46 | 47 | private TrieNode insert(TrieNode node, String s) { 48 | if (node == null) { 49 | node = new TrieNode(); 50 | } 51 | if (s.length() == 0) { 52 | node.isKey = true; 53 | } else { 54 | int c = s.charAt(0) - 'a'; 55 | node.children[c] = insert(node.children[c], s.substring(1)); 56 | } 57 | return node; 58 | } 59 | } -------------------------------------------------------------------------------- /Insert Interval.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * public class Interval { 4 | * int start; 5 | * int end; 6 | * Interval() { start = 0; end = 0; } 7 | * Interval(int s, int e) { start = s; end = e; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList insert(ArrayList intervals, Interval newInterval) { 12 | int n = intervals.size(); 13 | int left = bsearch(intervals, newInterval.start, 0, intervals.size()); 14 | int right = bsearch(intervals, newInterval.end, 0, intervals.size()); 15 | if(left < 0 || !interleave(intervals.get(left), newInterval)) 16 | left++; 17 | Interval insert = new Interval(); 18 | insert.start = newInterval.start; 19 | if(left < n) 20 | insert.start = Math.min(insert.start, intervals.get(left).start); 21 | insert.end = newInterval.end; 22 | if(right >= 0) 23 | insert.end = Math.max(insert.end, intervals.get(right).end); 24 | 25 | ArrayList result = new ArrayList(); 26 | result.addAll(intervals.subList(0, left)); 27 | result.add(insert); 28 | result.addAll(intervals.subList(right + 1, n)); 29 | return result; 30 | } 31 | 32 | private boolean interleave(Interval a, Interval b) { 33 | return (a.start - b.start) * (a.end - b.start) <= 0 34 | || (a.start - b.end) * (a.end - b.end) <= 0; 35 | } 36 | 37 | private int bsearch(List intervals, int target, int s, int e){ 38 | if(s == e) 39 | return s - 1; 40 | int mid = (s + e) / 2; 41 | Interval inter = intervals.get(mid); 42 | int val = inter.start; 43 | 44 | if(val == target) 45 | return mid; 46 | else if(val > target) 47 | return bsearch(intervals, target, s, mid); 48 | else 49 | return bsearch(intervals, target, mid + 1, e); 50 | } 51 | } -------------------------------------------------------------------------------- /Binary Tree Level Order Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList> levelOrder(TreeNode root) { 12 | ArrayList> res = new ArrayList>(); 13 | dfs(root, 0, res); 14 | return res; 15 | } 16 | 17 | public void dfs(TreeNode root, int depth, ArrayList> res) { 18 | if (root == null) 19 | return; 20 | ArrayList list = null; 21 | if (depth < res.size()) { 22 | list = res.get(depth); 23 | } else { 24 | list = new ArrayList(); 25 | res.add(list); 26 | } 27 | list.add(root.val); 28 | dfs(root.left, depth + 1, res); 29 | dfs(root.right, depth + 1, res); 30 | } 31 | } 32 | 33 | /** 34 | * @time: 2013-08-25 35 | * } 36 | */ 37 | public class Solution { 38 | public ArrayList> levelOrder(TreeNode root) { 39 | ArrayList> res = new ArrayList>(); 40 | ArrayList list = new ArrayList(); 41 | Queue queue = new LinkedList(); 42 | if(root != null) 43 | queue.offer(root); 44 | int leftCount = 0; 45 | while(!queue.isEmpty()){ 46 | if(leftCount == 0){ 47 | list = new ArrayList(); 48 | res.add(list); 49 | leftCount = queue.size(); 50 | } 51 | TreeNode node = queue.poll(); 52 | list.add(node.val); 53 | leftCount--; 54 | if(node.left != null) 55 | queue.offer(node.left); 56 | if(node.right != null) 57 | queue.offer(node.right); 58 | } 59 | return res; 60 | } 61 | } -------------------------------------------------------------------------------- /Binary Tree Level Order Traversal II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList> levelOrderBottom(TreeNode root) { 12 | ArrayList> res = new ArrayList>(); 13 | dfs(root, 0, res); 14 | Collections.reverse(res); 15 | return res; 16 | } 17 | 18 | public void dfs(TreeNode root, int depth, ArrayList> res) { 19 | if (root == null) 20 | return; 21 | ArrayList list = null; 22 | if (depth < res.size()) { 23 | list = res.get(depth); 24 | } else { 25 | list = new ArrayList(); 26 | res.add(list); 27 | } 28 | dfs(root.left, depth + 1, res); 29 | dfs(root.right, depth + 1, res); 30 | list.add(root.val); 31 | } 32 | } 33 | 34 | public class Solution { 35 | public ArrayList> levelOrderBottom(TreeNode root) { 36 | ArrayList> res = new ArrayList>(); 37 | ArrayList list = null; 38 | Queue queue = new LinkedList(); 39 | if(root != null) 40 | queue.offer(root); 41 | int count = 0; 42 | while(!queue.isEmpty()){ 43 | if(count == 0){ 44 | list = new ArrayList(); 45 | res.add(list); 46 | count = queue.size(); 47 | } 48 | TreeNode node = queue.poll(); 49 | list.add(node.val); 50 | count--; 51 | if(node.left != null) 52 | queue.offer(node.left); 53 | if(node.right != null) 54 | queue.offer(node.right); 55 | } 56 | Collections.reverse(res); 57 | return res; 58 | } 59 | } -------------------------------------------------------------------------------- /Add Two Numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 14 | ListNode n1 = l1; 15 | ListNode n2 = l2; 16 | while (n1 != null || n2 != null) { 17 | if (n2 != null) 18 | n1.val += n2.val; 19 | if (n1.next == null && (n1.val >= 10 || n2 != null && n2.next != null)) 20 | n1.next = new ListNode(0); 21 | if (n1.next != null) 22 | n1.next.val += n1.val / 10; 23 | n1.val %= 10; 24 | n1 = n1.next; 25 | if (n2 != null) 26 | n2 = n2.next; 27 | } 28 | return l1; 29 | } 30 | } 31 | 32 | public class Solution { 33 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 34 | ListNode root = null; 35 | ListNode cur = null, next = null; 36 | while(l1 != null || l2 != null){ 37 | int val = 0; 38 | if(l1 != null){ 39 | val += l1.val; 40 | l1 = l1.next; 41 | } 42 | if(l2 != null){ 43 | val += l2.val; 44 | l2 = l2.next; 45 | } 46 | if(cur == null){ 47 | cur = new ListNode(0); 48 | } 49 | if(root == null){ 50 | root = cur; 51 | } 52 | cur.val += val; 53 | cur.next = new ListNode(0); 54 | cur.next.val += cur.val / 10; 55 | cur.val %= 10; 56 | if(l1 == null && l2 == null){ 57 | // reach the last node, delete the last 0 node. 58 | if(cur.next.val == 0) 59 | cur.next = null; 60 | } 61 | cur = cur.next; 62 | } 63 | return root; 64 | } 65 | } -------------------------------------------------------------------------------- /Combinations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-27 3 | */ 4 | public class Solution { 5 | public ArrayList> combine(int n, int k) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | ArrayList> result = new ArrayList>(); 9 | combine(n, k, 0, new Integer[k], result); 10 | return result; 11 | } 12 | 13 | private void combine(int n, int k, int step, Integer[] choices, ArrayList> result){ 14 | if(k == step){ 15 | ArrayList list = new ArrayList(); 16 | list.addAll(Arrays.asList(choices)); 17 | result.add(list); 18 | return; 19 | } 20 | int start = 1; 21 | if(step > 0) 22 | start = choices[step - 1] + 1; 23 | for(int i = start; i <= n; i++){ 24 | choices[step] = i; 25 | combine(n, k, step + 1, choices, result); 26 | } 27 | } 28 | } 29 | 30 | /** 31 | * Time complexity = O(C(n, k) * k) 32 | */ 33 | public class Solution { 34 | public ArrayList> combine(int n, int k) { 35 | // Start typing your Java solution below 36 | // DO NOT write main() function 37 | ArrayList> res = new ArrayList>(); 38 | Integer[] a = new Integer[k]; 39 | for (int i = 0; i < k; i++) { 40 | a[i] = i + 1; 41 | } 42 | do { 43 | ArrayList list = new ArrayList(); 44 | list.addAll(Arrays.asList(a)); 45 | res.add(list); 46 | } while (add(a, n)); 47 | return res; 48 | } 49 | 50 | private boolean add(Integer[] a, int n) { 51 | int k = a.length; 52 | int i = k - 1; 53 | while (i >= 0 && a[i] == n - k + i + 1) { 54 | i--; 55 | } 56 | if (i < 0) 57 | return false; 58 | a[i]++; 59 | for (int j = i + 1; j < k; j++) { 60 | a[j] = a[i] + j - i; 61 | } 62 | return true; 63 | } 64 | } -------------------------------------------------------------------------------- /Populating Next Right Pointers in Each Node II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Use no extra space. 3 | * Time complexity is O(n) 4 | */ 5 | public class Solution { 6 | public void connect(TreeLinkNode root) { 7 | TreeLinkNode node; 8 | TreeLinkNode last = null, curr = null; 9 | while (root != null) { 10 | node = root; 11 | last = null; 12 | curr = null; 13 | while (node != null) { 14 | if (node.left != null && curr != node.left) 15 | curr = node.left; 16 | else if (node.right != null) 17 | curr = node.right; 18 | if (last != null) { 19 | if (last != curr) 20 | last.next = curr; 21 | } else 22 | root = curr; 23 | last = curr; 24 | if (node.right == null || curr == node.right) 25 | node = node.next; 26 | } 27 | } 28 | } 29 | } 30 | 31 | /** 32 | * @time: 2013-08-31 33 | * Use a queue to do bfs. 34 | * Time complexity and space complexity are both O(n) 35 | * 36 | * Definition for binary tree with next pointer. 37 | * public class TreeLinkNode { 38 | * int val; 39 | * TreeLinkNode left, right, next; 40 | * TreeLinkNode(int x) { val = x; } 41 | * } 42 | */ 43 | public class Solution { 44 | public void connect(TreeLinkNode root) { 45 | if(root == null) 46 | return; 47 | Queue queue = new LinkedList(); 48 | queue.offer(root); 49 | int leftCount = 1; 50 | TreeLinkNode last = null; 51 | while(!queue.isEmpty()){ 52 | if(leftCount == 0){ 53 | leftCount = queue.size(); 54 | last = null; 55 | } 56 | TreeLinkNode node = queue.poll(); 57 | leftCount--; 58 | if(node.left != null) 59 | queue.offer(node.left); 60 | if(node.right != null) 61 | queue.offer(node.right); 62 | if(last != null) 63 | last.next = node; 64 | last = node; 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /Binary Tree Maximum Path Sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | private int maxSum; 12 | 13 | public int maxPathSum(TreeNode root) { 14 | // Start typing your Java solution below 15 | // DO NOT write main() function 16 | if (root == null) 17 | return 0; 18 | maxSum = Integer.MIN_VALUE; 19 | maxSinglePathSum(root); 20 | return maxSum; 21 | } 22 | 23 | public int maxSinglePathSum(TreeNode root) { 24 | if (root == null) 25 | return 0; 26 | int leftSum = maxSinglePathSum(root.left); 27 | int rightSum = maxSinglePathSum(root.right); 28 | int pathSum = root.val + Math.max(leftSum, 0) + Math.max(rightSum, 0); 29 | maxSum = pathSum > maxSum ? pathSum : maxSum; 30 | return Math.max(Math.max(leftSum, rightSum), 0) + root.val; 31 | } 32 | } 33 | 34 | /** 35 | * @time: 2013-08-26 36 | */ 37 | public class Solution { 38 | 39 | public int maxPathSum(TreeNode root) { 40 | // Start typing your Java solution below 41 | // DO NOT write main() function 42 | int[] result = new int[2]; 43 | maxPathSum(root, result); 44 | return result[1]; 45 | } 46 | 47 | private void maxPathSum(TreeNode root, int[] result){ 48 | if(root == null){ 49 | result[0] = 0; 50 | result[1] = Integer.MIN_VALUE; 51 | return; 52 | } 53 | maxPathSum(root.left, result); 54 | int leftOneWaySum = result[0]; 55 | int leftPathSum = result[1]; 56 | 57 | maxPathSum(root.right, result); 58 | int rightOneWaySum = result[0]; 59 | int rightPathSum = result[1]; 60 | 61 | int oneWaySum = max(leftOneWaySum, rightOneWaySum, 0) + root.val; 62 | int pathSum = Math.max(leftOneWaySum, 0) + Math.max(rightOneWaySum, 0) + root.val; 63 | result[0] = oneWaySum; 64 | result[1] = max(leftPathSum, rightPathSum, pathSum); 65 | } 66 | 67 | private int max(int a, int b, int c){ 68 | return Math.max(a, Math.max(b, c)); 69 | } 70 | } -------------------------------------------------------------------------------- /Word Break II.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public ArrayList wordBreak(String s, Set dict) { 4 | ArrayList senList = new ArrayList(); 5 | 6 | Set dictSet = new HashSet(); 7 | for (String word : dict) 8 | for (int i = 0; i < word.length(); i++) 9 | dictSet.add(word.charAt(i)); 10 | for (int i = 0; i < s.length(); i++) 11 | if (!dictSet.contains(s.charAt(i))) 12 | return senList; 13 | 14 | TrieNode root = null; 15 | for (String word : dict) 16 | root = insert(root, word); 17 | 18 | dfsWord(s, "", "", senList, root, root); 19 | return senList; 20 | } 21 | 22 | private void dfsWord(String s, String sentence, String word, 23 | List senList, TrieNode curNode, TrieNode root) { 24 | if (curNode == null) 25 | return; 26 | if (s.length() == 0) { 27 | if (word.length() == 0) 28 | senList.add(sentence); 29 | return; 30 | } 31 | char c = s.charAt(0); 32 | int ci = c - 'a'; 33 | TrieNode nextNode = curNode.children[ci]; 34 | word += c; 35 | if (nextNode != null) { 36 | dfsWord(s.substring(1), sentence, word, senList, nextNode, root); 37 | if (nextNode.isKey) { 38 | if (sentence.length() > 0) 39 | sentence += " "; 40 | dfsWord(s.substring(1), sentence + word, "", senList, root, 41 | root); 42 | } 43 | } 44 | } 45 | 46 | private class TrieNode { 47 | private static final int R = 26; 48 | TrieNode[] children; 49 | boolean isKey; 50 | 51 | public TrieNode() { 52 | children = new TrieNode[R]; 53 | } 54 | } 55 | 56 | private TrieNode insert(TrieNode node, String s) { 57 | if (node == null) { 58 | node = new TrieNode(); 59 | } 60 | if (s.length() == 0) { 61 | node.isKey = true; 62 | } else { 63 | int c = s.charAt(0) - 'a'; 64 | node.children[c] = insert(node.children[c], s.substring(1)); 65 | } 66 | return node; 67 | } 68 | } -------------------------------------------------------------------------------- /Decode Ways.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-27 3 | */ 4 | public class Solution { 5 | public int numDecodings(String s) { 6 | // Start typing your Java solution below 7 | // DO NOT write main() function 8 | char[] cs = s.toCharArray(); 9 | int n = cs.length; 10 | if(n == 0) 11 | return 0; 12 | int[] ways = new int[n]; 13 | for(int i = 0; i < n; i++){ 14 | if(isLetter1(cs[i])){ 15 | if(i > 0) 16 | ways[i] += ways[i - 1]; 17 | else 18 | ways[i] += 1; 19 | } 20 | if(i >= 1 && isLetter2(cs[i - 1], cs[i])){ 21 | if(i >= 2) 22 | ways[i] += ways[i - 2]; 23 | else 24 | ways[i] += 1; 25 | } 26 | } 27 | return ways[n - 1]; 28 | } 29 | 30 | private boolean isLetter1(char a){ 31 | return a != '0'; 32 | } 33 | 34 | private boolean isLetter2(char a, char b){ 35 | if(a == '0') 36 | return false; 37 | if(a == '1') 38 | return true; 39 | else if(a == '2') 40 | return b <= '6'; 41 | return false; 42 | } 43 | } 44 | 45 | public class Solution { 46 | public int numDecodings(String s) { 47 | // Start typing your Java solution below 48 | // DO NOT write main() function 49 | char[] cs = s.toCharArray(); 50 | if (cs.length == 0) 51 | return 0; 52 | int[] num = new int[cs.length]; 53 | for (int i = 0; i < cs.length; i++) { 54 | if (validChar(cs[i])) { 55 | num[i] += i > 0 ? num[i - 1] : 1; 56 | } 57 | if (valid2Char(cs, i)) { 58 | num[i] += i > 1 ? num[i - 2] : 1; 59 | } 60 | } 61 | return num[cs.length - 1]; 62 | } 63 | 64 | private boolean validChar(char c) { 65 | return c >= '1' && c <= '9'; 66 | } 67 | 68 | private boolean valid2Char(char[] c, int i) { 69 | int len = c.length; 70 | if (i < 1 || len < 2) 71 | return false; 72 | return c[i - 1] == '1' && c[i] >= '0' && c[i] <= '9' || c[i - 1] == '2' 73 | && c[i] >= '0' && c[i] <= '6'; 74 | } 75 | } -------------------------------------------------------------------------------- /Populating Next Right Pointers in Each Node.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Use no extra space. 3 | * Time complexity is O(n) 4 | */ 5 | public class Solution { 6 | public void connect(TreeLinkNode root) { 7 | TreeLinkNode node = null; 8 | TreeLinkNode last = null, curr = null; 9 | TreeLinkNode rowHead = root; 10 | 11 | while (node != null || rowHead != null) { 12 | if (node == null) { 13 | // go to next level. 14 | node = rowHead; 15 | last = null; 16 | curr = null; 17 | rowHead = null; 18 | } 19 | if (node.left != null && curr != node.left) { 20 | curr = node.left; 21 | } else if (node.right != null) { 22 | curr = node.right; 23 | } 24 | if (last != null && last != curr) 25 | last.next = curr; 26 | last = curr; 27 | if (rowHead == null) 28 | rowHead = curr; 29 | if (node.right == null || node.right == curr) 30 | node = node.next; 31 | } 32 | } 33 | } 34 | 35 | /** 36 | * @time: 2013-08-31 37 | * Use a queue to do bfs. 38 | * Time complexity and space complexity are both O(n) 39 | * 40 | * Definition for binary tree with next pointer. 41 | * public class TreeLinkNode { 42 | * int val; 43 | * TreeLinkNode left, right, next; 44 | * TreeLinkNode(int x) { val = x; } 45 | * } 46 | */ 47 | public class Solution { 48 | public void connect(TreeLinkNode root) { 49 | if(root == null) 50 | return; 51 | Queue queue = new LinkedList(); 52 | queue.offer(root); 53 | int leftCount = 1; 54 | TreeLinkNode last = null; 55 | while(!queue.isEmpty()){ 56 | if(leftCount == 0){ 57 | leftCount = queue.size(); 58 | last = null; 59 | } 60 | TreeLinkNode node = queue.poll(); 61 | leftCount--; 62 | if(node.left != null) 63 | queue.offer(node.left); 64 | if(node.right != null) 65 | queue.offer(node.right); 66 | if(last != null) 67 | last.next = node; 68 | last = node; 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Wildcard Matching.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isMatch(String s, String p) { 3 | if (s.length() * p.length() < 1000000) { 4 | matchArray = new short[s.length() + 1][p.length() + 1]; 5 | } 6 | return match(s, 0, s.length(), p, 0, p.length()); 7 | } 8 | 9 | private short[][] matchArray; 10 | 11 | private boolean match(String a, int as, int ae, String b, int bs, int be) { 12 | if (matchArray != null && matchArray[as][bs] != 0) { 13 | return matchArray[as][bs] == 1; 14 | } 15 | boolean res = false; 16 | if (bs == be && as == ae) { 17 | res = true; 18 | } else if (bs == be) { 19 | res = false; 20 | } else { 21 | if (as < ae 22 | && (a.charAt(as) == b.charAt(bs) || b.charAt(bs) == '?')) { 23 | res = match(a, as + 1, ae, b, bs + 1, be); 24 | } else if (b.charAt(bs) == '*') { 25 | if (match(a, as, ae, b, bs + 1, be)) { 26 | res = true; 27 | } else if (as < ae) { 28 | if (match(a, as + 1, ae, b, bs + 1, be)) { 29 | res = true; 30 | } else if (match(a, as + 1, ae, b, bs, be)) { 31 | res = true; 32 | } 33 | } 34 | } 35 | } 36 | if (matchArray != null) { 37 | matchArray[as][bs] = (short) (res ? 1 : -1); 38 | } 39 | return res; 40 | } 41 | } 42 | 43 | public class Solution { 44 | public boolean isMatch(String s, String p) { 45 | char[] cs = s.toCharArray(); 46 | char[] cp = p.toCharArray(); 47 | int lens = cs.length; 48 | int lenp = cp.length; 49 | boolean[][] match = new boolean[lens + 1][lenp + 1]; 50 | match[0][0] = true; 51 | 52 | char a, b; 53 | for (int i = 0; i <= lens; i++) { 54 | for (int j = 0; j <= lenp; j++) { 55 | if (j > 0) { 56 | b = cp[j - 1]; 57 | match[i][j] |= match[i][j - 1] && b == '*'; 58 | if (i > 0) { 59 | a = cs[i - 1]; 60 | match[i][j] |= match[i - 1][j] && b == '*'; 61 | match[i][j] |= match[i - 1][j - 1] && charMatch(a, b); 62 | } 63 | } 64 | } 65 | } 66 | return match[lens][lenp]; 67 | } 68 | 69 | private boolean charMatch(char a, char b) { 70 | return a == b || b == '?' || b == '*'; 71 | } 72 | } -------------------------------------------------------------------------------- /Minimum Window Substring.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String minWindow(String S, String T) { 3 | int lens = S.length(); 4 | int lent = T.length(); 5 | 6 | Map freqT = new HashMap(); 7 | Map freqS = new HashMap(); 8 | Set unmatchSet = new HashSet(); 9 | 10 | for (int i = 0; i < lent; i++) { 11 | char ct = T.charAt(i); 12 | increase(freqT, ct); 13 | unmatchSet.add(ct); 14 | } 15 | 16 | int minWinStart = -1; 17 | int minWinLen = Integer.MAX_VALUE; 18 | int start = 0; 19 | for (int i = 0; i < lens; i++) { 20 | char cs = S.charAt(i); 21 | increase(freqS, cs); 22 | if (unmatchSet.contains(cs) && valDiff(freqS, freqT, cs) >= 0) { 23 | unmatchSet.remove(cs); 24 | } 25 | while (start <= i && unmatchSet.size() == 0) { 26 | int len = i - start + 1; 27 | if (len < minWinLen) { 28 | minWinLen = len; 29 | minWinStart = start; 30 | } 31 | char cstart = S.charAt(start); 32 | decrease(freqS, cstart); 33 | if (valDiff(freqS, freqT, cstart) < 0) { 34 | unmatchSet.add(cstart); 35 | } 36 | start++; 37 | } 38 | } 39 | if (minWinStart == -1) 40 | return ""; 41 | return S.substring(minWinStart, minWinStart + minWinLen); 42 | } 43 | 44 | private int valDiff(Map map1, 45 | Map map2, char c) { 46 | int v1 = 0; 47 | if (map1.containsKey(c)) 48 | v1 = map1.get(c); 49 | int v2 = 0; 50 | if (map2.containsKey(c)) 51 | v2 = map2.get(c); 52 | return v1 - v2; 53 | } 54 | 55 | private void increase(Map map, char c) { 56 | if (map.containsKey(c)) 57 | map.put(c, map.get(c) + 1); 58 | else 59 | map.put(c, 1); 60 | } 61 | 62 | private void decrease(Map map, char c) { 63 | if (map.containsKey(c)) { 64 | int val = map.get(c); 65 | if (val <= 1) 66 | map.remove(c); 67 | else 68 | map.put(c, val - 1); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Spiral Matrix.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | private static int[][] DIRS = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 3 | 4 | public ArrayList spiralOrder(int[][] matrix) { 5 | int n = matrix.length; 6 | int m = n > 0 ? matrix[0].length : 0; 7 | ArrayList res = new ArrayList(); 8 | int[] border = new int[]{0, m - 1, n - 1, 0}; 9 | int x = 0; 10 | int y = 0; 11 | int dir = 0; 12 | for(int i = 0; i < n * m; i++){ 13 | res.add(matrix[x][y]); 14 | int nextDir = (dir + 1) % 4; 15 | if(dir % 2 == 0 && y == border[nextDir] || dir % 2 == 1 && x == border[nextDir]){ 16 | // change direction 17 | border[dir] += DIRS[nextDir][0] + DIRS[nextDir][1]; 18 | dir = nextDir; 19 | } 20 | x += DIRS[dir][0]; 21 | y += DIRS[dir][1]; 22 | } 23 | return res; 24 | } 25 | } 26 | 27 | public class Solution { 28 | public ArrayList spiralOrder(int[][] matrix) { 29 | ArrayList res = new ArrayList(); 30 | spiralOutput(matrix, 0, res); 31 | return res; 32 | } 33 | 34 | private void spiralOutput(int[][] matrix, int index, ArrayList list) { 35 | int m = matrix.length; 36 | if (m == 0) 37 | return; 38 | int n = matrix[0].length; 39 | if (n == 0) 40 | return; 41 | if (Math.min(m, n) <= index * 2) { 42 | return; 43 | } 44 | int i, j; 45 | // (index, index) -> (index, n - index - 1) 46 | for (i = index, j = index; j < n - index; j++) { 47 | list.add(matrix[i][j]); 48 | } 49 | // (index + 1, n - index - 1) -> (n - index - 1, n - index - 1) 50 | for (i = index + 1, j = n - index - 1; i < m - index; i++) { 51 | list.add(matrix[i][j]); 52 | } 53 | // (n - index - 1, n - index - 2) -> (n - index - 1, index) 54 | if (index != m - index - 1) { 55 | for (i = m - index - 1, j = n - index - 2; j >= index; j--) { 56 | list.add(matrix[i][j]); 57 | } 58 | } 59 | // (n - index - 1, index) -> (index + 1, index) 60 | if (index != n - index - 1) { 61 | for (i = m - index - 2, j = index; i > index; i--) { 62 | list.add(matrix[i][j]); 63 | } 64 | } 65 | spiralOutput(matrix, index + 1, list); 66 | } 67 | } -------------------------------------------------------------------------------- /Integer to Roman.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | static Map romans = new HashMap(); 3 | static { 4 | romans.put(1, "I"); 5 | romans.put(5, "V"); 6 | romans.put(10, "X"); 7 | romans.put(50, "L"); 8 | romans.put(100, "C"); 9 | romans.put(500, "D"); 10 | romans.put(1000, "M"); 11 | } 12 | 13 | public String intToRoman(int num) { 14 | List keys = new ArrayList(romans.keySet()); 15 | Collections.sort(keys); 16 | for (int i = keys.size() - 1; i >= 0; i--) { 17 | int ki = keys.get(i); 18 | String si = romans.get(ki); 19 | if (num >= ki) 20 | return si + intToRoman(num - ki); 21 | if (i > 0) { 22 | int kj = keys.get(i - 1 - ((i - 1) % 2)); 23 | String sj = romans.get(kj); 24 | if (num >= ki - kj) 25 | return sj + si + intToRoman(num - (ki - kj)); 26 | } 27 | } 28 | return ""; 29 | } 30 | } 31 | 32 | public class Solution { 33 | private static final char[] ROMAN_CHAR = new char[] { 'I', 'V', 'X', 'L', 34 | 'C', 'D', 'M' }; 35 | private static final Map ROMAN_MAP = new HashMap(); 36 | 37 | static { 38 | ROMAN_MAP.put(0, ""); 39 | ROMAN_MAP.put(1, "I"); 40 | ROMAN_MAP.put(2, "II"); 41 | ROMAN_MAP.put(3, "III"); 42 | ROMAN_MAP.put(4, "IV"); 43 | ROMAN_MAP.put(5, "V"); 44 | ROMAN_MAP.put(6, "VI"); 45 | ROMAN_MAP.put(7, "VII"); 46 | ROMAN_MAP.put(8, "VIII"); 47 | ROMAN_MAP.put(9, "IX"); 48 | } 49 | 50 | public String intToRoman(int num) { 51 | StringBuffer buf = new StringBuffer(); 52 | 53 | int offset = 0; 54 | while (num != 0) { 55 | String roman = toRoman(num % 10, offset); 56 | buf.insert(0, roman); 57 | offset++; 58 | num /= 10; 59 | } 60 | return buf.toString(); 61 | } 62 | 63 | private String toRoman(int num, int offset) { 64 | String digits = ROMAN_MAP.get(num); 65 | int off2 = offset * 2; 66 | if (off2 + 2 < ROMAN_CHAR.length) 67 | digits = digits.replace('X', ROMAN_CHAR[off2 + 2]); 68 | if (off2 + 1 < ROMAN_CHAR.length) 69 | digits = digits.replace('V', ROMAN_CHAR[off2 + 1]); 70 | digits = digits.replace('I', ROMAN_CHAR[off2]); 71 | return digits; 72 | } 73 | } -------------------------------------------------------------------------------- /Binary Tree Zigzag Level Order Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public ArrayList> zigzagLevelOrder(TreeNode root) { 12 | ArrayList> res = new ArrayList>(); 13 | dfs(root, 0, res); 14 | for(int i = 0; i < res.size(); i++){ 15 | if(i % 2 != 0) 16 | Collections.reverse(res.get(i)); 17 | } 18 | return res; 19 | } 20 | 21 | public void dfs(TreeNode root, int depth, ArrayList> res) { 22 | if (root == null) 23 | return; 24 | ArrayList list = null; 25 | if (depth < res.size()) { 26 | list = res.get(depth); 27 | } else { 28 | list = new ArrayList(); 29 | res.add(list); 30 | } 31 | list.add(root.val); 32 | dfs(root.left, depth + 1, res); 33 | dfs(root.right, depth + 1, res); 34 | } 35 | } 36 | 37 | public class Solution { 38 | public ArrayList> zigzagLevelOrder(TreeNode root) { 39 | ArrayList> result = new ArrayList>(); 40 | Deque queue = new LinkedList(); 41 | if(root != null) 42 | queue.add(root); 43 | int nodesLeft = 0; 44 | ArrayList row = null; 45 | boolean reverse = true; 46 | while (!queue.isEmpty()) { 47 | if (nodesLeft == 0) { 48 | nodesLeft = queue.size(); 49 | row = new ArrayList(); 50 | result.add(row); 51 | reverse = !reverse; 52 | } 53 | TreeNode node = null; 54 | if (!reverse) 55 | node = queue.pollFirst(); 56 | else 57 | node = queue.pollLast(); 58 | nodesLeft--; 59 | row.add(node.val); 60 | if (!reverse) { 61 | if (node.left != null) 62 | queue.addLast(node.left); 63 | if (node.right != null) 64 | queue.addLast(node.right); 65 | } else { 66 | if (node.right != null) 67 | queue.addFirst(node.right); 68 | if (node.left != null) 69 | queue.addFirst(node.left); 70 | } 71 | } 72 | return result; 73 | } 74 | } -------------------------------------------------------------------------------- /Longest Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestValidParentheses(String s) { 3 | char[] cs = s.toCharArray(); 4 | int n = cs.length; 5 | Stack stack = new Stack(); 6 | int max = 0; 7 | int size = 0; 8 | for (int i = 0; i < n; i++) { 9 | if (cs[i] == '(') { 10 | stack.push(i); 11 | } else if (stack.size() > 0) { 12 | stack.pop(); 13 | size += 2; 14 | if (stack.size() == 0) 15 | max = Math.max(max, size); 16 | } else { 17 | size = 0; 18 | } 19 | } 20 | int last = n; 21 | while (stack.size() > 0) { 22 | int pop = stack.pop(); 23 | int interval = last - 1 - pop; 24 | max = Math.max(max, interval); 25 | last = pop; 26 | } 27 | return max; 28 | } 29 | } 30 | 31 | public class Solution { 32 | public int longestValidParentheses(String s) { 33 | char[] cs = s.toCharArray(); 34 | int n = cs.length; 35 | int left = 0; 36 | int right = 0; 37 | int max = 0; 38 | for (int i = 0; i < n; i++) { 39 | if (cs[i] == '(') 40 | left++; 41 | else 42 | right++; 43 | if (left == right) 44 | max = Math.max(max, left + right); 45 | else if (right > left) 46 | left = right = 0; 47 | } 48 | 49 | left = right = 0; 50 | for (int i = n - 1; i >= 0; i--) { 51 | if (cs[i] == '(') 52 | left++; 53 | else 54 | right++; 55 | if (left == right) 56 | max = Math.max(max, left + right); 57 | else if (left > right) 58 | left = right = 0; 59 | } 60 | return max; 61 | } 62 | } 63 | 64 | public class Solution { 65 | public int longestValidParentheses(String s) { 66 | int n = s.length(); 67 | int[] dp = new int[n]; 68 | int max = 0; 69 | for (int i = n - 2; i >= 0; i--) { 70 | if (s.charAt(i) == '(') { 71 | int j = i + 1 + dp[i + 1]; 72 | if (j < n && s.charAt(j) == ')') { 73 | dp[i] = dp[i + 1] + 2; 74 | if (j + 1 < n) 75 | dp[i] += dp[j + 1]; 76 | } 77 | max = Math.max(max, dp[i]); 78 | } 79 | } 80 | return max; 81 | } 82 | } -------------------------------------------------------------------------------- /Recover Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-31 3 | * Definition for binary tree 4 | * public class TreeNode { 5 | * int val; 6 | * TreeNode left; 7 | * TreeNode right; 8 | * TreeNode(int x) { val = x; } 9 | * } 10 | */ 11 | public class Solution { 12 | public void recoverTree(TreeNode root) { 13 | // Use stack to perform a inorder traversal 14 | // Find one or two descending points. 15 | Stack stack = new Stack(); 16 | stack.push(root); 17 | TreeNode node = null; 18 | TreeNode last = null; 19 | 20 | TreeNode leftNode = null; 21 | TreeNode rightNode = null; 22 | while(!stack.isEmpty() || node != null){ 23 | if(node != null) { 24 | node = node.left; 25 | } else { 26 | node = stack.pop(); 27 | // visit node here. 28 | if(last == null) 29 | last = node; 30 | else if (last.val > node.val){ 31 | if(leftNode == null){ 32 | leftNode = last; 33 | rightNode = node; 34 | } else { 35 | rightNode = node; 36 | } 37 | } 38 | node = node.right; 39 | } 40 | } 41 | 42 | if(leftNode != null){ 43 | int tmp = leftNode.val; 44 | leftNode.val = rightNode.val; 45 | rightNode.val = tmp; 46 | } 47 | } 48 | } 49 | 50 | public class Solution { 51 | public void recoverTree(TreeNode root) { 52 | TreeNode result = new TreeNode(0); 53 | inorder(root, null, result); 54 | if(result.left != null){ 55 | int tmp = result.left.val; 56 | result.left.val = result.right.val; 57 | result.right.val = tmp; 58 | } 59 | } 60 | 61 | /** 62 | * Return the last node. 63 | * @param parentLast: the largest parent that is smaller than node. 64 | */ 65 | private TreeNode inorder(TreeNode node, TreeNode parentLast, TreeNode result){ 66 | if(node == null) 67 | return null; 68 | TreeNode last = inorder(node.left, parentLast, result); 69 | if(last == null) 70 | last = parentLast; 71 | if(last != null && last.val > node.val){ 72 | if(result.left == null){ 73 | result.left = last; 74 | result.right = node; 75 | } else { 76 | result.right = node; 77 | } 78 | } 79 | // here node is the largest parent node in its right child. 80 | TreeNode rightLast = inorder(node.right, node, result); 81 | return rightLast == null ? node : rightLast; 82 | } 83 | } -------------------------------------------------------------------------------- /Median of Two Sorted Arrays.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-29 3 | * O(log(m) + log(n))) 4 | */ 5 | public class Solution { 6 | public double findMedianSortedArrays(int A[], int B[]) { 7 | int m = A.length; 8 | int n = B.length; 9 | if ((n + m) % 2 == 0) { 10 | return (getMedian(A, 0, m, B, 0, n, (m + n) / 2) + getMedian(A, 0, 11 | m, B, 0, n, (m + n) / 2 + 1)) / 2.0; 12 | } else 13 | return getMedian(A, 0, m, B, 0, n, (m + n) / 2 + 1); 14 | } 15 | 16 | private int getMedian(int a[], int as, int ae, int b[], int bs, int be, 17 | int k) { 18 | int n = ae - as; 19 | int m = be - bs; 20 | if (n <= 0) 21 | return b[bs + k - 1]; 22 | if (m <= 0) 23 | return a[as + k - 1]; 24 | if (k <= 1) 25 | return Math.min(a[as], b[bs]); 26 | int n2 = n / 2; 27 | int m2 = m / 2; 28 | if (b[bs + m / 2] >= a[as + n / 2]) { 29 | if (n2 + m2 + 1 >= k) 30 | return getMedian(a, as, ae, b, bs, bs + m2, k); 31 | else 32 | return getMedian(a, as + n2 + 1, ae, b, bs, be, k - n2 - 1); 33 | } else { 34 | if (n2 + m2 + 1 >= k) 35 | return getMedian(a, as, as + n2, b, bs, be, k); 36 | else 37 | return getMedian(a, as, ae, b, bs + m2 + 1, be, k - m2 - 1); 38 | } 39 | } 40 | } 41 | 42 | /** 43 | * O(log(m + n)) 44 | */ 45 | public class Solution { 46 | public double findMedianSortedArrays(int A[], int B[]) { 47 | int m = A.length; 48 | int n = B.length; 49 | int median1 = (m + n) / 2 + 1; 50 | int median2 = (m + n - 1) / 2 + 1; 51 | return (findKth(A, 0, m, B, 0, n, median1) + findKth(A, 0, m, B, 0, n, 52 | median2)) / 2f; 53 | } 54 | 55 | private int findKth(int a[], int as, int ae, int b[], int bs, int be, int k) { 56 | int m = ae - as; 57 | int n = be - bs; 58 | if (m == 0) { 59 | return b[bs + k - 1]; 60 | } else if (n == 0) { 61 | return a[as + k - 1]; 62 | } 63 | if (m == 1 && n == 1) { 64 | if (k == 1) { 65 | return Math.min(a[as], b[bs]); 66 | } else { 67 | return Math.max(a[as], b[bs]); 68 | } 69 | } 70 | if (k == m + n) { 71 | return Math.max(a[ae - 1], b[be - 1]); 72 | } 73 | float ratio = k * m * 1f / (m + n); 74 | int i = Math.round(m * ratio); 75 | i = fit(i, 0, m - 1); 76 | i = fit(i, k - 1 - n, k - 1); 77 | int j = k - 1 - i; 78 | if (a[as + i] > b[bs + j]) { 79 | return findKth(a, as, as + i, b, bs + j, be, k - j); 80 | } else { 81 | return findKth(a, as + i, ae, b, bs, bs + j, k - i); 82 | } 83 | } 84 | 85 | private int fit(int a, int lower, int upper) { 86 | if (a < lower) 87 | return lower; 88 | else if (a > upper) 89 | return upper; 90 | else 91 | return a; 92 | } 93 | } -------------------------------------------------------------------------------- /Interleaving String.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-28 3 | * A dp solution. 4 | */ 5 | public class Solution { 6 | public boolean isInterleave(String s1, String s2, String s3) { 7 | int l1 = s1.length(); 8 | int l2 = s2.length(); 9 | int l3 = s3.length(); 10 | if(l1 + l2 != l3) 11 | return false; 12 | if(l3 == 0) 13 | return true; 14 | boolean[][] isInter = new boolean[l1 + 1][l2 + 1]; 15 | 16 | for(int i = 0; i <= l1; i++){ 17 | for(int j = 0; j <= l2; j++){ 18 | int k = i + j; 19 | if(k == 0){ 20 | isInter[i][j] = true; 21 | continue; 22 | } 23 | if(i > 0 && s1.charAt(i - 1) == s3.charAt(k - 1)) 24 | isInter[i][j] |= isInter[i - 1][j]; 25 | 26 | if(j > 0 && s2.charAt(j - 1) == s3.charAt(k - 1)) 27 | isInter[i][j] |= isInter[i][j - 1]; 28 | } 29 | } 30 | return isInter[l1][l2]; 31 | } 32 | } 33 | 34 | /** 35 | * Bidirectional search 36 | */ 37 | public class Solution { 38 | public boolean isInterleave(String s1, String s2, String s3) { 39 | int len1 = s1.length(); 40 | int len2 = s2.length(); 41 | int len = s3.length(); 42 | if (len1 + len2 != len) { 43 | return false; 44 | } 45 | return isInter(s1, 0, s1.length(), s2, 0, s2.length(), s3, 0, 46 | s3.length(), true); 47 | } 48 | 49 | private boolean isInter(String s1, int a1, int b1, String s2, int a2, 50 | int b2, String s3, int a3, int b3, boolean forward) { 51 | if (a3 == b3) 52 | return true; 53 | if (a1 < b1) { 54 | if (forward) { 55 | if (s1.charAt(a1) == s3.charAt(a3)) { 56 | boolean f = isInter(s1, a1 + 1, b1, s2, a2, b2, s3, a3 + 1, 57 | b3, !forward); 58 | if (f) 59 | return true; 60 | } 61 | } else { 62 | if (s1.charAt(b1 - 1) == s3.charAt(b3 - 1)) { 63 | boolean f = isInter(s1, a1, b1 - 1, s2, a2, b2, s3, a3, 64 | b3 - 1, !forward); 65 | if (f) 66 | return true; 67 | } 68 | } 69 | } 70 | 71 | if (a2 < b2) { 72 | if (forward) { 73 | if (s2.charAt(a2) == s3.charAt(a3)) { 74 | boolean f = isInter(s1, a1, b1, s2, a2 + 1, b2, s3, a3 + 1, 75 | b3, !forward); 76 | if (f) 77 | return true; 78 | } 79 | } else { 80 | if (s2.charAt(b2 - 1) == s3.charAt(b3 - 1)) { 81 | boolean f = isInter(s1, a1, b1, s2, a2, b2 - 1, s3, a3, 82 | b3 - 1, !forward); 83 | if (f) 84 | return true; 85 | } 86 | } 87 | } 88 | return false; 89 | } 90 | } -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock III.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-13 3 | */ 4 | public class Solution { 5 | public int maxProfit(int[] prices) { 6 | List ps = new ArrayList(); 7 | int last = Integer.MIN_VALUE; 8 | // remove duplicate prices. 9 | for(int p : prices){ 10 | if(p != last) 11 | ps.add(p); 12 | last = p; 13 | } 14 | int n = ps.size(); 15 | prices = new int[n]; 16 | for(int i = 0; i < n; i++) 17 | prices[i] = ps.get(i); 18 | 19 | int[] minLeft = new int[n]; 20 | int[] maxRight = new int[n]; 21 | Arrays.fill(minLeft, Integer.MAX_VALUE); 22 | for(int i = 0; i < n; i++){ 23 | if(i > 0) 24 | minLeft[i] = minLeft[i - 1]; 25 | minLeft[i] = Math.min(minLeft[i], prices[i]); 26 | } 27 | Arrays.fill(maxRight, Integer.MIN_VALUE); 28 | for(int i = n - 1; i >= 0; i--){ 29 | if(i < n - 1) 30 | maxRight[i] = maxRight[i + 1]; 31 | maxRight[i] = Math.max(maxRight[i], prices[i]); 32 | } 33 | 34 | // First round, sell on ith day. 35 | // Second round, buy on jth day. 36 | int profit = 0; 37 | for(int i = 0; i < n; i++){ 38 | for(int j = i; j < n; j++){ 39 | int firstProfit = prices[i] - minLeft[i]; 40 | int secondProfit = maxRight[j] - prices[j]; 41 | profit = Math.max(profit, firstProfit + secondProfit); 42 | } 43 | } 44 | return profit; 45 | } 46 | } 47 | 48 | 49 | public class Solution { 50 | public int maxProfit(int[] prices) { 51 | // only record the header and footer of acsending sequence. 52 | List pList = new ArrayList(); 53 | int lastIndex = 0; 54 | for(int i = 1; i < prices.length; i++){ 55 | if(prices[i] < prices[i - 1]){ 56 | if(i - lastIndex > 1){ 57 | pList.add(prices[lastIndex]); 58 | pList.add(prices[i - 1]); 59 | } 60 | lastIndex = i; 61 | } 62 | } 63 | if(prices.length - lastIndex > 1){ 64 | pList.add(prices[lastIndex]); 65 | pList.add(prices[prices.length - 1]); 66 | } 67 | 68 | Integer[] pricesInt = pList.toArray(new Integer[] {}); 69 | int len = pricesInt.length; 70 | int[][] min = new int[len][len]; 71 | for (int i = 0; i < len; i++) { 72 | min[i][i] = pricesInt[i]; 73 | for (int j = i + 1; j < len; j++) { 74 | min[i][j] = pricesInt[j] < min[i][j - 1] ? pricesInt[j] 75 | : min[i][j - 1]; 76 | } 77 | } 78 | int max = 0; 79 | for (int i = 0; i < len; i++) { 80 | int value = pricesInt[i] - min[0][i]; 81 | max = value > max ? value : max; 82 | for (int j = i + 1; j < len; j++) { 83 | int value2 = value + pricesInt[j] - min[i + 1][j]; 84 | max = value2 > max ? value2 : max; 85 | } 86 | } 87 | return max; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Scramble String.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-09-01 3 | * use 3d dp. time complexity is O(n^4) 4 | */ 5 | public class Solution { 6 | public boolean isScramble(String s1, String s2) { 7 | int n = s1.length(); 8 | if(n != s2.length()) 9 | return false; 10 | if(n == 0) 11 | return true; 12 | // dp[i][j][k] is true iff s1[i:i+k] and s2[j:j+k] is scramble 13 | boolean[][][] dp = new boolean[n][n][n + 1]; 14 | for(int k = 1; k <= n; k++){ 15 | for(int i = 0; i <= n - k; i++){ 16 | for(int j = 0; j <= n - k; j++){ 17 | boolean res = false; 18 | for(int m = 1; m < k && !res; m++){ 19 | res |= dp[i][j][m] && dp[i + m][j + m][k - m]; 20 | res |= dp[i][j + k - m][m] && dp[i + m][j][k - m]; 21 | } 22 | if(k == 1) 23 | res = s1.charAt(i) == s2.charAt(j); 24 | dp[i][j][k] = res; 25 | } 26 | } 27 | } 28 | return dp[0][0][n]; 29 | } 30 | } 31 | 32 | public class Solution { 33 | public boolean isScramble(String s1, String s2) { 34 | int n1 = s1.length(); 35 | int n2 = s2.length(); 36 | if (n1 != n2) { 37 | return false; 38 | } 39 | return isScramble(s1.toCharArray(), 0, n1, s2.toCharArray(), 0, n2); 40 | } 41 | 42 | private boolean isScramble(char[] s1, int beg1, int end1, char[] s2, 43 | int beg2, int end2) { 44 | int n = end1 - beg1; 45 | if (n == 1) { 46 | return s1[beg1] == s2[beg2]; 47 | } 48 | CountMap map1 = new CountMap(); 49 | CountMap map2 = new CountMap(); 50 | 51 | for (int i = 0; i < n - 1; i++) { 52 | map1.add(s1[beg1 + i]); 53 | map2.add(s2[beg2 + i]); 54 | if (map1.equals(map2)) { 55 | boolean a1 = isScramble(s1, beg1, beg1 + i + 1, s2, beg2, beg2 56 | + i + 1); 57 | boolean b1 = isScramble(s1, beg1 + i + 1, end1, s2, beg2 + i 58 | + 1, end2); 59 | if (a1 && b1) { 60 | return true; 61 | } 62 | } 63 | } 64 | 65 | map1.clear(); 66 | map2.clear(); 67 | for (int i = 0; i < n - 1; i++) { 68 | map1.add(s1[beg1 + i]); 69 | map2.add(s2[end2 - 1 - i]); 70 | if (map1.equals(map2)) { 71 | boolean a2 = isScramble(s1, beg1, beg1 + i + 1, s2, end2 - 1 72 | - i, end2); 73 | boolean b2 = isScramble(s1, beg1 + i + 1, end1, s2, beg2, end2 74 | - 1 - i); 75 | if (a2 && b2) { 76 | return true; 77 | } 78 | } 79 | } 80 | return false; 81 | } 82 | 83 | class CountMap extends HashMap { 84 | public void add(Character c) { 85 | Integer count = get(c); 86 | if (count == null) { 87 | put(c, 1); 88 | } else { 89 | put(c, count + 1); 90 | } 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /Add Binary.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String addBinary(String a, String b) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | char[] ca = a.toCharArray(); 6 | char[] cb = b.toCharArray(); 7 | int lena = ca.length; 8 | int lenb = cb.length; 9 | reverse(ca); 10 | reverse(cb); 11 | offset(ca, -'0'); 12 | offset(cb, -'0'); 13 | int lenc = Math.max(lena, lenb) + 1; 14 | char[] cc = new char[lenc]; 15 | Arrays.fill(cc, '\0'); 16 | add(cc, ca); 17 | add(cc, cb); 18 | offset(cc, '0'); 19 | reverse(cc); 20 | int index = 0; 21 | while (index < cc.length - 1 && cc[index] == '0') { 22 | index++; 23 | } 24 | return new String(cc, index, cc.length - index); 25 | } 26 | 27 | private void add(char[] ca, char[] cb) { 28 | for (int i = 0; i < ca.length - 1; i++) { 29 | if (i < cb.length) { 30 | ca[i] += cb[i]; 31 | } 32 | ca[i + 1] += ca[i] / 2; 33 | ca[i] %= 2; 34 | } 35 | } 36 | 37 | private void offset(char[] c, int value) { 38 | for (int i = 0; i < c.length; i++) { 39 | c[i] += value; 40 | } 41 | } 42 | 43 | private void reverse(char[] c) { 44 | int len = c.length; 45 | char tmp; 46 | for (int i = 0; i < len / 2; i++) { 47 | tmp = c[i]; 48 | c[i] = c[len - 1 - i]; 49 | c[len - 1 - i] = tmp; 50 | } 51 | } 52 | } 53 | 54 | /** 55 | * @time: 2013-08-26 56 | */ 57 | public class Solution { 58 | public String addBinary(String a, String b) { 59 | // Start typing your Java solution below 60 | // DO NOT write main() function 61 | char[] as = a.toCharArray(); 62 | char[] bs = b.toCharArray(); 63 | reverse(as); 64 | reverse(bs); 65 | char[] cs = add(as, bs); 66 | reverse(cs); 67 | 68 | int i = 0; 69 | while(i < cs.length - 1 && cs[i] == '0') 70 | i++; 71 | 72 | return new String(cs, i, cs.length - i); 73 | 74 | } 75 | 76 | private char[] add(char[] as, char[] bs){ 77 | int lena = as.length; 78 | int lenb = bs.length; 79 | int lenc = Math.max(lena, lenb) + 1; 80 | char[] cs = new char[lenc]; 81 | Arrays.fill(cs, '0'); 82 | 83 | for(int i = 0; i < lenc - 1; i++){ 84 | int val = cs[i] - '0'; 85 | if(i < lena) 86 | val += as[i] - '0'; 87 | if(i < lenb) 88 | val += bs[i] - '0'; 89 | cs[i] = (char)(val % 2 + '0'); 90 | cs[i + 1] += (char)(val / 2); 91 | } 92 | return cs; 93 | } 94 | 95 | private void reverse(char[] c){ 96 | int i = 0; 97 | int j = c.length - 1; 98 | while(i < j){ 99 | swap(c, i++, j--); 100 | } 101 | } 102 | 103 | private void swap(char[] c, int i, int j){ 104 | char tmp = c[i]; 105 | c[i] = c[j]; 106 | c[j] = tmp; 107 | } 108 | } -------------------------------------------------------------------------------- /Multiply Strings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @time: 2013-08-30 3 | */ 4 | public class Solution { 5 | public String multiply(String num1, String num2) { 6 | char[] cs1 = num1.toCharArray(); 7 | char[] cs2 = num2.toCharArray(); 8 | reverse(cs1); 9 | reverse(cs2); 10 | char[] cs = mul(cs1, cs2); 11 | reverse(cs); 12 | 13 | int n = cs.length; 14 | int start = 0; 15 | for(;start < n - 1 && cs[start] == '0'; start++) 16 | ; 17 | return new String(cs, start, n - start); 18 | } 19 | 20 | private char[] mul(char[] cs1, char[] cs2){ 21 | int n1 = cs1.length; 22 | int n2 = cs2.length; 23 | int n = n1 + n2; 24 | char[] cs = new char[n]; 25 | Arrays.fill(cs, '0'); 26 | for(int i = 0; i < n1; i++){ 27 | for(int j = 0; j < n2; j++){ 28 | int val = (cs1[i] - '0') * (cs2[j] - '0') + cs[i + j] - '0'; 29 | cs[i + j] = (char) (val % 10 + '0'); 30 | if(i + j + 1 < n) 31 | cs[i + j + 1] += val / 10; 32 | } 33 | } 34 | return cs; 35 | } 36 | 37 | private void reverse(char[] cs){ 38 | int i = 0; 39 | int j = cs.length - 1; 40 | while(i < j){ 41 | swap(cs, i++, j--); 42 | } 43 | } 44 | 45 | private void swap(char[] cs, int i, int j){ 46 | char tmp = cs[i]; 47 | cs[i] = cs[j]; 48 | cs[j] = tmp; 49 | } 50 | } 51 | 52 | public class Solution { 53 | public String multiply(String num1, String num2) { 54 | char[] cs1 = num1.toCharArray(); 55 | char[] cs2 = num2.toCharArray(); 56 | offset(cs1, -'0'); 57 | offset(cs2, -'0'); 58 | char[] cs3 = mul(cs1, cs2); 59 | offset(cs3, '0'); 60 | return getTrimString(cs3); 61 | } 62 | 63 | private String getTrimString(char[] cs){ 64 | int n = cs.length; 65 | int i = 0; 66 | while(i < n - 1 && cs[i] == '0'){ 67 | i++; 68 | } 69 | return new String(cs, i, n - i); 70 | } 71 | 72 | private char[] mul(char[] cs1, char[] cs2){ 73 | int n1 = cs1.length; 74 | int n2 = cs2.length; 75 | char[] cs3 = new char[n1 + n2 + 1]; 76 | reverse(cs1); 77 | reverse(cs2); 78 | for(int i = 0; i < n1; i++){ 79 | for(int j = 0; j < n2; j++){ 80 | cs3[i + j] += cs1[i] * cs2[j]; 81 | cs3[i + j + 1] += (char)(cs3[i + j] / 10); 82 | cs3[i + j] = (char)(cs3[i + j] % 10); 83 | } 84 | } 85 | reverse(cs3); 86 | return cs3; 87 | } 88 | 89 | private void reverse(char[] cs){ 90 | int i = 0, j = cs.length - 1; 91 | while(i < j){ 92 | swap(cs, i++, j--); 93 | } 94 | } 95 | 96 | private void swap(char[] cs, int i, int j){ 97 | char tmp = cs[i]; 98 | cs[i] = cs[j]; 99 | cs[j] = tmp; 100 | } 101 | 102 | private void offset(char[] cs, int offset){ 103 | for(int i = 0; i < cs.length; i++){ 104 | cs[i] += (char)offset; 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /Regular Expression Matching.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isMatch(String s, String p) { 3 | char[] cs = s.toCharArray(); 4 | char[] ps = p.toCharArray(); 5 | int lens = cs.length; 6 | int lenp = ps.length; 7 | boolean[] isStar = new boolean[lenp]; 8 | int pi = 0; 9 | for (int i = 0; i < lenp; i++, pi++) { 10 | ps[pi] = ps[i]; 11 | if (isStar(ps, i)) { 12 | isStar[pi] = true; 13 | i++; 14 | } 15 | } 16 | lenp = pi; 17 | // match[i][j] == isMatch(s[0:i], p[0:j]) 18 | boolean[][] match = new boolean[lens + 1][lenp + 1]; 19 | for (int i = 0; i <= lens; i++) { 20 | for (int j = 0; j <= lenp; j++) { 21 | if (i + j == 0) { 22 | match[i][j] = true; 23 | continue; 24 | } 25 | if (i * j > 0 && (cs[i - 1] == ps[j - 1] || ps[j - 1] == '.')) { 26 | match[i][j] |= match[i - 1][j - 1]; 27 | if (isStar[j - 1]) 28 | match[i][j] |= match[i - 1][j]; 29 | } 30 | if (j > 0 && isStar[j - 1]) { 31 | match[i][j] |= match[i][j - 1]; 32 | } 33 | } 34 | } 35 | return match[lens][lenp]; 36 | } 37 | 38 | private boolean isStar(char[] a, int i) { 39 | return i + 1 < a.length && a[i + 1] == '*'; 40 | } 41 | } 42 | 43 | public class Solution { 44 | public boolean isMatch(String s, String p) { 45 | char[] as = s.toCharArray(); 46 | char[] bs = p.toCharArray(); 47 | for (int i = 0; i < bs.length; i++) { 48 | if (Character.isLetter(bs[i]) && !isStarLetter(bs, i)) { 49 | boolean contain = false; 50 | for (int j = 0; j < as.length; j++) { 51 | if (bs[i] == as[j]) { 52 | contain = true; 53 | break; 54 | } 55 | } 56 | if (!contain) 57 | return false; 58 | } 59 | } 60 | return match(s.toCharArray(), 0, p.toCharArray(), 0); 61 | } 62 | 63 | private boolean match(char[] as, int ai, char[] bs, int bi) { 64 | int an = as.length; 65 | int bn = bs.length; 66 | 67 | if ((bn - bi) * (an - ai) == 0) { 68 | while (bi < bn && isStarLetter(bs, bi)) { 69 | bi += 2; 70 | } 71 | return bn - bi + an - ai == 0; 72 | } 73 | 74 | if (as[ai] == bs[bi] || bs[bi] == '.') { 75 | if (isStarLetter(bs, bi)) { 76 | return match(as, ai + 1, bs, bi) 77 | || match(as, ai + 1, bs, bi + 2) 78 | || match(as, ai, bs, bi + 2); 79 | } else { 80 | return match(as, ai + 1, bs, bi + 1); 81 | } 82 | } else { 83 | if (isStarLetter(bs, bi)) { 84 | return match(as, ai, bs, bi + 2); 85 | } else { 86 | return false; 87 | } 88 | } 89 | } 90 | 91 | private boolean isStarLetter(char[] a, int i) { 92 | return i + 1 < a.length && a[i + 1] == '*'; 93 | } 94 | } -------------------------------------------------------------------------------- /3Sum Closest.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int threeSumClosest(int[] num, int target) { 3 | // Start typing your Java solution below 4 | // DO NOT write main() function 5 | Arrays.sort(num); 6 | int len = num.length; 7 | int min = Integer.MAX_VALUE; 8 | for (int i = 0; i < len - 2; i++) { 9 | for (int j = i + 1; j < len - 1; j++) { 10 | int value = target - num[i] - num[j]; 11 | int k = bsearch1(num, j + 1, len, value); 12 | if (k < j + 1) { 13 | k = j + 1; 14 | } 15 | if (k + 1 < len 16 | && Math.abs(value - num[k + 1]) < Math.abs(value 17 | - num[k])) { 18 | k++; 19 | } 20 | value -= num[k]; 21 | if (Math.abs(value) < Math.abs(min)) { 22 | min = value; 23 | } 24 | } 25 | } 26 | return target - min; 27 | } 28 | 29 | private int bsearch(int[] n, int start, int end, int target) { 30 | if (end - start == 1) { 31 | return target >= n[start] ? start : start - 1; 32 | } 33 | int mid = (start + end) / 2; 34 | if (n[mid] <= target) { 35 | return bsearch(n, mid, end, target); 36 | } else { 37 | return bsearch(n, start, mid, target); 38 | } 39 | } 40 | 41 | private int bsearch1(int[] n, int start, int end, int target) { 42 | int mid = start; 43 | while (start + 1 < end) { 44 | mid = (start + end) / 2; 45 | if (n[mid] <= target) { 46 | start = mid; 47 | } else { 48 | end = mid; 49 | } 50 | } 51 | return target >= n[start] ? start : start - 1; 52 | } 53 | 54 | private int bsearch2(int[] n, int start, int end, int target){ 55 | int mid; 56 | while(start < end){ 57 | mid = (start + end) / 2; 58 | if (n[mid] < target){ 59 | start = mid + 1; 60 | } else if(n[mid] > target){ 61 | end = mid; 62 | } else{ 63 | return mid; 64 | } 65 | } 66 | return start - 1; 67 | } 68 | 69 | } 70 | 71 | /** 72 | * Second version. 73 | * @time: 20130822 74 | */ 75 | public class Solution { 76 | public int threeSumClosest(int[] num, int target) { 77 | // Start typing your Java solution below 78 | // DO NOT write main() function 79 | Arrays.sort(num); 80 | 81 | int minDiff = Integer.MAX_VALUE; 82 | int n = num.length; 83 | for (int i = 0; i < n; i++) { 84 | for (int j = i + 1; j < n; j++) { 85 | int diff = minDiff(num, j + 1, n, target - num[i] - num[j]); 86 | if (Math.abs(diff) < Math.abs(minDiff)) 87 | minDiff = diff; 88 | } 89 | } 90 | return target - minDiff; 91 | } 92 | 93 | private int minDiff(int[] array, int s, int e, int target) { 94 | int i = bsearch(array, s, e, target); 95 | int minDiff = Integer.MAX_VALUE; 96 | for (int j = 0; j < 2; j++, i++) { 97 | if (i >= s && i < e) { 98 | if (Math.abs(target - array[i]) < Math.abs(minDiff)) { 99 | minDiff = target - array[i]; 100 | } 101 | } 102 | } 103 | return minDiff; 104 | } 105 | 106 | public int bsearch(int[] array, int s, int e, int target) { 107 | if (e - s == 0) { 108 | return s - 1; 109 | } 110 | int mid = (e + s) / 2; 111 | int val = array[mid]; 112 | if (target == val) { 113 | return mid; 114 | } else if (target > val) { 115 | return bsearch(array, mid + 1, e, target); 116 | } else { 117 | return bsearch(array, s, mid, target); 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /Anagrams.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList anagrams(String[] strs) { 3 | ArrayList res = new ArrayList(); 4 | List anas = new ArrayList(); 5 | for (String s : strs) 6 | anas.add(new Word(s)); 7 | Collections.sort(anas); 8 | int lastIndex = 0; 9 | int i = 1; 10 | for (; i < anas.size(); i++) { 11 | if (anas.get(i).compareTo(anas.get(i - 1)) == 0) { 12 | continue; 13 | } else { 14 | if (i - lastIndex >= 2) 15 | for (int j = lastIndex; j < i; j++) 16 | res.add(anas.get(j).val); 17 | lastIndex = i; 18 | } 19 | } 20 | if (i - lastIndex >= 2) 21 | for (int j = lastIndex; j < i; j++) 22 | res.add(anas.get(j).val); 23 | return res; 24 | } 25 | 26 | class Word implements Comparable { 27 | String val; 28 | int[] features = new int[26]; 29 | 30 | public Word(String v) { 31 | val = v; 32 | for (char c : val.toCharArray()) 33 | features[c - 'a']++; 34 | } 35 | 36 | @Override 37 | public int compareTo(Word w) { 38 | for (int i = 0; i < 26; i++) 39 | if (features[i] != w.features[i]) 40 | return features[i] - w.features[i]; 41 | return 0; 42 | } 43 | } 44 | } 45 | 46 | public class Solution { 47 | public ArrayList anagrams(String[] strs) { 48 | List strFeatures = new ArrayList(); 49 | for (String s : strs) 50 | strFeatures.add(new StrFeature(s)); 51 | Collections.sort(strFeatures); 52 | 53 | ArrayList result = new ArrayList(); 54 | int lastI = 0; 55 | int i = 0; 56 | for (; i < strFeatures.size(); i++) { 57 | StrFeature cur = strFeatures.get(i); 58 | StrFeature last = strFeatures.get(lastI); 59 | if (cur.compareTo(last) != 0) { 60 | if (i - lastI > 1) 61 | for (int j = lastI; j < i; j++) 62 | result.add(strFeatures.get(j).str); 63 | lastI = i; 64 | } 65 | } 66 | if (i - lastI > 1) 67 | for (int j = lastI; j < i; j++) 68 | result.add(strFeatures.get(j).str); 69 | return result; 70 | } 71 | 72 | private class StrFeature implements Comparable { 73 | private TreeMap feas; 74 | public String str; 75 | 76 | public StrFeature(String s) { 77 | str = s; 78 | feas = new TreeMap(); 79 | for (char c : s.toCharArray()) { 80 | if (feas.containsKey(c)) { 81 | feas.put(c, feas.get(c) + 1); 82 | } else { 83 | feas.put(c, 1); 84 | } 85 | } 86 | } 87 | 88 | public int compareTo(StrFeature str) { 89 | if (str == null) 90 | return 1; 91 | TreeMap mapa = feas; 92 | TreeMap mapb = str.feas; 93 | if (mapa.size() != mapb.size()) 94 | return mapa.size() - mapb.size(); 95 | Iterator itera = mapa.keySet().iterator(); 96 | Iterator iterb = mapb.keySet().iterator(); 97 | while (itera.hasNext()) { 98 | char ca = itera.next(); 99 | char cb = iterb.next(); 100 | if (ca != cb) 101 | return ca - cb; 102 | int fa = mapa.get(ca); 103 | int fb = mapb.get(cb); 104 | if (fa != fb) 105 | return fa - fb; 106 | } 107 | return 0; 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /3Sum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Solution { 3 | public ArrayList> threeSum(int[] num) { 4 | // Start typing your Java solution below 5 | // DO NOT write main() function 6 | Set> set = new HashSet>(); 7 | Arrays.sort(num); 8 | int len = num.length; 9 | for(int i = 0; i < len - 2; i++){ 10 | for(int j = i + 1; j < len - 1; j++){ 11 | int k = bsearch(num, j + 1, len, -num[i] - num[j]); 12 | if(k >= 0){ 13 | ArrayList list = new ArrayList(); 14 | list.add(num[i]); 15 | list.add(num[j]); 16 | list.add(num[k]); 17 | set.add(list); 18 | } 19 | } 20 | } 21 | ArrayList> res = new ArrayList>(); 22 | res.addAll(set); 23 | return res; 24 | } 25 | 26 | private int bsearch(int[] n, int start, int end, int target){ 27 | if(end == start){ 28 | return -1; 29 | } 30 | int mid = (start + end) / 2; 31 | if(n[mid] < target){ 32 | return bsearch(n, mid + 1, end, target); 33 | }else if(n[mid] > target){ 34 | return bsearch(n, start, mid, target); 35 | }else{ 36 | return mid; 37 | } 38 | } 39 | } 40 | 41 | 42 | public class Solution { 43 | public ArrayList> threeSum(int[] num) { 44 | // Start typing your Java solution below 45 | // DO NOT write main() function 46 | Arrays.sort(num); 47 | int n = num.length; 48 | ArrayList> res = new ArrayList>(); 49 | Set> resSet = new HashSet>(); 50 | for(int i = 0; i < n; i++){ 51 | int target = -num[i]; 52 | int s = i + 1; 53 | int e = n - 1; 54 | while(s < e){ 55 | if (num[s] + num[e] == target){ 56 | ArrayList items = new ArrayList(); 57 | items.add(num[i]); 58 | items.add(num[s]); 59 | items.add(num[e]); 60 | Collections.sort(items); 61 | resSet.add(items); 62 | e--; 63 | s++; 64 | } else if(num[s] + num[e] > target){ 65 | e--; 66 | } else{ 67 | s++; 68 | } 69 | } 70 | } 71 | res.addAll(resSet); 72 | return res; 73 | } 74 | } 75 | 76 | /** 77 | * @time: 2013-08-22 78 | */ 79 | public class Solution { 80 | public ArrayList> threeSum(int[] num) { 81 | // Start typing your Java solution below 82 | // DO NOT write main() function 83 | Arrays.sort(num); 84 | 85 | int n = num.length; 86 | Set> resultSet = new HashSet>(); 87 | for (int i = 0; i < n; i++) { 88 | int s = i + 1; 89 | int e = n - 1; 90 | while(s < e){ 91 | int val = num[i] + num[s] + num[e]; 92 | if(val == 0){ 93 | ArrayList list = new ArrayList(); 94 | list.add(num[i]); 95 | list.add(num[s]); 96 | list.add(num[e]); 97 | resultSet.add(list); 98 | s++; 99 | e--; 100 | } else if(val > 0) { 101 | e--; 102 | } else { 103 | s++; 104 | } 105 | } 106 | } 107 | ArrayList> resultList = new ArrayList>(); 108 | resultList.addAll(resultSet); 109 | Collections.sort(resultList, new Comparator>(){ 110 | public int compare(ArrayList a, ArrayList b){ 111 | for(int i = 0; i < a.size(); i++){ 112 | if(a.get(i) != b.get(i)) 113 | return a.get(i) - b.get(i); 114 | } 115 | return 0; 116 | } 117 | }); 118 | return resultList; 119 | } 120 | } 121 | 122 | -------------------------------------------------------------------------------- /Word Ladder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Time complexity: 26 * n * logn. 3 | */ 4 | public class Solution { 5 | public int ladderLength(String start, String end, HashSet dict) { 6 | dict.add(start); 7 | dict.add(end); 8 | Map> graph = buildGraph(dict); 9 | 10 | // perform a bfs to get shortest steps. 11 | Queue queue = new LinkedList(); 12 | queue.offer(start); 13 | int leftCount = 0; 14 | int step = 0; 15 | Set visited = new HashSet(); 16 | while (!queue.isEmpty()) { 17 | if (leftCount == 0) { 18 | leftCount = queue.size(); 19 | step++; 20 | } 21 | String node = queue.poll(); 22 | leftCount--; 23 | List adj = graph.get(node); 24 | if (adj != null) 25 | for (String s : adj) 26 | if (!visited.contains(s)) { 27 | if (s.equals(end)) 28 | return step + 1; 29 | queue.offer(s); 30 | visited.add(s); 31 | } 32 | 33 | } 34 | return 0; 35 | } 36 | 37 | // use sort to build the graph 38 | private Map> buildGraph(Set dict) { 39 | List nodes = new ArrayList(); 40 | Map> graph = new HashMap>(); 41 | nodes.addAll(dict); 42 | int wordLen = nodes.get(0).length(); 43 | int n = nodes.size(); 44 | NodeComparator cmp = new NodeComparator(); 45 | for (int maski = 0; maski < wordLen; maski++) { 46 | cmp.mask = maski; 47 | Collections.sort(nodes, cmp); 48 | int lasti = 0; 49 | for (int i = 0; i <= n; i++) { 50 | if (i == n || cmp.compare(nodes.get(i), nodes.get(lasti)) != 0) { 51 | for (int x = lasti; x < i; x++) 52 | for (int y = lasti; y < i; y++) 53 | if (x != y) 54 | addMap(graph, nodes.get(x), nodes.get(y)); 55 | lasti = i; 56 | } 57 | } 58 | } 59 | return graph; 60 | } 61 | 62 | private void addMap(Map> map, String a, String b) { 63 | if (map.containsKey(a)) { 64 | map.get(a).add(b); 65 | } else { 66 | List list = new ArrayList(); 67 | list.add(b); 68 | map.put(a, list); 69 | } 70 | } 71 | 72 | private class NodeComparator implements Comparator { 73 | int mask = -1; 74 | 75 | @Override 76 | public int compare(String a, String b) { 77 | for (int i = 0; i < a.length(); i++) 78 | if (i != mask && a.charAt(i) != b.charAt(i)) 79 | return a.charAt(i) - b.charAt(i); 80 | return 0; 81 | } 82 | } 83 | } 84 | 85 | /** 86 | * Time complexity: n * 26 * wordlen^2 87 | */ 88 | public class Solution { 89 | public int ladderLength(String start, String end, HashSet dict) { 90 | Set visited = new HashSet(); 91 | Queue queue = new LinkedList(); 92 | queue.offer(start); 93 | int step = 0; 94 | int leftCount = 0; 95 | while (!queue.isEmpty()) { 96 | if (leftCount == 0) { 97 | leftCount = queue.size(); 98 | step++; 99 | } 100 | String node = queue.poll(); 101 | leftCount--; 102 | char[] cs = node.toCharArray(); 103 | for (int i = 0; i < cs.length; i++) { 104 | char tmp = cs[i]; 105 | for (char c = 'a'; c <= 'z'; c++) { 106 | if (c == tmp) 107 | continue; 108 | cs[i] = c; 109 | String str = new String(cs); 110 | if(str.equals(end)){ 111 | return step + 1; 112 | } 113 | if (dict.contains(str) && !visited.contains(str)){ 114 | queue.offer(str); 115 | visited.add(str); 116 | } 117 | } 118 | cs[i] = tmp; 119 | } 120 | } 121 | return 0; 122 | } 123 | } -------------------------------------------------------------------------------- /Word Ladder II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList> findLadders(String start, String end, 3 | HashSet dict) { 4 | // bfs get search path. 5 | Map> last = bfsPaths(start, end, dict); 6 | // dfs get all shortest path 7 | ArrayList> paths = new ArrayList>(); 8 | dfsPaths(end, start, last, new ArrayList(), paths); 9 | return paths; 10 | } 11 | 12 | // Use builded graph to perform bfs. 13 | private Map> bfsPaths(String start, String end, 14 | Set dict) { 15 | Set visited = new HashSet(); 16 | Set newAdded = new HashSet(); 17 | Queue queue = new LinkedList(); 18 | queue.offer(start); 19 | int leftCount = 0; 20 | Map> last = new HashMap>(); 21 | Map> graph = buildGraph(dict); 22 | while (!queue.isEmpty()) { 23 | if (leftCount == 0) { 24 | leftCount = queue.size(); 25 | if (newAdded.contains(end)) { 26 | break; 27 | } 28 | visited.addAll(newAdded); 29 | newAdded.clear(); 30 | } 31 | String node = queue.poll(); 32 | leftCount--; 33 | List adj = graph.get(node); 34 | if (adj != null) 35 | for (String str : adj) 36 | if (!visited.contains(str)) { 37 | if (!newAdded.contains(str)) { 38 | queue.offer(str); 39 | newAdded.add(str); 40 | } 41 | addMap(last, str, node); 42 | } 43 | } 44 | return last; 45 | } 46 | 47 | // Iterate all possible path to perform bfs. 48 | private Map> bfsPaths2(String start, String end, 49 | Set dict) { 50 | Set visited = new HashSet(); 51 | Set newAdded = new HashSet(); 52 | Queue queue = new LinkedList(); 53 | queue.offer(start); 54 | int leftCount = 0; 55 | Map> last = new HashMap>(); 56 | while (!queue.isEmpty()) { 57 | if (leftCount == 0) { 58 | leftCount = queue.size(); 59 | if (newAdded.contains(end)) { 60 | break; 61 | } 62 | visited.addAll(newAdded); 63 | newAdded.clear(); 64 | } 65 | String node = queue.poll(); 66 | leftCount--; 67 | char[] cs = node.toCharArray(); 68 | for (int i = 0; i < cs.length; i++) { 69 | char tmp = cs[i]; 70 | for (char c = 'a'; c <= 'z'; c++) { 71 | if (c == tmp) 72 | continue; 73 | cs[i] = c; 74 | String str = new String(cs); 75 | if (dict.contains(str) && !visited.contains(str)) { 76 | if (!newAdded.contains(str)) { 77 | queue.offer(str); 78 | newAdded.add(str); 79 | } 80 | addMap(last, str, node); 81 | } 82 | } 83 | cs[i] = tmp; 84 | } 85 | } 86 | return last; 87 | } 88 | 89 | private void dfsPaths(String end, String start, 90 | Map> last, ArrayList path, 91 | ArrayList> paths) { 92 | path.add(end); 93 | if (end.equals(start)) { 94 | ArrayList cpath = new ArrayList(); 95 | cpath.addAll(path); 96 | Collections.reverse(cpath); 97 | paths.add(cpath); 98 | } else { 99 | if (last.containsKey(end)) 100 | for (String next : last.get(end)) { 101 | dfsPaths(next, start, last, path, paths); 102 | } 103 | } 104 | path.remove(path.size() - 1); 105 | } 106 | 107 | // use sort to build the graph 108 | private Map> buildGraph(Set dict) { 109 | List nodes = new ArrayList(); 110 | Map> graph = new HashMap>(); 111 | nodes.addAll(dict); 112 | int wordLen = nodes.get(0).length(); 113 | int n = nodes.size(); 114 | NodeComparator cmp = new NodeComparator(); 115 | for (int maski = 0; maski < wordLen; maski++) { 116 | cmp.mask = maski; 117 | Collections.sort(nodes, cmp); 118 | int lasti = 0; 119 | for (int i = 0; i <= n; i++) { 120 | if (i == n || cmp.compare(nodes.get(i), nodes.get(lasti)) != 0) { 121 | for (int x = lasti; x < i; x++) 122 | for (int y = lasti; y < i; y++) 123 | if (x != y) 124 | addMap(graph, nodes.get(x), nodes.get(y)); 125 | lasti = i; 126 | } 127 | } 128 | } 129 | return graph; 130 | } 131 | 132 | private class NodeComparator implements Comparator { 133 | int mask = -1; 134 | 135 | @Override 136 | public int compare(String a, String b) { 137 | for (int i = 0; i < a.length(); i++) 138 | if (i != mask && a.charAt(i) != b.charAt(i)) 139 | return a.charAt(i) - b.charAt(i); 140 | return 0; 141 | } 142 | } 143 | 144 | private void addMap(Map> map, String a, String b) { 145 | if (map.containsKey(a)) { 146 | map.get(a).add(b); 147 | } else { 148 | List list = new ArrayList(); 149 | list.add(b); 150 | map.put(a, list); 151 | } 152 | } 153 | } --------------------------------------------------------------------------------