From 2fead350368c3c722ae73a1d3bcf944d69207814 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 31 Oct 2013 11:15:03 +0800 Subject: [PATCH 001/456] Updated the solution --- .../PalindromePartitioningII.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java b/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java index 0d5cdac..a0257b5 100644 --- a/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java +++ b/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java @@ -16,7 +16,7 @@ public int minCut(String s) { cuts[i + 1] = i; } for (int i = 0; i < s.length(); i++) { - for (int j = i; j >= 0; j--) { + for (int j = 0; j <= i; j++) { if (s.charAt(i) == s.charAt(j) && (i - j < 2 || isPalindrome[j + 1][i - 1])) { isPalindrome[j][i] = true; @@ -29,10 +29,5 @@ public int minCut(String s) { } public static class UnitTest { - - @Test - public void test() { - new PalindromePartitioningII().new Solution().minCut("efe"); - } } } From 09f0ccb435f677339a592f679e30ac733ff5f4dd Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 31 Oct 2013 13:13:32 +0800 Subject: [PATCH 002/456] Solve the 'Populating Next Right Pointers in Each Node II' question --- ...pulatingNextRightPointersinEachNodeII.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java diff --git a/src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java b/src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java new file mode 100644 index 0000000..d9b44be --- /dev/null +++ b/src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java @@ -0,0 +1,42 @@ +package populating_next_right_pointers_in_each_node_ii; + +import common.TreeLinkNode; + +public class PopulatingNextRightPointersinEachNodeII { + + public class Solution { + public void connect(TreeLinkNode root) { + TreeLinkNode leftMost = root; + while (leftMost != null) { + TreeLinkNode p = leftMost; + TreeLinkNode pre = null; + leftMost = null; + while (p != null) { + if (p.left != null) { + if (leftMost == null) { + leftMost = p.left; + } + if (pre != null) { + pre.next = p.left; + } + pre = p.left; + } + if (p.right != null) { + if (leftMost == null) { + leftMost = p.right; + } + if (pre != null) { + pre.next = p.right; + } + pre = p.right; + } + p = p.next; + } + } + } + } + + public static class UnitTest { + + } +} From 03a36a5896be75921f0d0a65169bfa61e5ed548f Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 31 Oct 2013 21:37:01 +0800 Subject: [PATCH 003/456] Solve the 'Linked List Cycle II' question --- .../LinkedListCycleII.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/linked_list_cycle_ii/LinkedListCycleII.java diff --git a/src/main/java/linked_list_cycle_ii/LinkedListCycleII.java b/src/main/java/linked_list_cycle_ii/LinkedListCycleII.java new file mode 100644 index 0000000..2b156ce --- /dev/null +++ b/src/main/java/linked_list_cycle_ii/LinkedListCycleII.java @@ -0,0 +1,29 @@ +package linked_list_cycle_ii; + +import common.ListNode; + +public class LinkedListCycleII { + + public class Solution { + public ListNode detectCycle(ListNode head) { + ListNode fast = head; + ListNode slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (fast == slow) { + while (fast != head) { + fast = fast.next; + head = head.next; + } + return fast; + } + } + return null; + } + } + + public static class UnitTest { + + } +} From 1931475711e5bdb6308e7040a931972949c2b782 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 31 Oct 2013 21:37:46 +0800 Subject: [PATCH 004/456] Updated the solution --- .../palindrome_partitioning_ii/PalindromePartitioningII.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java b/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java index a0257b5..ee935c8 100644 --- a/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java +++ b/src/main/java/palindrome_partitioning_ii/PalindromePartitioningII.java @@ -1,6 +1,5 @@ package palindrome_partitioning_ii; -import org.junit.Test; public class PalindromePartitioningII { From 9b9083c72d66411de66b99dfa417a3a1cd48e452 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 31 Oct 2013 22:09:44 +0800 Subject: [PATCH 005/456] Solve the 'Spiral Matrix II' question --- .../java/spiral_matrix_ii/SpiralMatrixII.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/spiral_matrix_ii/SpiralMatrixII.java diff --git a/src/main/java/spiral_matrix_ii/SpiralMatrixII.java b/src/main/java/spiral_matrix_ii/SpiralMatrixII.java new file mode 100644 index 0000000..71e422d --- /dev/null +++ b/src/main/java/spiral_matrix_ii/SpiralMatrixII.java @@ -0,0 +1,36 @@ +package spiral_matrix_ii; + +public class SpiralMatrixII { + + public class Solution { + public int[][] generateMatrix(int n) { + int[][] matrix = new int[n][n]; + int num = 0; + int begin = 0; + int end = n - 1; + while (begin <= end) { + for (int i = begin; i <= end; i++) { + matrix[begin][i] = ++num; + } + for (int i = begin + 1; i < end; i++) { + matrix[i][end] = ++num; + } + if (begin != end) { + for (int i = end; i >= begin; i--) { + matrix[end][i] = ++num; + } + for (int i = end - 1; i > begin; i--) { + matrix[i][begin] = ++num; + } + } + begin++; + end--; + } + return matrix; + } + } + + public static class UnitTest { + + } +} From 948ba6c3e26d8c638104885027fce25f2a764132 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 31 Oct 2013 22:56:01 +0800 Subject: [PATCH 006/456] Solve the 'Text Justification' question --- .../text_justification/TextJustification.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/main/java/text_justification/TextJustification.java diff --git a/src/main/java/text_justification/TextJustification.java b/src/main/java/text_justification/TextJustification.java new file mode 100644 index 0000000..5ba09ac --- /dev/null +++ b/src/main/java/text_justification/TextJustification.java @@ -0,0 +1,66 @@ +package text_justification; + +import java.util.ArrayList; + +public class TextJustification { + + public class Solution { + private void appendSpace(StringBuilder line, int space) { + for (int i = 0; i < space; i++) { + line.append(' '); + } + } + + public ArrayList fullJustify(String[] words, int L) { + ArrayList ans = new ArrayList(); + if (words.length == 0) { + return ans; + } + int begin = 0; + int len = words[0].length(); + int current = 1; + while (current < words.length) { + if (len + words[current].length() + 1 <= L) { + len += words[current].length() + 1; + } else { + int wordCount = current - begin; + int padding = L - len + wordCount - 1; + StringBuilder line = new StringBuilder(); + if (wordCount == 1) { + line.append(words[begin]); + appendSpace(line, padding); + } else { + int slotSize = padding / (wordCount - 1); + int moreSlotCount = padding % (wordCount - 1); + for (int i = 0; i < moreSlotCount; i++) { + line.append(words[begin + i]); + appendSpace(line, slotSize + 1); + } + for (int i = moreSlotCount; i < wordCount - 1; i++) { + line.append(words[begin + i]); + appendSpace(line, slotSize); + } + line.append(words[current - 1]); + } + ans.add(line.toString()); + begin = current; + len = words[current].length(); + } + current++; + } + StringBuilder line = new StringBuilder(); + for (int i = begin; i < words.length - 1; i++) { + line.append(words[i]); + line.append(' '); + } + line.append(words[words.length - 1]); + appendSpace(line, L - len); + ans.add(line.toString()); + return ans; + } + } + + public static class UnitTest { + + } +} From afcdac29b022ff39db7732b3f1729f9c6cf48b49 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 31 Oct 2013 23:23:42 +0800 Subject: [PATCH 007/456] Solve the 'Word Search' question --- src/main/java/word_search/WordSearch.java | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/word_search/WordSearch.java diff --git a/src/main/java/word_search/WordSearch.java b/src/main/java/word_search/WordSearch.java new file mode 100644 index 0000000..72dd5b3 --- /dev/null +++ b/src/main/java/word_search/WordSearch.java @@ -0,0 +1,42 @@ +package word_search; + +public class WordSearch { + + public class Solution { + private boolean search(char[][] board, int i, int j, String word, + int begin) { + if (begin == word.length()) { + return true; + } + if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) { + return false; + } + if (board[i][j] == '*' || board[i][j] != word.charAt(begin)) { + return false; + } + char c = board[i][j]; + board[i][j] = '*'; + boolean re = search(board, i + 1, j, word, begin + 1) + || search(board, i - 1, j, word, begin + 1) + || search(board, i, j + 1, word, begin + 1) + || search(board, i, j - 1, word, begin + 1); + board[i][j] = c; + return re; + } + + public boolean exist(char[][] board, String word) { + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + if (search(board, i, j, word, 0)) { + return true; + } + } + } + return false; + } + } + + public static class UnitTest { + + } +} From cec0947e214e5f123cd477132e1b704849fe33b5 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 3 Nov 2013 20:16:08 +0800 Subject: [PATCH 008/456] Solve the 'Unique Binary Search Trees' question --- .../UniqueBinarySearchTrees.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/main/java/unique_binary_search_trees/UniqueBinarySearchTrees.java diff --git a/src/main/java/unique_binary_search_trees/UniqueBinarySearchTrees.java b/src/main/java/unique_binary_search_trees/UniqueBinarySearchTrees.java new file mode 100644 index 0000000..2dc4328 --- /dev/null +++ b/src/main/java/unique_binary_search_trees/UniqueBinarySearchTrees.java @@ -0,0 +1,19 @@ +package unique_binary_search_trees; + +public class UniqueBinarySearchTrees { + + public class Solution { + public int numTrees(int n) { + // Catalan number; + int c = 1; + for (int i = 2; i <= n; i++) { + c = c * 2 * (2 * i - 1) / (i + 1); + } + return c; + } + } + + public static class UnitTest { + + } +} From df478bfefc07ff34876fb1e01d36e2aa490ee57e Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 3 Nov 2013 21:38:00 +0800 Subject: [PATCH 009/456] Solve the 'Restore IP Addresses' question --- .../RestoreIPAddresses.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/restore_ip_addresses/RestoreIPAddresses.java diff --git a/src/main/java/restore_ip_addresses/RestoreIPAddresses.java b/src/main/java/restore_ip_addresses/RestoreIPAddresses.java new file mode 100644 index 0000000..a0362c2 --- /dev/null +++ b/src/main/java/restore_ip_addresses/RestoreIPAddresses.java @@ -0,0 +1,62 @@ +package restore_ip_addresses; + +import java.util.ArrayList; + +import org.junit.Test; + +public class RestoreIPAddresses { + + public class Solution { + private String toAddr(ArrayList solution) { + String addr = ""; + addr += solution.get(0); + addr += "."; + addr += solution.get(1); + addr += "."; + addr += solution.get(2); + addr += "."; + addr += solution.get(3); + return addr; + } + + private void search(String s, int begin, ArrayList solution, + ArrayList solutions) { + if (begin == s.length() && solution.size() == 4) { + solutions.add(toAddr(solution)); + return; + } + if (s.length() - begin > (4 - solution.size()) * 3) { + return; + } + if (s.length() - begin < 4 - solution.size()) { + return; + } + int num = 0; + for (int i = begin; i < Math.min(begin + 3, s.length()); i++) { + num = num * 10 + s.charAt(i) - '0'; + if (num < 256) { + solution.add(num); + search(s, i + 1, solution, solutions); + solution.remove(solution.size() - 1); + } + if (num == 0) { + break; + } + } + } + + public ArrayList restoreIpAddresses(String s) { + ArrayList solutions = new ArrayList(); + search(s, 0, new ArrayList(), solutions); + return solutions; + } + } + + public static class UnitTest { + + @Test + public void test() { + new RestoreIPAddresses().new Solution().restoreIpAddresses("1111"); + } + } +} From 71683e39cd387d3e5c5422d34d5c3d462f3a2a8a Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 3 Nov 2013 22:42:01 +0800 Subject: [PATCH 010/456] Updated the solution --- src/main/java/restore_ip_addresses/RestoreIPAddresses.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/main/java/restore_ip_addresses/RestoreIPAddresses.java b/src/main/java/restore_ip_addresses/RestoreIPAddresses.java index a0362c2..42b033b 100644 --- a/src/main/java/restore_ip_addresses/RestoreIPAddresses.java +++ b/src/main/java/restore_ip_addresses/RestoreIPAddresses.java @@ -2,8 +2,6 @@ import java.util.ArrayList; -import org.junit.Test; - public class RestoreIPAddresses { public class Solution { @@ -53,10 +51,5 @@ public ArrayList restoreIpAddresses(String s) { } public static class UnitTest { - - @Test - public void test() { - new RestoreIPAddresses().new Solution().restoreIpAddresses("1111"); - } } } From 8ad75225acb3183f814b8aebcef70e5a80de6d46 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 3 Nov 2013 22:42:29 +0800 Subject: [PATCH 011/456] Solve the 'Reorder List' question --- src/main/java/reorder_list/ReorderList.java | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/reorder_list/ReorderList.java diff --git a/src/main/java/reorder_list/ReorderList.java b/src/main/java/reorder_list/ReorderList.java new file mode 100644 index 0000000..06d770d --- /dev/null +++ b/src/main/java/reorder_list/ReorderList.java @@ -0,0 +1,62 @@ +package reorder_list; + +import org.junit.Test; + +import common.ListNode; + +public class ReorderList { + + public class Solution { + private ListNode reverse(ListNode head) { + ListNode pre = null; + ListNode p = head; + while (p != null) { + ListNode temp = p.next; + p.next = pre; + pre = p; + p = temp; + } + return pre; + } + + private ListNode[] split(ListNode head) { + ListNode[] lists = new ListNode[2]; + lists[0] = head; + if (head == null || head.next == null) { + return lists; + } + ListNode slow = head; + ListNode fast = head.next.next; + while (fast != null) { + slow = slow.next; + if (fast.next == null) { + break; + } + fast = fast.next.next; + } + lists[1] = slow.next; + slow.next = null; + return lists; + } + + private void zip(ListNode l1, ListNode l2) { + while (l2 != null) { + ListNode temp = l1.next; + l1.next = l2; + l1 = temp; + temp = l2.next; + l2.next = l1; + l2 = temp; + } + } + + public void reorderList(ListNode head) { + ListNode[] lists = split(head); + lists[1] = reverse(lists[1]); + zip(lists[0], lists[1]); + } + } + + public static class UnitTest { + } +} From 839468d6beb7e86542b8035036470e2a5c18b418 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 3 Nov 2013 23:18:47 +0800 Subject: [PATCH 012/456] Solve the 'Symmetric Tree' question --- .../java/symmetric_tree/SymmetricTree.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/symmetric_tree/SymmetricTree.java diff --git a/src/main/java/symmetric_tree/SymmetricTree.java b/src/main/java/symmetric_tree/SymmetricTree.java new file mode 100644 index 0000000..422f3ce --- /dev/null +++ b/src/main/java/symmetric_tree/SymmetricTree.java @@ -0,0 +1,62 @@ +package symmetric_tree; + +import java.util.LinkedList; + +import common.TreeNode; + +public class SymmetricTree { + + public class Solution { + private boolean isSymmetric(TreeNode left, TreeNode right) { + if (left == null && right == null) { + return true; + } + if (left == null || right == null) { + return left == right; + } + return left.val == right.val && isSymmetric(left.left, right.right) + && isSymmetric(left.right, right.left); + } + + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return true; + } + return isSymmetric(root.left, root.right); + } + } + + public class SolutionWithIterative { + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return true; + } + LinkedList lefts = new LinkedList(); + LinkedList rights = new LinkedList(); + lefts.add(root.left); + rights.add(root.right); + while (!lefts.isEmpty() && !rights.isEmpty()) { + TreeNode left = lefts.poll(); + TreeNode right = rights.poll(); + if (left == null && right == null) { + continue; + } + if (left == null || right == null) { + return false; + } + if (left.val != right.val) { + return false; + } + lefts.add(left.left); + lefts.add(left.right); + rights.add(right.right); + rights.add(right.left); + } + return lefts.isEmpty() && rights.isEmpty(); + } + } + + public static class UnitTest { + + } +} From f3bb3b7d0e69b309abed6944a5a470d18ded8450 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 5 Nov 2013 13:55:57 +0800 Subject: [PATCH 013/456] Solve the 'Reverse Linked List II' question --- .../ReverseLinkedListII.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java diff --git a/src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java b/src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java new file mode 100644 index 0000000..e4ed140 --- /dev/null +++ b/src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java @@ -0,0 +1,43 @@ +package reverse_linked_list_ii; + +import common.ListNode; + +public class ReverseLinkedListII { + + public class Solution { + public ListNode reverseBetween(ListNode head, int m, int n) { + ListNode prefix = null; + int count = n - m + 1; + m--; + while (m > 0) { + prefix = prefix == null ? head : prefix.next; + m--; + } + ListNode pre = null; + ListNode p = prefix == null ? head : prefix.next; + ListNode reversedTail = p; + while (count > 0) { + ListNode temp = p.next; + if (pre != null) { + p.next = pre; + } + pre = p; + p = temp; + count--; + } + if (prefix == null) { + head = pre; + } else { + prefix.next = pre; + } + if (reversedTail != null) { + reversedTail.next = p; + } + return head; + } + } + + public static class UnitTest { + + } +} From 7f9bb5bd26f7c9e608030863211fa59da34c76ea Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 6 Nov 2013 14:08:06 +0800 Subject: [PATCH 014/456] Solve the 'Binary Tree Preorder Traversal' question --- .../BinaryTreePreorderTraversal.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java diff --git a/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java b/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java new file mode 100644 index 0000000..52f2935 --- /dev/null +++ b/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java @@ -0,0 +1,30 @@ +package binary_tree_preorder_traversal; + +import java.util.ArrayList; + +import common.TreeNode; + +public class BinaryTreePreorderTraversal { + + public class Solution { + private void preorderTraversal(TreeNode root, + ArrayList preorder) { + if (root == null) { + return; + } + preorder.add(root.val); + preorderTraversal(root.left, preorder); + preorderTraversal(root.right, preorder); + } + + public ArrayList preorderTraversal(TreeNode root) { + ArrayList preorder = new ArrayList(); + preorderTraversal(root, preorder); + return preorder; + } + } + + public static class UnitTest { + + } +} From d22f9afa6855f80cd5b21238faca6db1ac3a7e5b Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 6 Nov 2013 22:18:57 +0800 Subject: [PATCH 015/456] Solve the 'Combination Sum' question --- .../java/combination_sum/CombinationSum.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/combination_sum/CombinationSum.java diff --git a/src/main/java/combination_sum/CombinationSum.java b/src/main/java/combination_sum/CombinationSum.java new file mode 100644 index 0000000..98fcbc4 --- /dev/null +++ b/src/main/java/combination_sum/CombinationSum.java @@ -0,0 +1,41 @@ +package combination_sum; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; + +public class CombinationSum { + + public class Solution { + private void search(int[] n, int index, int target, + ArrayDeque s, ArrayList> ans) { + if (target == 0) { + ans.add(new ArrayList(s)); + return; + } + if (index == n.length || target < n[index]) { + return; + } + + for (int i = 0; i <= target / n[index]; i++) { + search(n, index + 1, target - i * n[index], s, ans); + s.offerLast(n[index]); + } + for (int i = 0; i <= target / n[index]; i++) { + s.removeLast(); + } + } + + public ArrayList> combinationSum(int[] candidates, + int target) { + ArrayList> ans = new ArrayList>(); + Arrays.sort(candidates); + search(candidates, 0, target, new ArrayDeque(), ans); + return ans; + } + } + + public static class UnitTest { + + } +} From b09d36179adc1d967a10d4c8931e3b92b4d7fd46 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 13:42:02 +0800 Subject: [PATCH 016/456] Update the solution --- .../BinaryTreePreorderTraversal.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java b/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java index 52f2935..fba129e 100644 --- a/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java +++ b/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java @@ -1,5 +1,6 @@ package binary_tree_preorder_traversal; +import java.util.ArrayDeque; import java.util.ArrayList; import common.TreeNode; @@ -22,6 +23,25 @@ public ArrayList preorderTraversal(TreeNode root) { preorderTraversal(root, preorder); return preorder; } + + public ArrayList preorderTraversalWithIterative(TreeNode root) { + ArrayList preorder = new ArrayList(); + ArrayDeque stack = new ArrayDeque(); + if (root != null) { + stack.offerLast(root); + while (!stack.isEmpty()) { + TreeNode p = stack.removeLast(); + while (p != null) { + preorder.add(p.val); + if (p.right != null) { + stack.offerLast(p.right); + } + p = p.left; + } + } + } + return preorder; + } } public static class UnitTest { From ac410bce2c9f2dd45cebf6b21ee9ce578aeb2d3c Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 14:31:55 +0800 Subject: [PATCH 017/456] Solve the 'Binary Tree Postorder Traversal' question --- .../BinaryTreePostorderTraversal.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java diff --git a/src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java b/src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java new file mode 100644 index 0000000..390a90d --- /dev/null +++ b/src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java @@ -0,0 +1,60 @@ +package binary_tree_postorder_traversal; + +import java.util.ArrayDeque; +import java.util.ArrayList; + +import common.TreeNode; + +public class BinaryTreePostorderTraversal { + + public class Solution { + private void postorderTraversal(TreeNode root, + ArrayList postorder) { + if (root == null) { + return; + } + postorderTraversal(root.left, postorder); + postorderTraversal(root.right, postorder); + postorder.add(root.val); + } + + public ArrayList postorderTraversal(TreeNode root) { + ArrayList postorder = new ArrayList(); + postorderTraversal(root, postorder); + return postorder; + } + + public ArrayList postorderTraversalWithIterative(TreeNode root) { + ArrayList postorder = new ArrayList(); + if (root == null) { + return postorder; + } + ArrayDeque stack = new ArrayDeque(); + TreeNode pre = null; + stack.offerLast(root); + while (!stack.isEmpty()) { + TreeNode p = stack.peekLast(); + if (pre == null || pre.left == p || pre.right == p) { + if (p.left != null) { + stack.offerLast(p.left); + } else if (p.right != null) { + stack.offerLast(p.right); + } + } else if (p.left == pre) { + if (p.right != null) { + stack.offerLast(p.right); + } + } else { + postorder.add(p.val); + stack.removeLast(); + } + pre = p; + } + return postorder; + } + } + + public static class UnitTest { + + } +} From fdba8d5d5af0de6a2c50387c6a85473ab9413b99 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 15:15:18 +0800 Subject: [PATCH 018/456] Solve the 'Convert Sorted List to Binary Search Tree' question --- .../ConvertSortedListtoBinarySearchTree.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java diff --git a/src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java b/src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java new file mode 100644 index 0000000..7a45fd6 --- /dev/null +++ b/src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java @@ -0,0 +1,37 @@ +package convert_sorted_list_to_binary_search_tree; + +import common.ListNode; +import common.TreeNode; + +public class ConvertSortedListtoBinarySearchTree { + + public class Solution { + private TreeNode sortedListToBST(ListNode head, ListNode[] tail, + int begin, int end) { + if (begin > end) { + tail[0] = head; + return null; + } + TreeNode p = new TreeNode(0); + int mid = begin + (end - begin) / 2; + p.left = sortedListToBST(head, tail, begin, mid - 1); + p.val = tail[0].val; + p.right = sortedListToBST(tail[0].next, tail, mid + 1, end); + return p; + } + + public TreeNode sortedListToBST(ListNode head) { + ListNode p = head; + int len = 0; + while (p != null) { + len++; + p = p.next; + } + return sortedListToBST(head, new ListNode[1], 0, len - 1); + } + } + + public static class UnitTest { + + } +} From 3cd5e4bc7c816282c8c047dc310ff50361ac17f6 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 15:37:21 +0800 Subject: [PATCH 019/456] Solve the 'Binary Tree Zigzag Level Order Traversal' question --- .../BinaryTreeZigzagLevelOrderTraversal.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/java/binary_tree_zigzag_level_order_traversal/BinaryTreeZigzagLevelOrderTraversal.java diff --git a/src/main/java/binary_tree_zigzag_level_order_traversal/BinaryTreeZigzagLevelOrderTraversal.java b/src/main/java/binary_tree_zigzag_level_order_traversal/BinaryTreeZigzagLevelOrderTraversal.java new file mode 100644 index 0000000..9f44de8 --- /dev/null +++ b/src/main/java/binary_tree_zigzag_level_order_traversal/BinaryTreeZigzagLevelOrderTraversal.java @@ -0,0 +1,51 @@ +package binary_tree_zigzag_level_order_traversal; + +import java.util.ArrayList; + +import common.TreeNode; + +public class BinaryTreeZigzagLevelOrderTraversal { + + public class Solution { + public ArrayList> zigzagLevelOrder(TreeNode root) { + ArrayList> ans = new ArrayList>(); + if (root == null) { + return ans; + } + ArrayList q = new ArrayList(); + q.add(root); + int tail = 0; + boolean reverse = false; + while (tail != q.size()) { + int begin = tail; + tail = q.size(); + for (int i = begin; i < tail; i++) { + TreeNode p = q.get(i); + if (p.left != null) { + q.add(p.left); + } + if (p.right != null) { + q.add(p.right); + } + } + ArrayList level = new ArrayList(); + if (reverse) { + for (int i = tail - 1; i >= begin; i--) { + level.add(q.get(i).val); + } + } else { + for (int i = begin; i < tail; i++) { + level.add(q.get(i).val); + } + } + ans.add(level); + reverse = !reverse; + } + return ans; + } + } + + public static class UnitTest { + + } +} From 7be0fcbc4d8a5492527513bd2155908fe7b6f31f Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 16:07:52 +0800 Subject: [PATCH 020/456] Solve the 'Scramble String' question --- .../java/scramble_string/ScrambleString.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/scramble_string/ScrambleString.java diff --git a/src/main/java/scramble_string/ScrambleString.java b/src/main/java/scramble_string/ScrambleString.java new file mode 100644 index 0000000..8a33d8a --- /dev/null +++ b/src/main/java/scramble_string/ScrambleString.java @@ -0,0 +1,39 @@ +package scramble_string; + +public class ScrambleString { + + public class Solution { + public boolean isScramble(String s1, String s2) { + if (s1.equals(s2)) { + return true; + } + int len = s1.length(); + boolean[][][] dp = new boolean[len][len][len + 1]; + for (int i = 0; i < len; i++) { + for (int j = 0; j < len; j++) { + dp[i][j][1] = s1.charAt(i) == s2.charAt(j); + } + } + + for (int l = 2; l <= len; l++) { + for (int i = 0; i <= len - l; i++) { + for (int j = 0; j <= len - l; j++) { + for (int p = 1; p < l; p++) { + if ((dp[i][j][p] && dp[i + p][j + p][l - p]) + || (dp[i][j + l - p][p] && dp[i + p][j][l + - p])) { + dp[i][j][l] = true; + break; + } + } + } + } + } + return dp[0][0][len]; + } + } + + public static class UnitTest { + + } +} From 900f2d9d85771b86e0d25260fb4e317b49bc9035 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 16:33:40 +0800 Subject: [PATCH 021/456] Solve the 'N-Queens' question --- src/main/java/n_queens/NQueens.java | 63 +++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/main/java/n_queens/NQueens.java diff --git a/src/main/java/n_queens/NQueens.java b/src/main/java/n_queens/NQueens.java new file mode 100644 index 0000000..cf99703 --- /dev/null +++ b/src/main/java/n_queens/NQueens.java @@ -0,0 +1,63 @@ +package n_queens; + +import java.util.ArrayDeque; +import java.util.ArrayList; + +public class NQueens { + + public class Solution { + private boolean isValid(int row, int column, ArrayDeque columns) { + int r = 0; + for (int c : columns) { + if (c == column || Math.abs(c - column) == Math.abs(r - row)) { + return false; + } + r++; + } + return true; + } + + private String[] toSolution(ArrayDeque columns) { + int n = columns.size(); + String[] s = new String[n]; + int row = 0; + for (int column : columns) { + String line = ""; + for (int i = 0; i < n; i++) { + if (i != column) { + line += '.'; + } else { + line += 'Q'; + } + } + s[row++] = line; + } + return s; + } + + private void search(int row, int n, ArrayDeque columns, + ArrayList ans) { + if (row == n) { + ans.add(toSolution(columns)); + return; + } + for (int i = 0; i < n; i++) { + if (isValid(row, i, columns)) { + columns.offerLast(i); + search(row + 1, n, columns, ans); + columns.removeLast(); + } + } + } + + public ArrayList solveNQueens(int n) { + ArrayList ans = new ArrayList(); + search(0, n, new ArrayDeque(), ans); + return ans; + } + } + + public static class UnitTest { + + } +} From ebd7456906ad8cae20d3d8d7ca29e4969a735348 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 17:19:00 +0800 Subject: [PATCH 022/456] Solve the 'Unique Binary Search Trees II' question --- .../UniqueBinarySearchTreesII.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/unique_binary_search_trees_ii/UniqueBinarySearchTreesII.java diff --git a/src/main/java/unique_binary_search_trees_ii/UniqueBinarySearchTreesII.java b/src/main/java/unique_binary_search_trees_ii/UniqueBinarySearchTreesII.java new file mode 100644 index 0000000..5bcc91a --- /dev/null +++ b/src/main/java/unique_binary_search_trees_ii/UniqueBinarySearchTreesII.java @@ -0,0 +1,38 @@ +package unique_binary_search_trees_ii; + +import java.util.ArrayList; + +import common.TreeNode; + +public class UniqueBinarySearchTreesII { + + public class Solution { + + private ArrayList generateTrees(int start, int end) { + ArrayList ans = new ArrayList(); + if (start > end) { + ans.add(null); + return ans; + } + for (int i = start; i <= end; i++) { + for (TreeNode left : generateTrees(start, i - 1)) { + for (TreeNode right : generateTrees(i + 1, end)) { + TreeNode p = new TreeNode(i); + p.left = left; + p.right = right; + ans.add(p); + } + } + } + return ans; + } + + public ArrayList generateTrees(int n) { + return generateTrees(1, n); + } + } + + public static class UnitTest { + + } +} From 7929ff8552072239d60e8ab853894d2b26973083 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 22:48:40 +0800 Subject: [PATCH 023/456] Solve the 'Largest Rectangle in Histogram' question --- .../LargestRectangleinHistogram.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java diff --git a/src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java b/src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java new file mode 100644 index 0000000..8fd774e --- /dev/null +++ b/src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java @@ -0,0 +1,35 @@ +package largest_rectangle_in_histogram; + +import java.util.ArrayDeque; +import java.util.Deque; + +public class LargestRectangleinHistogram { + + public class Solution { + public int largestRectangleArea(int[] height) { + int maxArea = 0; + Deque p = new ArrayDeque(); + int i = 0; + while (i < height.length) { + if (p.isEmpty() || height[p.peekLast()] <= height[i]) { + p.offerLast(i++); + } else { + int pos = p.removeLast(); + maxArea = Math.max(maxArea, + (p.isEmpty() ? i : i - p.peekLast() - 1) + * height[pos]); + } + } + while (!p.isEmpty()) { + int pos = p.removeLast(); + maxArea = Math.max(maxArea, (p.isEmpty() ? i : i - p.peekLast() + - 1) + * height[pos]); + } + return maxArea; + } + } + + public static class UnitTest { + } +} From aa6591282173bfffa7002d85a4caec41991e8f1c Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 23:09:26 +0800 Subject: [PATCH 024/456] Solve the 'Maximal Rectangle' question --- .../maximal_rectangle/MaximalRectangle.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/maximal_rectangle/MaximalRectangle.java diff --git a/src/main/java/maximal_rectangle/MaximalRectangle.java b/src/main/java/maximal_rectangle/MaximalRectangle.java new file mode 100644 index 0000000..6b39bcd --- /dev/null +++ b/src/main/java/maximal_rectangle/MaximalRectangle.java @@ -0,0 +1,49 @@ +package maximal_rectangle; + +import java.util.ArrayDeque; + +public class MaximalRectangle { + + public class Solution { + private int largestRectangleArea(int[] height) { + ArrayDeque p = new ArrayDeque(); + int i = 0; + int maxArea = 0; + while (i < height.length) { + if (p.isEmpty() || height[p.peekLast()] <= height[i]) { + p.offerLast(i++); + } else { + int pos = p.removeLast(); + maxArea = Math.max(maxArea, height[pos] + * (p.isEmpty() ? i : (i - p.peekLast() - 1))); + } + } + return maxArea; + } + + public int maximalRectangle(char[][] matrix) { + if (matrix.length == 0 || matrix[0].length == 0) { + return 0; + } + int m = matrix.length; + int n = matrix[0].length; + int[] height = new int[n + 1]; + int maxArea = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == '1') { + height[j]++; + } else { + height[j] = 0; + } + } + maxArea = Math.max(maxArea, largestRectangleArea(height)); + } + return maxArea; + } + } + + public static class UnitTest { + + } +} From 61173393e4a3669b8062efa32e83995ed0c4947f Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 23:10:57 +0800 Subject: [PATCH 025/456] Update the solution --- src/main/java/reorder_list/ReorderList.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/reorder_list/ReorderList.java b/src/main/java/reorder_list/ReorderList.java index 06d770d..49c3e80 100644 --- a/src/main/java/reorder_list/ReorderList.java +++ b/src/main/java/reorder_list/ReorderList.java @@ -1,7 +1,5 @@ package reorder_list; -import org.junit.Test; - import common.ListNode; public class ReorderList { From b2dbeecd2c388b26a3dc9fd0a3eb0ae33c46354a Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 23:27:12 +0800 Subject: [PATCH 026/456] Update the solution --- .../ReverseLinkedListII.java | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java b/src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java index e4ed140..761a68c 100644 --- a/src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java +++ b/src/main/java/reverse_linked_list_ii/ReverseLinkedListII.java @@ -6,34 +6,30 @@ public class ReverseLinkedListII { public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { - ListNode prefix = null; + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode prefix = dummy; int count = n - m + 1; m--; while (m > 0) { - prefix = prefix == null ? head : prefix.next; + prefix = prefix.next; m--; } ListNode pre = null; - ListNode p = prefix == null ? head : prefix.next; + ListNode p = prefix.next; ListNode reversedTail = p; while (count > 0) { ListNode temp = p.next; - if (pre != null) { - p.next = pre; - } + p.next = pre; pre = p; p = temp; count--; } - if (prefix == null) { - head = pre; - } else { - prefix.next = pre; - } + prefix.next = pre; if (reversedTail != null) { reversedTail.next = p; } - return head; + return dummy.next; } } From f7cac9548301c68b8fcd165e634cfaf0f5cb48d8 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 10 Nov 2013 23:59:32 +0800 Subject: [PATCH 027/456] Solve the 'Permutations' question --- src/main/java/permutations/Permutations.java | 61 ++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/main/java/permutations/Permutations.java diff --git a/src/main/java/permutations/Permutations.java b/src/main/java/permutations/Permutations.java new file mode 100644 index 0000000..023d114 --- /dev/null +++ b/src/main/java/permutations/Permutations.java @@ -0,0 +1,61 @@ +package permutations; + +import java.util.ArrayList; +import java.util.Arrays; + +public class Permutations { + + public class Solution { + private void swap(int[] num, int i, int j) { + int temp = num[i]; + num[i] = num[j]; + num[j] = temp; + } + + private void reverse(int[] num, int begin, int end) { + end--; + while (begin < end) { + swap(num, begin++, end--); + } + } + + private boolean nextPermutation(int[] num) { + if (num.length <= 1) { + return false; + } + int i = num.length - 1; + while (true) { + i--; + if (num[i] < num[i + 1]) { + int j = num.length; + while (num[i] >= num[--j]) { + } + swap(num, i, j); + reverse(num, i + 1, num.length); + return true; + } + if (i == 0) { + reverse(num, 0, num.length); + return false; + } + } + } + + public ArrayList> permute(int[] num) { + Arrays.sort(num); + ArrayList> ans = new ArrayList>(); + do { + ArrayList l = new ArrayList(); + for (int n : num) { + l.add(n); + } + ans.add(l); + } while (nextPermutation(num)); + return ans; + } + } + + public static class UnitTest { + + } +} From 105cdc3c55dd28088e775c577cdb025579642196 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Mon, 11 Nov 2013 00:04:19 +0800 Subject: [PATCH 028/456] Solve the 'Permutations II' question --- .../java/permutations_ii/PermutationsII.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/main/java/permutations_ii/PermutationsII.java diff --git a/src/main/java/permutations_ii/PermutationsII.java b/src/main/java/permutations_ii/PermutationsII.java new file mode 100644 index 0000000..2ddcff0 --- /dev/null +++ b/src/main/java/permutations_ii/PermutationsII.java @@ -0,0 +1,61 @@ +package permutations_ii; + +import java.util.ArrayList; +import java.util.Arrays; + +public class PermutationsII { + + public class Solution { + private void swap(int[] num, int i, int j) { + int temp = num[i]; + num[i] = num[j]; + num[j] = temp; + } + + private void reverse(int[] num, int begin, int end) { + end--; + while (begin < end) { + swap(num, begin++, end--); + } + } + + private boolean nextPermutation(int[] num) { + if (num.length <= 1) { + return false; + } + int i = num.length - 1; + while (true) { + i--; + if (num[i] < num[i + 1]) { + int j = num.length; + while (num[i] >= num[--j]) { + } + swap(num, i, j); + reverse(num, i + 1, num.length); + return true; + } + if (i == 0) { + reverse(num, 0, num.length); + return false; + } + } + } + + public ArrayList> permuteUnique(int[] num) { + Arrays.sort(num); + ArrayList> ans = new ArrayList>(); + do { + ArrayList l = new ArrayList(); + for (int n : num) { + l.add(n); + } + ans.add(l); + } while (nextPermutation(num)); + return ans; + } + } + + public static class UnitTest { + + } +} From 88bd41a2d0467e8dab4c86eca036c18ccdf6daad Mon Sep 17 00:00:00 2001 From: zsxwing Date: Mon, 11 Nov 2013 22:21:51 +0800 Subject: [PATCH 029/456] Solve the 'Next Permutation' question --- .../next_permutation/NextPermutation.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/next_permutation/NextPermutation.java diff --git a/src/main/java/next_permutation/NextPermutation.java b/src/main/java/next_permutation/NextPermutation.java new file mode 100644 index 0000000..85bfe37 --- /dev/null +++ b/src/main/java/next_permutation/NextPermutation.java @@ -0,0 +1,42 @@ +package next_permutation; + +public class NextPermutation { + + public class Solution { + private void swap(int[] num, int i, int j) { + int temp = num[i]; + num[i] = num[j]; + num[j] = temp; + } + + private void reverse(int[] num, int begin, int end) { + end--; + while (begin < end) { + swap(num, begin++, end--); + } + } + + public void nextPermutation(int[] num) { + if (num.length <= 1) { + return; + } + int i = num.length - 1; + while (i > 0) { + i--; + if (num[i] < num[i + 1]) { + int j = num.length; + while (num[--j] <= num[i]) { + } + swap(num, i, j); + reverse(num, i + 1, num.length); + return; + } + } + reverse(num, 0, num.length); + } + } + + public static class UnitTest { + + } +} From 8f663c0bbe8f39aabb0420a8db8c3f82229ee446 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 13 Nov 2013 22:03:36 +0800 Subject: [PATCH 030/456] Solve the 'Insertion Sort List' question --- .../InsertionSortList.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/insertion_sort_list/InsertionSortList.java diff --git a/src/main/java/insertion_sort_list/InsertionSortList.java b/src/main/java/insertion_sort_list/InsertionSortList.java new file mode 100644 index 0000000..05a35a8 --- /dev/null +++ b/src/main/java/insertion_sort_list/InsertionSortList.java @@ -0,0 +1,32 @@ +package insertion_sort_list; + +import common.ListNode; + +public class InsertionSortList { + + public class Solution { + public ListNode insertionSortList(ListNode head) { + ListNode dummy = new ListNode(0); + ListNode p = head; + while (p != null) { + ListNode pre = dummy; + while (pre.next != null) { + if (pre.next.val <= p.val) { // stable sort + pre = pre.next; + } else { + break; + } + } + ListNode temp = p.next; + p.next = pre.next; + pre.next = p; + p = temp; + } + return dummy.next; + } + } + + public static class UnitTest { + + } +} From 507d9b9d2a7fcac72aeeb0820d11967b41a589fc Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 13 Nov 2013 22:43:32 +0800 Subject: [PATCH 031/456] Solve the 'Sudoku Solver' question --- src/main/java/sudoku_solver/SudokuSolver.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/sudoku_solver/SudokuSolver.java diff --git a/src/main/java/sudoku_solver/SudokuSolver.java b/src/main/java/sudoku_solver/SudokuSolver.java new file mode 100644 index 0000000..7256795 --- /dev/null +++ b/src/main/java/sudoku_solver/SudokuSolver.java @@ -0,0 +1,50 @@ +package sudoku_solver; + +public class SudokuSolver { + + public class Solution { + private boolean isValid(char[][] board, int row, int column, char c) { + int cellRow = row - row % 3; + int cellColumn = column - column % 3; + for (int i = 0; i < 9; i++) { + if (board[i][column] == c || board[row][i] == c + || board[cellRow + i / 3][cellColumn + i % 3] == c) { + return false; + } + } + return true; + } + + private boolean search(char[][] board, int pos) { + while (pos < 81) { + if (board[pos / 9][pos % 9] == '.') { + break; + } + pos++; + } + if (pos == 81) { + return true; + } + int row = pos / 9; + int column = pos % 9; + for (char c = '1'; c <= '9'; c++) { + if (isValid(board, row, column, c)) { + board[row][column] = c; + if (search(board, pos + 1)) { + return true; + } + } + } + board[row][column] = '.'; + return false; + } + + public void solveSudoku(char[][] board) { + search(board, 0); + } + } + + public static class UnitTest { + + } +} From 5526b085cc6681a7c5fd93c0effb94e20cb33a72 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 20 Nov 2013 00:14:31 +0800 Subject: [PATCH 032/456] Solve the 'Sort List' question --- src/main/java/sort_list/SortList.java | 59 +++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/java/sort_list/SortList.java diff --git a/src/main/java/sort_list/SortList.java b/src/main/java/sort_list/SortList.java new file mode 100644 index 0000000..254e561 --- /dev/null +++ b/src/main/java/sort_list/SortList.java @@ -0,0 +1,59 @@ +package sort_list; + +import common.ListNode; + +public class SortList { + + public class Solution { + + private ListNode merge(ListNode h1, ListNode h2) { + ListNode dummy = new ListNode(0); + ListNode prefix = dummy; + while (h1 != null || h2 != null) { + if (h2 == null || (h1 != null && h1.val < h2.val)) { + prefix.next = h1; + prefix = h1; + h1 = h1.next; + } else { + prefix.next = h2; + prefix = h2; + h2 = h2.next; + } + } + return dummy.next; + } + + private ListNode sortList(ListNode head, int start, int end, + ListNode[] tail) { + if (start == end) { + tail[0] = head; + return null; + } + if (end - start == 1) { + tail[0] = head.next; + head.next = null; + return head; + } + int mid = start + (end - start) / 2; + ListNode left = sortList(head, start, mid, tail); + ListNode right = sortList(tail[0], mid, end, tail); + return merge(left, right); + } + + private int len(ListNode head) { + int len = 0; + while (head != null) { + len++; + head = head.next; + } + return len; + } + + public ListNode sortList(ListNode head) { + return sortList(head, 0, len(head), new ListNode[1]); + } + } + + public static class UnitTest { + } +} From 6e8e68c723ebd40da7d9d253d46357a512cd4045 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 20 Nov 2013 00:44:17 +0800 Subject: [PATCH 033/456] Solve the 'LRU Cache' question --- src/main/java/lru_cache/LRUCache.java | 31 +++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/lru_cache/LRUCache.java diff --git a/src/main/java/lru_cache/LRUCache.java b/src/main/java/lru_cache/LRUCache.java new file mode 100644 index 0000000..91454c0 --- /dev/null +++ b/src/main/java/lru_cache/LRUCache.java @@ -0,0 +1,31 @@ +package lru_cache; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class LRUCache { + private LinkedHashMap map; + + @SuppressWarnings("serial") + public LRUCache(final int capacity) { + assert capacity > 0; + map = new LinkedHashMap(16, 0.75f, true) { + protected boolean removeEldestEntry( + Map.Entry eldest) { + return size() > capacity; + } + }; + } + + public int get(int key) { + Integer value = map.get(key); + if (value == null) { + return -1; + } + return value; + } + + public void set(int key, int value) { + map.put(key, value); + } +} From 0bc3dca236a55c321c6774003e25cf48c93d85e4 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 24 Nov 2013 19:01:39 +0800 Subject: [PATCH 034/456] Solve the 'Longest Common Prefix' question --- .../LongestCommonPrefix.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/longest_common_prefix/LongestCommonPrefix.java diff --git a/src/main/java/longest_common_prefix/LongestCommonPrefix.java b/src/main/java/longest_common_prefix/LongestCommonPrefix.java new file mode 100644 index 0000000..1414544 --- /dev/null +++ b/src/main/java/longest_common_prefix/LongestCommonPrefix.java @@ -0,0 +1,28 @@ +package longest_common_prefix; + +public class LongestCommonPrefix { + + public class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs.length == 0) { + return ""; + } + + int longest = strs[0].length(); + for (int i = 1; i < strs.length; i++) { + longest = Math.min(strs[i].length(), longest); + for (int j = 0; j < longest; j++) { + if (strs[i].charAt(j) != strs[0].charAt(j)) { + longest = j; + break; + } + } + } + return strs[0].substring(0, longest); + } + } + + public static class UnitTest { + + } +} From 78a4ce184c1194fd5846da7dbe3579b62597cd9c Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 24 Nov 2013 20:13:05 +0800 Subject: [PATCH 035/456] Solve the 'Longest Valid Parentheses' question --- .../LongestValidParentheses.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/longest_valid_parentheses/LongestValidParentheses.java diff --git a/src/main/java/longest_valid_parentheses/LongestValidParentheses.java b/src/main/java/longest_valid_parentheses/LongestValidParentheses.java new file mode 100644 index 0000000..93bf7b4 --- /dev/null +++ b/src/main/java/longest_valid_parentheses/LongestValidParentheses.java @@ -0,0 +1,31 @@ +package longest_valid_parentheses; + +public class LongestValidParentheses { + + public class Solution { + public int longestValidParentheses(String s) { + int[] dp = new int[s.length()]; + int max = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == ')') { + int p = i - 1; + while (p >= 0) { + if (s.charAt(p) == '(') { + dp[i] = i - p + 1 + (p > 0 ? dp[p - 1] : 0); + break; + } else if (dp[p] == 0) { + break; + } + p = p - dp[p]; + } + } + max = Math.max(max, dp[i]); + } + return max; + } + } + + public static class UnitTest { + + } +} From 72ae8737a5d573ff726b259febec69fdd63e8b81 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 24 Nov 2013 20:31:53 +0800 Subject: [PATCH 036/456] Solve the 'Substring with Concatenation of All Words' question --- .../SubstringwithConcatenationofAllWords.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java diff --git a/src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java b/src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java new file mode 100644 index 0000000..7c04d16 --- /dev/null +++ b/src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java @@ -0,0 +1,53 @@ +package substring_with_concatenation_of_all_words; + +import java.util.ArrayList; +import java.util.HashMap; + +public class SubstringwithConcatenationofAllWords { + + public class Solution { + public ArrayList findSubstring(String S, String[] L) { + HashMap dict = new HashMap(); + for (String l : L) { + Integer count = dict.get(l); + if (count == null) { + dict.put(l, 1); + } else { + dict.put(l, count + 1); + } + } + int wordSize = L[0].length(); + int windowSize = wordSize * L.length; + + ArrayList ans = new ArrayList(); + for (int i = 0; i <= S.length() - windowSize; i++) { + HashMap temp = new HashMap(); + boolean skip = false; + for (int j = 0; j < windowSize; j += wordSize) { + String word = S.substring(i + j, i + j + wordSize); + Integer count = dict.get(word); + if (count == null) { + skip = true; + break; + } + Integer tempCount = temp.get(word); + if (tempCount == null) { + temp.put(word, 1); + } else if (count == tempCount) { + skip = true; + break; + } else { + temp.put(word, tempCount + 1); + } + } + if (!skip && dict.equals(temp)) { + ans.add(i); + } + } + return ans; + } + } + + public static class UnitTest { + } +} From fcb67719935f37f4f26656a05a1fd41e75c544b6 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 24 Nov 2013 21:37:49 +0800 Subject: [PATCH 037/456] Solve the 'Max Points on a Line' question --- src/main/java/common/Point.java | 16 +++++ .../MaxPointsonaLine.java | 59 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/main/java/common/Point.java create mode 100644 src/main/java/max_points_on_a_line/MaxPointsonaLine.java diff --git a/src/main/java/common/Point.java b/src/main/java/common/Point.java new file mode 100644 index 0000000..f25349d --- /dev/null +++ b/src/main/java/common/Point.java @@ -0,0 +1,16 @@ +package common; + +class Point { + public int x; + public int y; + + public Point() { + x = 0; + y = 0; + } + + public Point(int a, int b) { + x = a; + y = b; + } +} \ No newline at end of file diff --git a/src/main/java/max_points_on_a_line/MaxPointsonaLine.java b/src/main/java/max_points_on_a_line/MaxPointsonaLine.java new file mode 100644 index 0000000..79a2b37 --- /dev/null +++ b/src/main/java/max_points_on_a_line/MaxPointsonaLine.java @@ -0,0 +1,59 @@ +package max_points_on_a_line; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.List; + +public class MaxPointsonaLine { + + public class Solution { + + private class Line { + Point p1; + Point p2; + + Line(Point p1, Point p2) { + this.p1 = p1; + this.p2 = p2; + } + } + + private boolean isOnTheSameLine(Point p1, Point p2, Point p3) { + return (p3.y - p2.y) * (p2.x - p1.x) == (p3.x - p2.x) + * (p2.y - p1.y); + } + + public int maxPoints(Point[] points) { + List lines = new ArrayList(); + for (int i = 0; i < points.length; i++) { + for (int j = i + 1; j < points.length; j++) { + if (points[i].x != points[j].x + || points[i].y != points[j].y) { + lines.add(new Line(points[i], points[j])); + } + } + } + if (lines.size() == 0) { + return points.length; + } + int[] counts = new int[lines.size()]; + for (int i = 0; i < lines.size(); i++) { + Line line = lines.get(i); + for (Point point : points) { + if (isOnTheSameLine(line.p1, line.p2, point)) { + counts[i]++; + } + } + } + int max = counts[0]; + for (int i = 1; i < counts.length; i++) { + max = Math.max(max, counts[i]); + } + return max; + } + } + + public static class UnitTest { + + } +} From 7f67216d5c2c707fa0a71d97aa317b7310afae8c Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 24 Nov 2013 23:57:31 +0800 Subject: [PATCH 038/456] Solve the 'Anagrams' question --- src/main/java/anagrams/Anagrams.java | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/anagrams/Anagrams.java diff --git a/src/main/java/anagrams/Anagrams.java b/src/main/java/anagrams/Anagrams.java new file mode 100644 index 0000000..3701d25 --- /dev/null +++ b/src/main/java/anagrams/Anagrams.java @@ -0,0 +1,39 @@ +package anagrams; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public class Anagrams { + + public class Solution { + public ArrayList anagrams(String[] strs) { + Map> dict = new HashMap>(); + for (String str : strs) { + char[] cs = str.toCharArray(); + Arrays.sort(cs); + String anagram = new String(cs); + List l = dict.get(anagram); + if (l == null) { + l = new ArrayList(); + dict.put(anagram, l); + } + l.add(str); + } + ArrayList ans = new ArrayList(); + for (Entry> e : dict.entrySet()) { + if (e.getValue().size() > 1) { + ans.addAll(e.getValue()); + } + } + return ans; + } + } + + public static class UnitTest { + + } +} From ea5fc2642bf1b756fcb519c6b3710663e187249f Mon Sep 17 00:00:00 2001 From: zsxwing Date: Mon, 25 Nov 2013 22:54:17 +0800 Subject: [PATCH 039/456] Solve the 'Valid Number' question --- src/main/java/valid_number/ValidNumber.java | 103 ++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/main/java/valid_number/ValidNumber.java diff --git a/src/main/java/valid_number/ValidNumber.java b/src/main/java/valid_number/ValidNumber.java new file mode 100644 index 0000000..2c66950 --- /dev/null +++ b/src/main/java/valid_number/ValidNumber.java @@ -0,0 +1,103 @@ +package valid_number; + +public class ValidNumber { + + enum Status { + INIT, SYMBOL, INT, DOT, FRAC, E, SYMBOL_E, INT_E + } + + public class Solution { + + public boolean isNumber(String s) { + s = s.trim(); + Status status = Status.INIT; + boolean hasInt = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (status) { + case INIT: + if (c == '+' || c == '-') { + status = Status.SYMBOL; + } else if (Character.isDigit(c)) { + status = Status.INT; + hasInt = true; + } else if (c == '.') { + status = Status.DOT; + } else { + return false; + } + break; + case SYMBOL: + if (Character.isDigit(c)) { + status = Status.INT; + hasInt = true; + } else if (c == '.') { + status = Status.DOT; + } else { + return false; + } + break; + case INT: + if (Character.isDigit(c)) { + + } else if (c == '.') { + status = Status.DOT; + } else if (c == 'E' || c == 'e') { + status = Status.E; + } else { + return false; + } + break; + case DOT: + if (Character.isDigit(c)) { + status = Status.FRAC; + } else if (c == 'E' || c == 'e') { + if (!hasInt) { + return false; + } + status = Status.E; + } else { + return false; + } + break; + case FRAC: + if (Character.isDigit(c)) { + } else if (c == 'E' || c == 'e') { + status = Status.E; + } else { + return false; + } + break; + case E: + if (Character.isDigit(c)) { + status = Status.INT_E; + } else if (c == '+' || c == '-') { + status = Status.SYMBOL_E; + } else { + return false; + } + break; + case SYMBOL_E: + if (Character.isDigit(c)) { + status = Status.INT_E; + } else { + return false; + } + break; + case INT_E: + if (Character.isDigit(c)) { + } else { + return false; + } + break; + } + } + return (hasInt && status == Status.DOT) || status == Status.INT + || status == Status.FRAC || status == Status.INT_E; + } + } + + public static class UnitTest { + + } +} From 792fb1a88e85836e4954c771d4695e71238ea8f0 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 26 Nov 2013 21:31:24 +0800 Subject: [PATCH 040/456] Solve the 'Multiply Strings' question --- .../multiply_strings/MultiplyStrings.java | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/main/java/multiply_strings/MultiplyStrings.java diff --git a/src/main/java/multiply_strings/MultiplyStrings.java b/src/main/java/multiply_strings/MultiplyStrings.java new file mode 100644 index 0000000..07bab2a --- /dev/null +++ b/src/main/java/multiply_strings/MultiplyStrings.java @@ -0,0 +1,90 @@ +package multiply_strings; + +import java.util.ArrayList; +import java.util.List; + +public class MultiplyStrings { + + public class Solution { + + private List multiply(List l1, List l2) { + List result = new ArrayList(); + for (int offset = 0; offset < l2.size(); offset++) { + if (l2.get(offset) != 0) { + List temp = multiplyDigit(l1, l2.get(offset)); + result = add(temp, result, offset); + } + } + return result; + } + + private List add(List l1, List l2, int offset) { + List result = new ArrayList(); + int index = 0; + while (index < offset) { + if (index < l2.size()) { + result.add(l2.get(index)); + } else { + result.add(0); + } + index++; + } + int carry = 0; + for (int i : l1) { + int value = i + carry + (index < l2.size() ? l2.get(index) : 0); + result.add(value % 10); + carry = value / 10; + index++; + } + if (carry != 0) { + result.add(carry); + } + return result; + } + + private List toList(String s) { + List result = new ArrayList(); + for (int i = s.length() - 1; i >= 0; i--) { + result.add(s.charAt(i) - '0'); + } + return result; + } + + private String toString(List l) { + StringBuilder builder = new StringBuilder(); + int i = l.size() - 1; + for (; i >= 0; i--) { + if (l.get(i) != 0) { + break; + } + } + for (; i >= 0; i--) { + builder.append(l.get(i)); + } + if (builder.length() == 0) { + return "0"; + } + return builder.toString(); + } + + private List multiplyDigit(List l, int digit) { + List result = new ArrayList(); + int carry = 0; + for (int i : l) { + result.add((i * digit + carry) % 10); + carry = (i * digit + carry) / 10; + } + if (carry != 0) { + result.add(carry); + } + return result; + } + + public String multiply(String num1, String num2) { + return toString(multiply(toList(num1), toList(num2))); + } + } + + public static class UnitTest { + } +} From 56d810518b34e4b59dd816e8d176a3df75a058c9 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 26 Nov 2013 22:26:44 +0800 Subject: [PATCH 041/456] Solve the 'Wildcard Matching' question --- .../wildcard_matching/WildcardMatching.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/wildcard_matching/WildcardMatching.java diff --git a/src/main/java/wildcard_matching/WildcardMatching.java b/src/main/java/wildcard_matching/WildcardMatching.java new file mode 100644 index 0000000..b1e44f8 --- /dev/null +++ b/src/main/java/wildcard_matching/WildcardMatching.java @@ -0,0 +1,46 @@ +package wildcard_matching; + +public class WildcardMatching { + + public class Solution { + + private int minLength(String p) { + int len = 0; + for (int i = 0; i < p.length(); i++) { + if (p.charAt(i) != '*') { + len++; + } + } + return len; + } + + public boolean isMatch(String s, String p) { + if (s.length() < minLength(p)) { + return false; + } + boolean[] dp = new boolean[s.length() + 1]; + dp[0] = true; + for (int i = 1; i <= p.length(); i++) { + for (int j = s.length(); j > 0; j--) { + if (p.charAt(i - 1) == '*') { + for (int k = 0; k <= j; k++) { + if (dp[k]) { + dp[j] = true; + break; + } + } + } else { + dp[j] = dp[j - 1] + && (p.charAt(i - 1) == '?' || p.charAt(i - 1) == s + .charAt(j - 1)); + } + } + dp[0] = p.charAt(i - 1) == '*' && dp[0]; + } + return dp[s.length()]; + } + } + + public static class UnitTest { + } +} From 6d9fa8c381cdc4ee39c09e098fadc821dbe47172 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 27 Nov 2013 23:01:06 +0800 Subject: [PATCH 042/456] Solve the 'Regular Expression Matching' question --- .../RegularExpressionMatching.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/regular_expression_matching/RegularExpressionMatching.java diff --git a/src/main/java/regular_expression_matching/RegularExpressionMatching.java b/src/main/java/regular_expression_matching/RegularExpressionMatching.java new file mode 100644 index 0000000..b7a382b --- /dev/null +++ b/src/main/java/regular_expression_matching/RegularExpressionMatching.java @@ -0,0 +1,42 @@ +package regular_expression_matching; + + +public class RegularExpressionMatching { + + public class Solution { + public boolean isMatch(String s, String p) { + boolean[][] dp = new boolean[p.length() + 1][s.length() + 1]; + dp[0][0] = true; + for (int i = 1; i <= p.length(); i++) { + dp[i][0] = p.charAt(i - 1) == '*' && dp[i - 2][0]; + for (int j = 1; j <= s.length(); j++) { + if (p.charAt(i - 1) == '*') { + if (dp[i - 2][j]) { + dp[i][j] = true; + continue; + } + char prev = p.charAt(i - 2); + for (int k = j; k > 0; k--) { + if (prev != '.' && prev != s.charAt(k - 1)) { + break; + } + if (dp[i - 2][k - 1]) { + dp[i][j] = true; + break; + } + } + } else { + dp[i][j] = dp[i - 1][j - 1] + && (p.charAt(i - 1) == '.' || p.charAt(i - 1) == s + .charAt(j - 1)); + } + } + + } + return dp[p.length()][s.length()]; + } + } + + public static class UnitTest { + } +} From 00867f8871fcd14cf35209a4368b311794e6b0ee Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 27 Nov 2013 23:23:26 +0800 Subject: [PATCH 043/456] Solve the 'Combination Sum II' question --- .../combination_sum_ii/CombinationSumII.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/combination_sum_ii/CombinationSumII.java diff --git a/src/main/java/combination_sum_ii/CombinationSumII.java b/src/main/java/combination_sum_ii/CombinationSumII.java new file mode 100644 index 0000000..12edcdb --- /dev/null +++ b/src/main/java/combination_sum_ii/CombinationSumII.java @@ -0,0 +1,62 @@ +package combination_sum_ii; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CombinationSumII { + + public class Solution { + private void search(List nums, List counts, + int index, int target, ArrayDeque s, + ArrayList> ans) { + if (target == 0) { + ans.add(new ArrayList(s)); + } + if (target <= 0 || index == nums.size()) { + return; + } + int n = nums.get(index); + int count = counts.get(index); + for (int i = 0; i <= count; i++) { + search(nums, counts, index + 1, target - i * n, s, ans); + s.offerLast(n); + } + for (int i = 0; i <= count; i++) { + s.removeLast(); + } + } + + public ArrayList> combinationSum2(int[] num, + int target) { + ArrayList> ans = new ArrayList>(); + if (num.length == 0) { + return ans; + } + Arrays.sort(num); + List nums = new ArrayList(); + List counts = new ArrayList(); + int count = 1; + int i = 1; + for (; i < num.length; i++) { + if (num[i] != num[i - 1]) { + nums.add(num[i - 1]); + counts.add(count); + count = 1; + } else { + count++; + } + + } + nums.add(num[i - 1]); + counts.add(count); + search(nums, counts, 0, target, new ArrayDeque(), ans); + return ans; + } + } + + public static class UnitTest { + + } +} From f72b387eff93953ea5ce5439155f0bfedf43d165 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 28 Nov 2013 19:00:28 +0800 Subject: [PATCH 044/456] Solve the 'Evaluate Reverse Polish Notation' question --- .../EvaluateReversePolishNotation.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/evaluate_reverse_polish_notation/EvaluateReversePolishNotation.java diff --git a/src/main/java/evaluate_reverse_polish_notation/EvaluateReversePolishNotation.java b/src/main/java/evaluate_reverse_polish_notation/EvaluateReversePolishNotation.java new file mode 100644 index 0000000..5c21723 --- /dev/null +++ b/src/main/java/evaluate_reverse_polish_notation/EvaluateReversePolishNotation.java @@ -0,0 +1,38 @@ +package evaluate_reverse_polish_notation; + +import java.util.ArrayDeque; + +public class EvaluateReversePolishNotation { + + public class Solution { + public int evalRPN(String[] tokens) { + ArrayDeque stack = new ArrayDeque(); + for (String token : tokens) { + if (token.equals("+")) { + int num2 = stack.removeLast(); + int num1 = stack.removeLast(); + stack.offerLast(num1 + num2); + } else if (token.equals("-")) { + int num2 = stack.removeLast(); + int num1 = stack.removeLast(); + stack.offerLast(num1 - num2); + } else if (token.equals("*")) { + int num2 = stack.removeLast(); + int num1 = stack.removeLast(); + stack.offerLast(num1 * num2); + } else if (token.equals("/")) { + int num2 = stack.removeLast(); + int num1 = stack.removeLast(); + stack.offerLast(num1 / num2); + } else { + stack.offerLast(Integer.parseInt(token)); + } + } + return stack.removeLast(); + } + } + + public static class UnitTest { + + } +} From cb16952419792dae1c100666e6d3e0ddedbfc0d4 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 28 Nov 2013 21:27:59 +0800 Subject: [PATCH 045/456] Solve the 'Reverse Nodes in k-Group' question --- .../ReverseNodesinkGroup.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java diff --git a/src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java b/src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java new file mode 100644 index 0000000..8585bd8 --- /dev/null +++ b/src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java @@ -0,0 +1,50 @@ +package reverse_nodes_in_kgroup; + +import common.ListNode; + +public class ReverseNodesinkGroup { + + public class Solution { + private ListNode reverseGroup(ListNode start, ListNode end) { + ListNode prefix = start.next; + ListNode p = prefix.next; + while (p != end) { + ListNode temp = p.next; + p.next = prefix; + prefix = p; + p = temp; + } + ListNode temp = start.next; + start.next = prefix; + temp.next = end; + return temp; + } + + public ListNode reverseKGroup(ListNode head, int k) { + if (k == 0) { + return head; + } + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode start = dummy; + ListNode end = start.next; + int count = 0; + while (end != null) { + if (count == k) { + start = reverseGroup(start, end); + count = 0; + } + count++; + end = end.next; + } + if (count == k) { + reverseGroup(start, end); + } + return dummy.next; + } + } + + public static class UnitTest { + + } +} From 00b2116126f9d34822e6b2f2764c4acc1dfdac88 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 28 Nov 2013 22:32:30 +0800 Subject: [PATCH 046/456] Solve the 'Simplify Path' question --- src/main/java/simplify_path/SimplifyPath.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/simplify_path/SimplifyPath.java diff --git a/src/main/java/simplify_path/SimplifyPath.java b/src/main/java/simplify_path/SimplifyPath.java new file mode 100644 index 0000000..814f675 --- /dev/null +++ b/src/main/java/simplify_path/SimplifyPath.java @@ -0,0 +1,36 @@ +package simplify_path; + +import java.util.ArrayDeque; + +public class SimplifyPath { + + public class Solution { + public String simplifyPath(String path) { + String[] splits = path.split("/"); + ArrayDeque stack = new ArrayDeque(); + for (String split : splits) { + if (!split.isEmpty()) { + if (split.equals("..")) { + if (!stack.isEmpty()) { + stack.removeLast(); + } + } else if (split.equals(".")) { + continue; + } else { + stack.offerLast(split); + } + } + } + StringBuilder newPath = new StringBuilder(); + for (String s : stack) { + newPath.append('/'); + newPath.append(s); + } + return newPath.length() == 0 ? "/" : newPath.toString(); + } + } + + public static class UnitTest { + + } +} From 7f0c9a394f5f784295352d021deb21f60bb82914 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 28 Nov 2013 23:10:11 +0800 Subject: [PATCH 047/456] Solve the 'Minimum Window Substring' question --- .../MinimumWindowSubstring.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/main/java/minimum_window_substring/MinimumWindowSubstring.java diff --git a/src/main/java/minimum_window_substring/MinimumWindowSubstring.java b/src/main/java/minimum_window_substring/MinimumWindowSubstring.java new file mode 100644 index 0000000..0711b9b --- /dev/null +++ b/src/main/java/minimum_window_substring/MinimumWindowSubstring.java @@ -0,0 +1,63 @@ +package minimum_window_substring; + +public class MinimumWindowSubstring { + + public class Solution { + public String minWindow(String S, String T) { + int[] tCount = new int[256]; + for (int i = 0; i < T.length(); i++) { + tCount[T.charAt(i)]++; + } + int[] sCount = new int[256]; + int i = 0; + for (; i < S.length(); i++) { + sCount[S.charAt(i)]++; + boolean find = true; + for (int j = 0; j < 256; j++) { + if (sCount[j] < tCount[j]) { + find = false; + break; + } + } + if (find) { + break; + } + } + if (i == S.length()) { + return ""; + } + int windowStart = 0; + int windowEnd = i; + int minWindowStart = windowStart; + int minWindowEnd = windowEnd; + while (windowStart < S.length()) { + char c = S.charAt(windowStart); + sCount[c]--; + windowStart++; + if (sCount[c] < tCount[c]) { + windowEnd++; + while (windowEnd < S.length()) { + char endC = S.charAt(windowEnd); + sCount[endC]++; + if (c == endC) { + break; + } + windowEnd++; + } + if (windowEnd == S.length()) { + break; + } + } + if (windowEnd - windowStart < minWindowEnd - minWindowStart) { + minWindowStart = windowStart; + minWindowEnd = windowEnd; + } + } + return S.substring(minWindowStart, minWindowEnd + 1); + } + } + + public static class UnitTest { + + } +} From a566b1b5c456075e3c3900a2c771a9550d768036 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 28 Nov 2013 23:19:43 +0800 Subject: [PATCH 048/456] Solve the '4Sum' question --- src/main/java/_4sum/_4Sum.java | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/_4sum/_4Sum.java diff --git a/src/main/java/_4sum/_4Sum.java b/src/main/java/_4sum/_4Sum.java new file mode 100644 index 0000000..bf8eaa4 --- /dev/null +++ b/src/main/java/_4sum/_4Sum.java @@ -0,0 +1,62 @@ +package _4sum; + +import java.util.ArrayList; +import java.util.Arrays; + +public class _4Sum { + + public class Solution { + + private ArrayList list(int... ns) { + ArrayList l = new ArrayList(); + for (int n : ns) { + l.add(n); + } + return l; + } + + private void twoSum(int[] num, int a, int b, int start, int target, + ArrayList> quadruplets) { + int low = start; + int high = num.length - 1; + while (low < high) { + int sum = num[low] + num[high]; + if (sum < target) { + low++; + } else if (sum > target) { + high--; + } else { + quadruplets.add(list(a, b, num[low], num[high])); + do { + low++; + } while (low < high && num[low] == num[low - 1]); + do { + high--; + } while (low < high && num[high] == num[high + 1]); + } + } + } + + public ArrayList> fourSum(int[] num, int target) { + ArrayList> quadruplets = new ArrayList>(); + Arrays.sort(num); + for (int i = 0; i < num.length - 3; i++) { + if (i != 0 && num[i] == num[i - 1]) { + continue; + } + for (int j = i + 1; j < num.length - 2; j++) { + if (j != i + 1 && num[j] == num[j - 1]) { + continue; + } + twoSum(num, num[i], num[j], j + 1, + target - num[i] - num[j], quadruplets); + } + } + return quadruplets; + } + } + + public static class UnitTest { + + } +} From 1d6e0606c85792b472767ceb212f837811dd44e1 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sat, 30 Nov 2013 23:21:10 +0800 Subject: [PATCH 049/456] Solve the 'Word Ladder II' question --- .../java/word_ladder_ii/WordLadderII.java | 128 ++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 src/main/java/word_ladder_ii/WordLadderII.java diff --git a/src/main/java/word_ladder_ii/WordLadderII.java b/src/main/java/word_ladder_ii/WordLadderII.java new file mode 100644 index 0000000..3e8b77c --- /dev/null +++ b/src/main/java/word_ladder_ii/WordLadderII.java @@ -0,0 +1,128 @@ +package word_ladder_ii; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +public class WordLadderII { + + /** + * "Time Limit Exceeded". Is there a perfect Java solution to pass the + * tests? + */ + public class Solution { + + private HashMap> searchNeighbors(String[] nodes) { + HashMap indices = new HashMap( + nodes.length); + int i = 0; + for (String word : nodes) { + indices.put(word, i++); + } + + HashMap> neighbors = new HashMap>(); + + i = 0; + for (String word : nodes) { + List neighbor = neighbors.get(word); + if (neighbor == null) { + neighbor = new ArrayList(); + neighbors.put(i, neighbor); + } + char[] temp = word.toCharArray(); + for (int j = 0; j < temp.length; j++) { + char oldC = temp[j]; + for (char c = 'a'; c <= 'z'; c++) { + if (c != oldC) { + temp[j] = c; + String newS = new String(temp); + Integer index = indices.get(newS); + if (index != null) { + neighbor.add(index); + } + } + } + temp[j] = oldC; + } + i++; + } + return neighbors; + } + + public ArrayList> findLadders(String start, + String end, HashSet dict) { + ArrayList> ans = new ArrayList>(); + + if (start.equals(end)) { + ArrayList l = new ArrayList(); + l.add(start); + ans.add(l); + return ans; + } + + ArrayList queue = new ArrayList(); + ArrayList prev = new ArrayList(); + + dict.add(start); + dict.add(end); + + String[] nodes = new String[dict.size()]; + int j = 0; + int startIndex = 0; + int endIndex = 0; + for (String word : dict) { + if (word.equals(start)) { + startIndex = j; + } + if (word.equals(end)) { + endIndex = j; + } + nodes[j++] = word; + } + HashMap> neighbors = searchNeighbors(nodes); + System.gc(); // To avoid "Memory Limit Exceeded" + + queue.add(startIndex); + prev.add(-1); + boolean[] used = new boolean[nodes.length]; + used[startIndex] = true; + int begin = 0; + boolean find = false; + while (!find && begin < queue.size()) { + int tail = queue.size(); + for (int i = begin; i < tail; i++) { + int s = queue.get(i); + for (int indexInNode : neighbors.get(s)) { + if (indexInNode == endIndex) { + find = true; + ArrayList path = new ArrayList(); + path.add(end); + int index = i; + while (index >= 0) { + path.add(nodes[queue.get(index)]); + index = prev.get(index); + } + Collections.reverse(path); + ans.add(path); + break; + } + if (!find && !used[indexInNode]) { + queue.add(indexInNode); + prev.add(i); + } + } + } + begin = tail; + for (int i = begin; i < tail; i++) { + used[queue.get(i)] = true; + } + } + return ans; + } + } + + public static class UnitTest { + } +} From b8596eba1d50ca8f71c2b38642adda39072ee85b Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sat, 30 Nov 2013 23:23:37 +0800 Subject: [PATCH 050/456] Solve the 'Insert Interval' question --- .../java/insert_interval/InsertInterval.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/insert_interval/InsertInterval.java diff --git a/src/main/java/insert_interval/InsertInterval.java b/src/main/java/insert_interval/InsertInterval.java new file mode 100644 index 0000000..f22a15e --- /dev/null +++ b/src/main/java/insert_interval/InsertInterval.java @@ -0,0 +1,38 @@ +package insert_interval; + +import java.util.ArrayList; + +import common.Interval; + +public class InsertInterval { + + /** + * "Output Limit Exceeded". Is there a perfect Java solution to pass the + * tests? + */ + public class Solution { + + public ArrayList insert(ArrayList intervals, + Interval newInterval) { + for (int i = 0; i < intervals.size(); i++) { + Interval interval = intervals.get(i); + if (newInterval.end > interval.start) { + intervals.add(i, newInterval); + return intervals; + } + if (newInterval.start >= interval.end) { + newInterval.start = Math.min(newInterval.start, + interval.start); + newInterval.end = Math.max(newInterval.end, interval.end); + intervals.remove(i); + } + } + intervals.add(newInterval); + return intervals; + } + } + + public static class UnitTest { + + } +} From 80d732c9789030e9a890af1ecd338553e0c0b08b Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 15 Dec 2013 12:38:30 +0800 Subject: [PATCH 051/456] Update the solution --- .../MaxPointsonaLine.java | 37 ++++++------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/src/main/java/max_points_on_a_line/MaxPointsonaLine.java b/src/main/java/max_points_on_a_line/MaxPointsonaLine.java index 79a2b37..58c9e8e 100644 --- a/src/main/java/max_points_on_a_line/MaxPointsonaLine.java +++ b/src/main/java/max_points_on_a_line/MaxPointsonaLine.java @@ -8,46 +8,33 @@ public class MaxPointsonaLine { public class Solution { - private class Line { - Point p1; - Point p2; - - Line(Point p1, Point p2) { - this.p1 = p1; - this.p2 = p2; - } - } - - private boolean isOnTheSameLine(Point p1, Point p2, Point p3) { - return (p3.y - p2.y) * (p2.x - p1.x) == (p3.x - p2.x) - * (p2.y - p1.y); + private boolean isOnLine(Point p1, Point p2, Point p3) { + return (p1.y - p2.y) * (p2.x - p3.x) == (p1.x - p2.x) + * (p2.y - p3.y); } public int maxPoints(Point[] points) { - List lines = new ArrayList(); + List lines = new ArrayList(); for (int i = 0; i < points.length; i++) { for (int j = i + 1; j < points.length; j++) { if (points[i].x != points[j].x || points[i].y != points[j].y) { - lines.add(new Line(points[i], points[j])); + lines.add(new Point[] { points[i], points[j] }); } } } - if (lines.size() == 0) { + if (lines.isEmpty()) { return points.length; } - int[] counts = new int[lines.size()]; - for (int i = 0; i < lines.size(); i++) { - Line line = lines.get(i); + int max = 0; + for (Point[] line : lines) { + int count = 0; for (Point point : points) { - if (isOnTheSameLine(line.p1, line.p2, point)) { - counts[i]++; + if (isOnLine(line[0], line[1], point)) { + count++; } } - } - int max = counts[0]; - for (int i = 1; i < counts.length; i++) { - max = Math.max(max, counts[i]); + max = Math.max(max, count); } return max; } From 4e5b1b961dfad8d17234c3dd97b6af72d9b5695c Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 17 Jun 2014 23:09:32 +0800 Subject: [PATCH 052/456] Fix a tiny bug --- .../LongestPalindromicSubstring.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java b/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java index 3965af0..83b0e67 100644 --- a/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java +++ b/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java @@ -29,7 +29,7 @@ public String longestPalindrome(String s) { p[i]++; } if (rightIndex < i + p[i]) { - rightIndex = i; + rightIndex = i + p[i]; id = i; } } From 92c3781e950f80de2bcf7e6a827cb3ea7254fe80 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 17 Jun 2014 23:10:01 +0800 Subject: [PATCH 053/456] Solve the 'Reverse Words in a String' question --- .../ReverseWordsinaString.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java diff --git a/src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java b/src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java new file mode 100644 index 0000000..c58ff0c --- /dev/null +++ b/src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java @@ -0,0 +1,29 @@ +package reverse_words_in_a_string; + +public class ReverseWordsinaString { + + public class Solution { + public String reverseWords(String s) { + String[] tokens = s.split(" +"); + StringBuilder r = new StringBuilder(); + boolean isFirst = true; + for (int i = tokens.length - 1; i >= 0; i--) { + String token = tokens[i]; + if (token.isEmpty()) { + continue; + } + if (isFirst) { + isFirst = false; + } else { + r.append(' '); + } + r.append(token); + } + return r.toString(); + } + } + + public static class UnitTest { + + } +} From ff36774d5a1d13fb1cb506913e4db3d8b50d15f4 Mon Sep 17 00:00:00 2001 From: pansophism Date: Sat, 6 Dec 2014 21:39:24 -0800 Subject: [PATCH 054/456] bug fix for CloneGraph --- src/main/java/clone_graph/CloneGraph.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/clone_graph/CloneGraph.java b/src/main/java/clone_graph/CloneGraph.java index 244f805..bad5c20 100644 --- a/src/main/java/clone_graph/CloneGraph.java +++ b/src/main/java/clone_graph/CloneGraph.java @@ -18,7 +18,7 @@ private UndirectedGraphNode cloneGraph(UndirectedGraphNode node, } newNode.neighbors.add(newNeighbor); } - return node; + return newNode; } public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { From 599d3b2868c776c7cda9bf8687d296d9fa685a4d Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 9 Dec 2014 22:45:49 +0800 Subject: [PATCH 055/456] Add gradlew --- README.md | 12 +- build.gradle | 5 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 51348 bytes gradle/wrapper/gradle-wrapper.properties | 6 + gradlew | 164 +++++++++++++++++++++++ gradlew.bat | 90 +++++++++++++ 6 files changed, 274 insertions(+), 3 deletions(-) create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat diff --git a/README.md b/README.md index 8d6e9b8..4dc78d3 100644 --- a/README.md +++ b/README.md @@ -13,13 +13,19 @@ My Java solutions for [LeetCode Online Judge](http://oj.leetcode.com/). ## Generate an eclipse project ```bash -gradle eclipse +./gradlew eclipse +``` + +## Generate an IntelliJ IDEA project + +```bash +./gradlew idea ``` ## Generate a file for a question ```bash -gradle question "-Pq=Some Question" +./gradlew question "-Pq=Some Question" ``` The above command will generate a source file called `src/main/java/some_question/SomeQuestion.java`, and you can write your solution in this file directly. @@ -31,6 +37,6 @@ Unit tests are also embedded as inner classes of the main code. For an explanati If you write some unit tests, you can use the following command to run them. ```bash -gradle test +./gradlew test ``` diff --git a/build.gradle b/build.gradle index 00f47a8..1612599 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,6 @@ apply plugin: 'java' apply plugin: 'eclipse' +apply plugin: 'idea' sourceCompatibility = JavaVersion.VERSION_1_6 targetCompatibility = JavaVersion.VERSION_1_6 @@ -28,6 +29,10 @@ dependencies { sourceSets.test.java.srcDir 'src/main/java' +task wrapper(type: Wrapper) { + gradleVersion = '1.8' +} + task(question) << { def insertUnderlineIfStartsWithDigit = { s -> diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..0087cd3b18659b5577cf6ad3ef61f8eb9416ebba GIT binary patch literal 51348 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

CflOl1i4(-2^1KXo)&I5QlgjRKFQgM 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 z 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 literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..71233fc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Dec 09 22:42:19 CST 2014 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-1.8-bin.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..91a7e26 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega From 13b4a3265cd8c53815026c86c8e1fcf229d0fcd4 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 9 Dec 2014 23:00:34 +0800 Subject: [PATCH 056/456] Update .gitignore for IDEA --- .gitignore | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.gitignore b/.gitignore index 848782f..f560c52 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,12 @@ target build bin .gradle + +# IntelliJ specific files/directories +out +.idea +*.ipr +*.iws +*.iml +atlassian-ide-plugin.xml + From b91c9328daf96336004fdcd695809c508607f167 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 9 Dec 2014 23:01:23 +0800 Subject: [PATCH 057/456] Solve the 'Intersection of Two Linked Lists' question --- .../IntersectionofTwoLinkedLists.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java diff --git a/src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java b/src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java new file mode 100644 index 0000000..8a54dc6 --- /dev/null +++ b/src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java @@ -0,0 +1,45 @@ +package intersection_of_two_linked_lists; + +import common.ListNode; + +public class IntersectionofTwoLinkedLists { + + public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + if (headA == null) { + return null; + } + ListNode tailA = headA; + while (tailA.next != null) { + tailA = tailA.next; + } + tailA.next = headB; + + // Find the beginning of the cycle + ListNode fast = headA; + ListNode slow = headA; + do { + if (fast == null || fast.next == null) { + tailA.next = null; + return null; + } + fast = fast.next.next; + slow = slow.next; + if (slow == fast) { + fast = headA; + while (fast != slow) { + fast = fast.next; + slow = slow.next; + } + tailA.next = null; + return fast; + } + } while (true); + } + } + + public static class UnitTest { + + } +} + From a5991e8ed1e417279e4c384c4bd76f2d7ab99b77 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 9 Dec 2014 23:31:51 +0800 Subject: [PATCH 058/456] Solve the 'Find Minimum in Rotated Sorted Array' question --- .../FindMinimuminRotatedSortedArray.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/find_minimum_in_rotated_sorted_array/FindMinimuminRotatedSortedArray.java diff --git a/src/main/java/find_minimum_in_rotated_sorted_array/FindMinimuminRotatedSortedArray.java b/src/main/java/find_minimum_in_rotated_sorted_array/FindMinimuminRotatedSortedArray.java new file mode 100644 index 0000000..c27dda1 --- /dev/null +++ b/src/main/java/find_minimum_in_rotated_sorted_array/FindMinimuminRotatedSortedArray.java @@ -0,0 +1,35 @@ +package find_minimum_in_rotated_sorted_array; + +import java.util.*; + +import org.junit.*; + +import static org.junit.Assert.*; + +public class FindMinimuminRotatedSortedArray { + + public class Solution { + public int findMin(int[] num) { + assert (num.length > 0); + int left = 0; + int right = num.length - 1; + while (left < right) { + if (num[left] < num[right]) { + return num[left]; + } + int mid = left + (right - left) / 2; + if (num[left] <= num[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + return num[left]; + } + } + + public static class UnitTest { + + } +} + From c164844fdb0095e4f7ab868c5a7ee88cf01f53e8 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 9 Dec 2014 23:37:50 +0800 Subject: [PATCH 059/456] Solve the 'Find Minimum in Rotated Sorted Array II' question --- .../FindMinimuminRotatedSortedArrayII.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/find_minimum_in_rotated_sorted_array_ii/FindMinimuminRotatedSortedArrayII.java diff --git a/src/main/java/find_minimum_in_rotated_sorted_array_ii/FindMinimuminRotatedSortedArrayII.java b/src/main/java/find_minimum_in_rotated_sorted_array_ii/FindMinimuminRotatedSortedArrayII.java new file mode 100644 index 0000000..8223f79 --- /dev/null +++ b/src/main/java/find_minimum_in_rotated_sorted_array_ii/FindMinimuminRotatedSortedArrayII.java @@ -0,0 +1,40 @@ +package find_minimum_in_rotated_sorted_array_ii; + +import java.util.*; + +import org.junit.*; + +import static org.junit.Assert.*; + +public class FindMinimuminRotatedSortedArrayII { + + public class Solution { + public int findMin(int[] num) { + assert (num.length > 0); + int left = 0; + int right = num.length - 1; + while (left < right) { + if (num[left] < num[right]) { + return num[left]; + } else if (num[left] == num[right]) { + right--; + } else { + int mid = left + (right - left) / 2; + if (num[left] == num[mid]) { + left++; + } else if (num[left] < num[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + } + return num[left]; + } + } + + public static class UnitTest { + + } +} + From 264189398b3b783b60a17ad1038a9340339a5db4 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 11 Dec 2014 22:45:21 +0800 Subject: [PATCH 060/456] Solve the 'Find Peak Element' question --- .../find_peak_element/FindPeakElement.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/find_peak_element/FindPeakElement.java diff --git a/src/main/java/find_peak_element/FindPeakElement.java b/src/main/java/find_peak_element/FindPeakElement.java new file mode 100644 index 0000000..7e2478e --- /dev/null +++ b/src/main/java/find_peak_element/FindPeakElement.java @@ -0,0 +1,27 @@ +package find_peak_element; + +import java.util.*; + +import org.junit.*; + +import static org.junit.Assert.*; + +public class FindPeakElement { + + public class Solution { + public int findPeakElement(int[] num) { + assert num.length != 0; + for (int i = 0; i < num.length - 1; i++) { + if (num[i] > num[i + 1]) { + return i; + } + } + return num.length - 1; + } + } + + public static class UnitTest { + + } +} + From 227a685cceaabc449b390016343418bb71b981b4 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 11 Dec 2014 23:15:44 +0800 Subject: [PATCH 061/456] Solve the 'Maximum Product Subarray' question --- .../MaximumProductSubarray.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/maximum_product_subarray/MaximumProductSubarray.java diff --git a/src/main/java/maximum_product_subarray/MaximumProductSubarray.java b/src/main/java/maximum_product_subarray/MaximumProductSubarray.java new file mode 100644 index 0000000..d36caf8 --- /dev/null +++ b/src/main/java/maximum_product_subarray/MaximumProductSubarray.java @@ -0,0 +1,42 @@ +package maximum_product_subarray; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class MaximumProductSubarray { + + public class Solution { + public int maxProduct(int[] A) { + assert A.length != 0; + int globalMax = A[0]; + int prevMax = A[0]; + int prevMin = A[0]; + for (int i = 1; i < A.length; i++) { + int max; + int min; + if (A[i] > 0) { + max = Math.max(A[i], prevMax * A[i]); + min = Math.min(A[i], prevMin * A[i]); + } else { + max = Math.max(A[i], prevMin * A[i]); + min = Math.min(A[i], prevMax * A[i]); + } + globalMax = Math.max(globalMax, max); + prevMax = max; + prevMin = min; + } + return globalMax; + } + } + + public static class UnitTest { + + @Test + public void testMaxProduct() { + Solution s = new MaximumProductSubarray().new Solution(); + assertEquals(12, s.maxProduct(new int[]{-4, -3, -2})); + } + } +} + From 2a3ee1bfdeea6ba46fe1f9420f5d0ffa4f878187 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 16 Dec 2014 00:27:14 +0800 Subject: [PATCH 062/456] Solve the 'Maximum Gap' question --- src/main/java/maximum_gap/MaximumGap.java | 62 +++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/maximum_gap/MaximumGap.java diff --git a/src/main/java/maximum_gap/MaximumGap.java b/src/main/java/maximum_gap/MaximumGap.java new file mode 100644 index 0000000..7aff947 --- /dev/null +++ b/src/main/java/maximum_gap/MaximumGap.java @@ -0,0 +1,62 @@ +package maximum_gap; + +import java.util.*; + +import org.junit.*; + +import static org.junit.Assert.*; + +public class MaximumGap { + + public class Solution { + public int maximumGap(int[] num) { + if (num.length < 2) { + return 0; + } + int min = num[0]; + int max = num[0]; + for (int i = 1; i < num.length; i++) { + min = Math.min(min, num[i]); + max = Math.max(max, num[i]); + } + if (min == max) { + return 0; + } + // ceil( (max - min) / (n - 1) ) + int gap = (max - min + num.length - 2) / (num.length - 1); + int bucketNum = (max - min) / gap + 1; + int[] minInBucket = new int[bucketNum]; + int[] maxInBucket = new int[bucketNum]; + Arrays.fill(minInBucket, -1); + Arrays.fill(maxInBucket, -1); + for (int i = 0; i < num.length; i++) { + int bucketId = (num[i] - min) / gap; + if (minInBucket[bucketId] < 0) { + minInBucket[bucketId] = maxInBucket[bucketId] = num[i]; + } else { + minInBucket[bucketId] = Math.min(minInBucket[bucketId], num[i]); + maxInBucket[bucketId] = Math.max(maxInBucket[bucketId], num[i]); + } + } + int currentMax; + int i = 0; + while (i < bucketNum && minInBucket[i] < 0) { + i++; + } + currentMax = maxInBucket[i]; + gap = 0; + for (i++; i < bucketNum; i++) { + if (minInBucket[i] >= 0) { + gap = Math.max(gap, minInBucket[i] - currentMax); + currentMax = maxInBucket[i]; + } + } + return gap; + } + } + + public static class UnitTest { + + } +} + From 87127913cf6698ec17862c368adf754e7de42936 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 16 Dec 2014 23:24:58 +0800 Subject: [PATCH 063/456] Solve the 'Compare Version Numbers' question --- .../CompareVersionNumbers.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/compare_version_numbers/CompareVersionNumbers.java diff --git a/src/main/java/compare_version_numbers/CompareVersionNumbers.java b/src/main/java/compare_version_numbers/CompareVersionNumbers.java new file mode 100644 index 0000000..0a87899 --- /dev/null +++ b/src/main/java/compare_version_numbers/CompareVersionNumbers.java @@ -0,0 +1,42 @@ +package compare_version_numbers; + +public class CompareVersionNumbers { + + public class Solution { + public int compareVersion(String version1, String version2) { + String[] splits1 = version1.split("\\."); + String[] splits2 = version2.split("\\."); + int i = 0; + for (; i < splits1.length && i < splits2.length; i++) { + int v1 = Integer.parseInt(splits1[i]); + int v2 = Integer.parseInt(splits2[i]); + if (v1 > v2) { + return 1; + } else if (v1 < v2) { + return -1; + } + } + if (i == splits1.length) { + for (int j = i; j < splits2.length; j++) { + int v = Integer.parseInt(splits2[j]); + if (v != 0) { + return -1; + } + } + } else { + for (int j = i; j < splits1.length; j++) { + int v = Integer.parseInt(splits1[j]); + if (v != 0) { + return 1; + } + } + } + return 0; + } + } + + public static class UnitTest { + + } +} + From 09ab37d370d4b8deffa3aeca7926e74561ab351c Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 11 Dec 2014 23:38:36 +0800 Subject: [PATCH 064/456] Solve the 'Min Stack' question --- src/main/java/min_stack/MinStack.java | 67 +++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/main/java/min_stack/MinStack.java diff --git a/src/main/java/min_stack/MinStack.java b/src/main/java/min_stack/MinStack.java new file mode 100644 index 0000000..036a224 --- /dev/null +++ b/src/main/java/min_stack/MinStack.java @@ -0,0 +1,67 @@ +package min_stack; + +public class MinStack { + + private static class IntStack { + private int[] items = new int[16]; + private int size = 0; + + private void ensureSize(int newSize) { + if (items.length < newSize) { + int[] newItems = new int[items.length * 2]; + System.arraycopy(items, 0, newItems, 0, items.length); + items = newItems; + } + } + + public void push(int v) { + ensureSize(size + 1); + items[size++] = v; + } + + public void pop() { + if (size == 0) { + throw new IllegalStateException("The stack is empty"); + } + size--; + } + + public int top() { + if (size == 0) { + throw new IllegalStateException("The stack is empty"); + } + return items[size - 1]; + } + + public boolean isEmpty() { + return size == 0; + } + } + + private IntStack minStack = new IntStack(); + private IntStack stack = new IntStack(); + + public void push(int x) { + if (stack.isEmpty() || x <= minStack.top()) { + minStack.push(x); + } + stack.push(x); + } + + public void pop() { + int x = stack.top(); + stack.pop(); + if (x == minStack.top()) { + minStack.pop(); + } + } + + public int top() { + return stack.top(); + } + + public int getMin() { + return minStack.top(); + } + +} From 9d4568b4dca5254462a25c4d76e4d2a672a6a748 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Wed, 17 Dec 2014 00:36:16 +0800 Subject: [PATCH 065/456] Solve the 'Fraction to Recurring Decimal' question --- .../FractiontoRecurringDecimal.java | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java diff --git a/src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java b/src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java new file mode 100644 index 0000000..09786d3 --- /dev/null +++ b/src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java @@ -0,0 +1,86 @@ +package fraction_to_recurring_decimal; + +import org.junit.Test; + +import java.util.ArrayList; + +import static org.junit.Assert.assertEquals; + +public class FractiontoRecurringDecimal { + + public class Solution { + + private String fraction(long mod, long divider) { + ArrayList mods = new ArrayList(); + mods.add(mod); + ArrayList remainders = new ArrayList(); + int i; + while (true) { + mod *= 10; + remainders.add(mod / divider); + mod = mod % divider; + if (mod == 0) { + i = -1; + break; + } + i = mods.indexOf(mod); + if (i >= 0) { + break; + } + mods.add(mod); + } + StringBuilder builder = new StringBuilder(); + if (i < 0) { + for (long r : remainders) { + builder.append(r); + } + } else { + int j = 0; + for (; j < i; j++) { + builder.append(remainders.get(j)); + } + builder.append('('); + for (; j < remainders.size(); j++) { + builder.append(remainders.get(j)); + } + builder.append(')'); + } + return builder.toString(); + } + + public String fractionToDecimal(int numerator, int denominator) { + boolean negative = (numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0); + long num = Math.abs((long) numerator); + long denom = Math.abs((long) denominator); + long remainder = num / denom; + long mod = num % denom; + if (mod == 0) { + if (negative) { + return "-" + remainder; + } else { + return Long.toString(remainder); + } + } else { + if (negative) { + return "-" + remainder + "." + fraction(mod, denom); + } else { + return remainder + "." + fraction(mod, denom); + } + } + + } + } + + public static class UnitTest { + + @Test + public void testFractionToDecimal() { + Solution s = new FractiontoRecurringDecimal().new Solution(); + assertEquals("3.(3)", s.fractionToDecimal(10, 3)); + assertEquals("0.75", s.fractionToDecimal(3, 4)); + assertEquals("0.(09)", s.fractionToDecimal(1, 11)); + assertEquals("0.0000000004656612873077392578125", s.fractionToDecimal(-1, -2147483648)); + } + } +} + From 2799be33c5613cd71bb1f1da153965a393d141c4 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Mon, 22 Dec 2014 23:55:24 +0800 Subject: [PATCH 066/456] Solve the 'Majority Element' question --- .../majority_element/MajorityElement.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/majority_element/MajorityElement.java diff --git a/src/main/java/majority_element/MajorityElement.java b/src/main/java/majority_element/MajorityElement.java new file mode 100644 index 0000000..635ce5a --- /dev/null +++ b/src/main/java/majority_element/MajorityElement.java @@ -0,0 +1,29 @@ +package majority_element; + +public class MajorityElement { + + public class Solution { + public int majorityElement(int[] num) { + int majority = num[0]; + int count = 1; + for (int i = 1; i < num.length; i++) { + if (majority != num[i]) { + count--; + if (count == 0) { + // the majority element always exist in the array + majority = num[++i]; + count = 1; + } + } else { + count++; + } + } + return majority; + } + } + + public static class UnitTest { + + } +} + From 651a1fa221c0cd1720c4842b76b80db5f267a0be Mon Sep 17 00:00:00 2001 From: zsxwing Date: Mon, 22 Dec 2014 23:48:36 +0800 Subject: [PATCH 067/456] Solve the 'Excel Sheet Column Title' question --- .../ExcelSheetColumnTitle.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/excel_sheet_column_title/ExcelSheetColumnTitle.java diff --git a/src/main/java/excel_sheet_column_title/ExcelSheetColumnTitle.java b/src/main/java/excel_sheet_column_title/ExcelSheetColumnTitle.java new file mode 100644 index 0000000..a622509 --- /dev/null +++ b/src/main/java/excel_sheet_column_title/ExcelSheetColumnTitle.java @@ -0,0 +1,22 @@ +package excel_sheet_column_title; + +public class ExcelSheetColumnTitle { + + public class Solution { + public String convertToTitle(int n) { + StringBuilder builder = new StringBuilder(); + while (n != 0) { + n--; + char c = (char) (n % 26 + 'A'); + builder.append(c); + n /= 26; + } + return builder.reverse().toString(); + } + } + + public static class UnitTest { + + } +} + From 7f898bae0b3c27a29dac57fe784e334c0e697b38 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 28 Dec 2014 16:47:26 +0800 Subject: [PATCH 068/456] Solve the 'Excel Sheet Column Number' question --- .../ExcelSheetColumnNumber.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/main/java/excel_sheet_column_number/ExcelSheetColumnNumber.java diff --git a/src/main/java/excel_sheet_column_number/ExcelSheetColumnNumber.java b/src/main/java/excel_sheet_column_number/ExcelSheetColumnNumber.java new file mode 100644 index 0000000..d606d2e --- /dev/null +++ b/src/main/java/excel_sheet_column_number/ExcelSheetColumnNumber.java @@ -0,0 +1,20 @@ +package excel_sheet_column_number; + +public class ExcelSheetColumnNumber { + + public class Solution { + public int titleToNumber(String s) { + int n = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + n = n * 26 + c - 'A' + 1; + } + return n; + } + } + + public static class UnitTest { + + } +} + From c595c92e3dc58269c2b875ac5d5c980c15981117 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 28 Dec 2014 17:36:08 +0800 Subject: [PATCH 069/456] Return 0 when overflow --- .../java/reverse_integer/ReverseInteger.java | 27 +++++++------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/src/main/java/reverse_integer/ReverseInteger.java b/src/main/java/reverse_integer/ReverseInteger.java index 19cd66f..99a7bb3 100644 --- a/src/main/java/reverse_integer/ReverseInteger.java +++ b/src/main/java/reverse_integer/ReverseInteger.java @@ -4,31 +4,22 @@ public class ReverseInteger { public class Solution { public int reverse(int x) { - // Minor revision for this question: if overflow, return - // Integer.MIN_VALUE or Integer.MAX_VALUE if (x == Integer.MIN_VALUE) { - return x; + return 0; } - boolean overflow = false; boolean negative = x < 0; - x = Math.abs(x); + if (negative) { + x = -x; + } int y = 0; while (x != 0) { - if (Integer.MAX_VALUE / 10 < y) { - overflow = true; - break; + int mod = x % 10; + if (y > (Integer.MAX_VALUE - mod) / 10) { + // y * 10 + mod > Integer.MAX_VALUE + return 0; } - y *= 10; - int digit = x % 10; + y = y * 10 + mod; x /= 10; - if (Integer.MAX_VALUE - digit < y) { - overflow = true; - break; - } - y += digit; - } - if (overflow) { - return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE; } return negative ? -y : y; } From c0932b3f38b8cd54a684eb857abadd72e2b39023 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Tue, 30 Dec 2014 23:07:25 +0800 Subject: [PATCH 070/456] Solve the 'Factorial Trailing Zeroes' question --- .../FactorialTrailingZeroes.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/main/java/factorial_trailing_zeroes/FactorialTrailingZeroes.java diff --git a/src/main/java/factorial_trailing_zeroes/FactorialTrailingZeroes.java b/src/main/java/factorial_trailing_zeroes/FactorialTrailingZeroes.java new file mode 100644 index 0000000..c785493 --- /dev/null +++ b/src/main/java/factorial_trailing_zeroes/FactorialTrailingZeroes.java @@ -0,0 +1,21 @@ +package factorial_trailing_zeroes; + +public class FactorialTrailingZeroes { + + public class Solution { + public int trailingZeroes(int n) { + int times = 5; + int zeroes = 0; + while (n >= times) { + zeroes += n / times; + times *= 5; + } + return zeroes; + } + } + + public static class UnitTest { + + } +} + From d7f647cd92c5b7d5d2a7c7661d4bacaa15a8dfbe Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 1 Jan 2015 14:51:40 +0800 Subject: [PATCH 071/456] Solve the 'Binary Search Tree Iterator' question --- .../BinarySearchTreeIterator.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/main/java/binary_search_tree_iterator/BinarySearchTreeIterator.java diff --git a/src/main/java/binary_search_tree_iterator/BinarySearchTreeIterator.java b/src/main/java/binary_search_tree_iterator/BinarySearchTreeIterator.java new file mode 100644 index 0000000..97fee95 --- /dev/null +++ b/src/main/java/binary_search_tree_iterator/BinarySearchTreeIterator.java @@ -0,0 +1,60 @@ +package binary_search_tree_iterator; + +import java.util.ArrayDeque; + +import common.TreeNode; + +public class BinarySearchTreeIterator { + + public class BSTIterator { + + private ArrayDeque stack = new ArrayDeque(); + + private TreeNode current = null; + + public BSTIterator(TreeNode root) { + pushNode(root); + } + + private void pushNode(TreeNode node) { + while (node != null) { + stack.push(node); + node = node.left; + } + } + + /** + * @return whether we have a next smallest number + */ + public boolean hasNext() { + if (current == null) { + if (stack.isEmpty()) { + return false; + } else { + current = stack.pop(); + pushNode(current.right); + } + } + return true; + } + + /** + * @return the next smallest number + */ + public int next() { + if (hasNext()) { + int val = current.val; + current = null; + return val; + } else { + // Follow the contract of java.util.Iterator + throw new java.util.NoSuchElementException(); + } + } + } + + public static class UnitTest { + + } +} + From 75825d094abd9a4c6abff7978f64b29a4c4aa571 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sat, 3 Jan 2015 22:18:20 +0800 Subject: [PATCH 072/456] Solve the 'Insert Interval' question --- src/main/java/common/Interval.java | 24 +++++++++- .../java/insert_interval/InsertInterval.java | 47 +++++++++++-------- 2 files changed, 51 insertions(+), 20 deletions(-) diff --git a/src/main/java/common/Interval.java b/src/main/java/common/Interval.java index 1341f7d..3fe3ee5 100644 --- a/src/main/java/common/Interval.java +++ b/src/main/java/common/Interval.java @@ -1,6 +1,6 @@ package common; -public class Interval { +public final class Interval { public int start; public int end; @@ -13,4 +13,26 @@ public Interval(int s, int e) { start = s; end = e; } + + @Override + public String toString() { + return "[" + start + ", " + end + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Interval that = (Interval) o; + return start == that.start && end == that.end; + } + + @Override + public int hashCode() { + return 31 * start + end; + } } diff --git a/src/main/java/insert_interval/InsertInterval.java b/src/main/java/insert_interval/InsertInterval.java index f22a15e..8c616e7 100644 --- a/src/main/java/insert_interval/InsertInterval.java +++ b/src/main/java/insert_interval/InsertInterval.java @@ -1,38 +1,47 @@ package insert_interval; +import common.Interval; +import org.junit.Test; + import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; -import common.Interval; +import static org.junit.Assert.assertEquals; public class InsertInterval { - /** - * "Output Limit Exceeded". Is there a perfect Java solution to pass the - * tests? - */ public class Solution { - public ArrayList insert(ArrayList intervals, - Interval newInterval) { - for (int i = 0; i < intervals.size(); i++) { - Interval interval = intervals.get(i); - if (newInterval.end > interval.start) { - intervals.add(i, newInterval); - return intervals; - } - if (newInterval.start >= interval.end) { - newInterval.start = Math.min(newInterval.start, - interval.start); + public List insert(List intervals, Interval newInterval) { + List newIntervals = new ArrayList(); + for (Interval interval : intervals) { + if (newInterval == null || interval.end < newInterval.start) { + newIntervals.add(interval); + } else if (interval.start > newInterval.end) { + newIntervals.add(newInterval); + newIntervals.add(interval); + newInterval = null; + } else { + newInterval.start = Math.min(newInterval.start, interval.start); newInterval.end = Math.max(newInterval.end, interval.end); - intervals.remove(i); } } - intervals.add(newInterval); - return intervals; + if (newInterval != null) { + newIntervals.add(newInterval); + } + return newIntervals; } } public static class UnitTest { + @Test + public void testInsert() { + Solution s = new InsertInterval().new Solution(); + assertEquals( + Arrays.asList(new Interval(0, 0), new Interval(1, 5)), + s.insert(Arrays.asList(new Interval(1, 5)), new Interval(0, 0))); + } } } From 12f4d75a46625486879b4ca4801ac887c7ac7289 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sat, 3 Jan 2015 22:39:39 +0800 Subject: [PATCH 073/456] Use kth to solve 'Median of Two Sorted Arrays' --- .../MedianofTwoSortedArrays.java | 58 +++++++++++-------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java b/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java index a601e3a..e473616 100644 --- a/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java +++ b/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java @@ -1,45 +1,53 @@ package median_of_two_sorted_arrays; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + public class MedianofTwoSortedArrays { public class Solution { - private double findMedianSortedArrays(int A[], int left, int right, - int B[]) { - if (left > right) { - return findMedianSortedArrays(B, - Math.max(0, (A.length + B.length) / 2 - A.length), - Math.min(B.length - 1, (A.length + B.length) / 2), A); - } - int i = (left + right) / 2; - int j = (A.length + B.length) / 2 - i - 1; - if (j >= 0 && A[i] < B[j]) { - return findMedianSortedArrays(A, i + 1, right, B); + private int findKth(int A[], int m, int B[], int n, int k) { + if (m == 0) { + return B[k - 1]; } - if (j < B.length - 1 && A[i] > B[j + 1]) { - return findMedianSortedArrays(A, left, i - 1, B); + if (n == 0) { + return A[k - 1]; } - - if ((A.length + B.length) % 2 == 0) { - if (i > 0) { - int pre = j < 0 ? A[i - 1] : Math.max(A[i - 1], B[j]); - return (A[i] + pre) / 2.0; - } else { - return (A[i] + B[j]) / 2.0; - } + if (m + n == k) { + return Math.max(A[m - 1], B[n - 1]); + } + if (m > n) { + return findKth(B, n, A, m, k); + } + int x = Math.min(m, k / 2 + 1); + int y = k + 1 - x; + if (A[x - 1] < B[y - 1]) { + return findKth(A, m, B, y - 1, k); + } else if (A[x - 1] > B[y - 1]) { + return findKth(A, x - 1, B, n, k); } else { - return A[i]; + return A[x - 1]; } } public double findMedianSortedArrays(int A[], int B[]) { - return findMedianSortedArrays(A, - Math.max(0, (A.length + B.length) / 2 - B.length), - Math.min(A.length - 1, (A.length + B.length) / 2), B); + int n = A.length + B.length; + if (n % 2 == 1) { + return findKth(A, A.length, B, B.length, n / 2 + 1); + } + return (findKth(A, A.length, B, B.length, n / 2) + + findKth(A, A.length, B, B.length, n / 2 + 1)) / 2.0; } } public static class UnitTest { + @Test + public void testFindMedianSortedArrays() { + Solution s = new MedianofTwoSortedArrays().new Solution(); + assertEquals(2.5, s.findMedianSortedArrays(new int[]{3, 4}, new int[]{1, 2}), 1E-6); + } } } From 000d0dafcb90ab66f31ac8f545479abb4ba4a758 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sun, 4 Jan 2015 23:18:04 +0800 Subject: [PATCH 074/456] Use indexOf --- .../implement_strstr/ImplementstrStr.java | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/src/main/java/implement_strstr/ImplementstrStr.java b/src/main/java/implement_strstr/ImplementstrStr.java index 7726842..abef036 100644 --- a/src/main/java/implement_strstr/ImplementstrStr.java +++ b/src/main/java/implement_strstr/ImplementstrStr.java @@ -3,23 +3,8 @@ public class ImplementstrStr { public class Solution { - public String strStr(String haystack, String needle) { - if (haystack == null || needle == null) { - return null; - } - for (int i = 0; i <= haystack.length() - needle.length(); i++) { - boolean find = true; - for (int j = 0; j < needle.length(); j++) { - if (haystack.charAt(i + j) != needle.charAt(j)) { - find = false; - break; - } - } - if (find) { - return haystack.substring(i); - } - } - return null; + public int strStr(String haystack, String needle) { + return haystack.indexOf(needle); } } From 51c95c4138b115500fee4ee6901459bc49462b65 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sat, 17 Jan 2015 22:32:08 +0800 Subject: [PATCH 075/456] Solve the 'Largest Number' question --- .../java/largest_number/LargestNumber.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/largest_number/LargestNumber.java diff --git a/src/main/java/largest_number/LargestNumber.java b/src/main/java/largest_number/LargestNumber.java new file mode 100644 index 0000000..34eb1b0 --- /dev/null +++ b/src/main/java/largest_number/LargestNumber.java @@ -0,0 +1,53 @@ +package largest_number; + +import java.util.Arrays; +import java.util.Comparator; + +public class LargestNumber { + + public class Solution { + + private int skipLendingZeros(String s) { + int i = 0; + for (; i < s.length(); i++) { + if (s.charAt(i) != '0') { + return i; + } + } + return i; + } + + public String largestNumber(int[] num) { + String[] nums = new String[num.length]; + for (int i = 0; i < nums.length; i++) { + nums[i] = Integer.toString(num[i]); + } + Arrays.sort(nums, new Comparator() { + @Override + public int compare(String s1, String s2) { + return -(s1 + s2).compareTo(s2 + s1); + } + }); + StringBuilder builder = new StringBuilder(); + boolean skip = true; + for (String n : nums) { + if (skip) { + int start = skipLendingZeros(n); + if (start != n.length()) { + skip = false; + builder.append(n, start, n.length()); + } + } else { + builder.append(n); + } + } + String r = builder.toString(); + return r.isEmpty() ? "0" : r; + } + } + + public static class UnitTest { + + } +} + From 325dce4231cc1e79e909af3efa0bbd2467c9df4d Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sat, 17 Jan 2015 23:24:17 +0800 Subject: [PATCH 076/456] Solve the 'Dungeon Game' question --- src/main/java/dungeon_game/DungeonGame.java | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/dungeon_game/DungeonGame.java diff --git a/src/main/java/dungeon_game/DungeonGame.java b/src/main/java/dungeon_game/DungeonGame.java new file mode 100644 index 0000000..ed8ae2b --- /dev/null +++ b/src/main/java/dungeon_game/DungeonGame.java @@ -0,0 +1,32 @@ +package dungeon_game; + +public class DungeonGame { + + public class Solution { + public int calculateMinimumHP(int[][] dungeon) { + int m = dungeon.length; + int n = dungeon[0].length; + int[][] dp = new int[m][n]; + dp[m - 1][n - 1] = 1; + for (int i = m - 2; i >= 0; i--) { + dp[i][n - 1] = Math.max(1, dp[i + 1][n - 1] - dungeon[i + 1][n - 1]); + } + for (int i = n - 2; i >= 0; i--) { + dp[m - 1][i] = Math.max(1, dp[m - 1][i + 1] - dungeon[m - 1][i + 1]); + } + for (int i = m - 2; i >= 0; i--) { + for (int j = n - 2; j >= 0; j--) { + dp[i][j] = Math.max(1, + Math.min(dp[i][j + 1] - dungeon[i][j + 1], dp[i + 1][j] - dungeon[i + 1][j]) + ); + } + } + return Math.max(1, dp[0][0] - dungeon[0][0]); + } + } + + public static class UnitTest { + + } +} + From a24bd81a1af72930fe0d4e8470e59959ec0d263e Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 5 Feb 2015 22:51:10 +0800 Subject: [PATCH 077/456] Scan in the reverse direction --- .../length_of_last_word/LengthofLastWord.java | 26 +++++++------------ 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/src/main/java/length_of_last_word/LengthofLastWord.java b/src/main/java/length_of_last_word/LengthofLastWord.java index 9e2fcd8..5d51395 100644 --- a/src/main/java/length_of_last_word/LengthofLastWord.java +++ b/src/main/java/length_of_last_word/LengthofLastWord.java @@ -4,23 +4,17 @@ public class LengthofLastWord { public class Solution { public int lengthOfLastWord(String s) { + int i = s.length() - 1; + while (i >= 0 && s.charAt(i) == ' ') { + i--; + } + if (i < 0) { + return 0; + } int len = 0; - int i = 0; - while (true) { - while (i < s.length() && s.charAt(i) == ' ') { - i++; - } - if (i == s.length()) { - break; - } - int start = i; - while (i < s.length() && s.charAt(i) != ' ') { - i++; - } - len = i - start; - if (i == s.length()) { - break; - } + while (i >= 0 && s.charAt(i) != ' ') { + len++; + i--; } return len; } From 06562e6ed3860e166fb588a6379a14948de7f444 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Sat, 11 Apr 2015 20:03:49 +0800 Subject: [PATCH 078/456] Solve the 'Number of 1 Bits' question --- .../java/number_of_1_bits/Numberof1Bits.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/main/java/number_of_1_bits/Numberof1Bits.java diff --git a/src/main/java/number_of_1_bits/Numberof1Bits.java b/src/main/java/number_of_1_bits/Numberof1Bits.java new file mode 100644 index 0000000..7a430d4 --- /dev/null +++ b/src/main/java/number_of_1_bits/Numberof1Bits.java @@ -0,0 +1,16 @@ +package number_of_1_bits; + +public class Numberof1Bits { + + public class Solution { + public int hammingWeight(int n) { + int count = 0; + while (n != 0) { + count++; + n &= (n - 1); + } + return count; + } + } +} + From bd9116923c286a01ace30dab70232aaf16951dd5 Mon Sep 17 00:00:00 2001 From: zsxwing Date: Thu, 26 Feb 2015 19:09:04 -0800 Subject: [PATCH 079/456] Multiple commits --- .../BestTimetoBuyandSellStockIV.java | 35 ++++++++++ .../BinaryTreeRightSideView.java | 34 +++++++++ .../BitwiseANDofNumbersRange.java | 19 +++++ src/main/java/count_primes/CountPrimes.java | 35 ++++++++++ .../java/course_schedule/CourseSchedule.java | 48 +++++++++++++ src/main/java/house_robber/HouseRobber.java | 25 +++++++ .../java/implement_trie/ImplementTrie.java | 69 +++++++++++++++++++ .../isomorphic_strings/IsomorphicStrings.java | 33 +++++++++ .../RepeatedDNASequences.java | 27 ++++++++ src/main/java/reverse_bits/ReverseBits.java | 20 ++++++ .../ReverseLinkedList.java | 21 ++++++ src/main/java/rotate_array/RotateArray.java | 24 +++++++ 12 files changed, 390 insertions(+) create mode 100644 src/main/java/best_time_to_buy_and_sell_stock_iv/BestTimetoBuyandSellStockIV.java create mode 100644 src/main/java/binary_tree_right_side_view/BinaryTreeRightSideView.java create mode 100644 src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java create mode 100644 src/main/java/count_primes/CountPrimes.java create mode 100644 src/main/java/course_schedule/CourseSchedule.java create mode 100644 src/main/java/house_robber/HouseRobber.java create mode 100644 src/main/java/implement_trie/ImplementTrie.java create mode 100644 src/main/java/isomorphic_strings/IsomorphicStrings.java create mode 100644 src/main/java/repeated_dna_sequences/RepeatedDNASequences.java create mode 100644 src/main/java/reverse_bits/ReverseBits.java create mode 100644 src/main/java/reverse_linked_list/ReverseLinkedList.java create mode 100644 src/main/java/rotate_array/RotateArray.java diff --git a/src/main/java/best_time_to_buy_and_sell_stock_iv/BestTimetoBuyandSellStockIV.java b/src/main/java/best_time_to_buy_and_sell_stock_iv/BestTimetoBuyandSellStockIV.java new file mode 100644 index 0000000..50403cb --- /dev/null +++ b/src/main/java/best_time_to_buy_and_sell_stock_iv/BestTimetoBuyandSellStockIV.java @@ -0,0 +1,35 @@ +package best_time_to_buy_and_sell_stock_iv; + +public class BestTimetoBuyandSellStockIV { + + public class Solution { + private int maxProfitUnlimited(int[] prices) { + int profit = 0; + for (int i = 1; i < prices.length; i++) { + profit += Math.max(0, prices[i] - prices[i - 1]); + } + return profit; + } + + public int maxProfit(int k, int[] prices) { + int n = prices.length; + if (n <= 1) { + return 0; + } + if (k >= n) { + return maxProfitUnlimited(prices); + } + int[] global = new int[k + 1]; + int[] local = new int[k + 1]; + for (int i = 1; i < n; i++) { + int diff = prices[i] - prices[i - 1]; + for (int j = k; j >= 1; j--) { + local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff); + global[j] = Math.max(global[j], local[j]); + } + } + return global[k]; + } + } +} + diff --git a/src/main/java/binary_tree_right_side_view/BinaryTreeRightSideView.java b/src/main/java/binary_tree_right_side_view/BinaryTreeRightSideView.java new file mode 100644 index 0000000..d01c8b2 --- /dev/null +++ b/src/main/java/binary_tree_right_side_view/BinaryTreeRightSideView.java @@ -0,0 +1,34 @@ +package binary_tree_right_side_view; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.List; + +public class BinaryTreeRightSideView { + + public class Solution { + public List rightSideView(TreeNode root) { + List result = new ArrayList(); + if (root != null) { + List level = new ArrayList(); + level.add(root); + while (!level.isEmpty()) { + result.add(level.get(level.size() - 1).val); + List nextLevel = new ArrayList(); + for (TreeNode node : level) { + if (node.left != null) { + nextLevel.add(node.left); + } + if (node.right != null) { + nextLevel.add(node.right); + } + } + level = nextLevel; + } + } + return result; + } + } +} + diff --git a/src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java b/src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java new file mode 100644 index 0000000..831ad07 --- /dev/null +++ b/src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java @@ -0,0 +1,19 @@ +package bitwise_and_of_numbers_range; + +public class BitwiseANDofNumbersRange { + + public class Solution { + public int rangeBitwiseAnd(int m, int n) { + int r = 0; + for (int i = 0; i < 32 && n != 0; i++) { + if ((m & 1) != 0 && n == m) { + r |= (1 << i); + } + n >>>= 1; + m >>>= 1; + } + return r; + } + } +} + diff --git a/src/main/java/count_primes/CountPrimes.java b/src/main/java/count_primes/CountPrimes.java new file mode 100644 index 0000000..dd10573 --- /dev/null +++ b/src/main/java/count_primes/CountPrimes.java @@ -0,0 +1,35 @@ +package count_primes; + +public class CountPrimes { + + public class Solution { + public int countPrimes(int n) { + if (n < 3) { + return 0; + } + boolean[] a = new boolean[n]; + a[0] = true; + a[1] = true; + int i = 2; + while (i * i < n) { + if (!a[i]) { + int j = i * i; + while (j < n) { + a[j] = true; + j += i; + } + } + i++; + } + int count = 0; + for (boolean _a : a) { + if (!_a) { + count++; + } + } + return count; + } + } + +} + diff --git a/src/main/java/course_schedule/CourseSchedule.java b/src/main/java/course_schedule/CourseSchedule.java new file mode 100644 index 0000000..537e809 --- /dev/null +++ b/src/main/java/course_schedule/CourseSchedule.java @@ -0,0 +1,48 @@ +package course_schedule; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CourseSchedule { + + public class Solution { + public boolean canFinish(int numCourses, int[][] prerequisites) { + Map> outNodes = new HashMap>(); + int[] inDegree = new int[numCourses]; + Set courses = new HashSet(numCourses); + for (int i = 0; i < numCourses; i++) { + courses.add(i); + outNodes.put(i, new ArrayList()); + } + for (int[] edge : prerequisites) { + int from = edge[1]; + int to = edge[0]; + inDegree[to]++; + List nodes = outNodes.get(from); + nodes.add(to); + } + while (!courses.isEmpty()) { + List toRemoved = new ArrayList(); + for (int course : courses) { + if (inDegree[course] == 0) { + toRemoved.add(course); + for (int node : outNodes.get(course)) { + inDegree[node]--; + } + } + } + if (toRemoved.isEmpty()) { + return false; + } + courses.removeAll(toRemoved); + } + return true; + } + } + +} + diff --git a/src/main/java/house_robber/HouseRobber.java b/src/main/java/house_robber/HouseRobber.java new file mode 100644 index 0000000..00d62ad --- /dev/null +++ b/src/main/java/house_robber/HouseRobber.java @@ -0,0 +1,25 @@ +package house_robber; + +public class HouseRobber { + + public class Solution { + public int rob(int[] nums) { + if (nums.length == 0) { + return 0; + } + if (nums.length < 2) { + return nums[0]; + } + int f1 = nums[0]; + int f2 = Math.max(nums[0], nums[1]); + for (int i = 2; i < nums.length; i++) { + // f(i) = max { f(i - 2) + nums[i], f(i - 1) } + int f = Math.max(f1 + nums[i], f2); + f1 = f2; + f2 = f; + } + return f2; + } + } +} + diff --git a/src/main/java/implement_trie/ImplementTrie.java b/src/main/java/implement_trie/ImplementTrie.java new file mode 100644 index 0000000..a19d30f --- /dev/null +++ b/src/main/java/implement_trie/ImplementTrie.java @@ -0,0 +1,69 @@ +package implement_trie; + +public class ImplementTrie { + + class TrieNode { + private TrieNode[] children = new TrieNode[26]; + + private boolean end = false; + + private TrieNode getChild(char c) { + return children[c - 'a']; + } + + private TrieNode getOrCreateChild(char c) { + if (children[c - 'a'] == null) { + children[c - 'a'] = new TrieNode(); + } + return children[c - 'a']; + } + + public void insert(int start, String word) { + if (start == word.length()) { + end = true; + } else { + TrieNode child = getOrCreateChild(word.charAt(start)); + child.insert(start + 1, word); + } + } + + public boolean search(int start, String word, boolean prefixSearch) { + if (start == word.length()) { + return end || prefixSearch; + } + TrieNode child = getChild(word.charAt(start)); + if (child != null) { + return child.search(start + 1, word, prefixSearch); + } + return false; + } + } + + public class Trie { + private TrieNode root = new TrieNode(); + + /** + * Inserts a word into the trie. + */ + public void insert(String word) { + root.insert(0, word); + } + + /** + * Returns if the word is in the trie. + */ + public boolean search(String word) { + return root.search(0, word, false); + } + + /** + * Returns if there is any word in the trie + * that starts with the given prefix. + */ + public boolean startsWith(String prefix) { + return root.search(0, prefix, true); + } + } + +} + diff --git a/src/main/java/isomorphic_strings/IsomorphicStrings.java b/src/main/java/isomorphic_strings/IsomorphicStrings.java new file mode 100644 index 0000000..3dd593a --- /dev/null +++ b/src/main/java/isomorphic_strings/IsomorphicStrings.java @@ -0,0 +1,33 @@ +package isomorphic_strings; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class IsomorphicStrings { + + public class Solution { + public boolean isIsomorphic(String s, String t) { + Map mapping = new HashMap(); + Set mapped = new HashSet(); + for (int i = 0; i < s.length(); i++) { + char c1 = s.charAt(i); + char c2 = t.charAt(i); + if (mapping.containsKey(c1)) { + if (mapping.get(c1) != c2) { + return false; + } + } else { + if (mapped.contains(c2)) { + return false; + } + mapped.add(c2); + mapping.put(c1, c2); + } + } + return true; + } + } +} + diff --git a/src/main/java/repeated_dna_sequences/RepeatedDNASequences.java b/src/main/java/repeated_dna_sequences/RepeatedDNASequences.java new file mode 100644 index 0000000..f387212 --- /dev/null +++ b/src/main/java/repeated_dna_sequences/RepeatedDNASequences.java @@ -0,0 +1,27 @@ +package repeated_dna_sequences; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class RepeatedDNASequences { + + public class Solution { + public List findRepeatedDnaSequences(String s) { + Set sequences = new HashSet(); + Set result = new HashSet(); + for (int i = 0; i + 10 <= s.length(); i++) { + String substring = s.substring(i, i + 10); + if (sequences.contains(substring)) { + result.add(substring); + } else { + sequences.add(substring); + } + } + System.gc(); + return new ArrayList(result); + } + } +} + diff --git a/src/main/java/reverse_bits/ReverseBits.java b/src/main/java/reverse_bits/ReverseBits.java new file mode 100644 index 0000000..89d4510 --- /dev/null +++ b/src/main/java/reverse_bits/ReverseBits.java @@ -0,0 +1,20 @@ +package reverse_bits; + +public class ReverseBits { + + public class Solution { + + public int reverseBits(int n) { + int reversed = 0; + int i; + for (i = 32; i > 0 && n != 0; i--) { + reversed = (reversed << 1) + (n & 1); + n >>= 1; + } + reversed <<= i; + return reversed; + } + } + +} + diff --git a/src/main/java/reverse_linked_list/ReverseLinkedList.java b/src/main/java/reverse_linked_list/ReverseLinkedList.java new file mode 100644 index 0000000..9e9c063 --- /dev/null +++ b/src/main/java/reverse_linked_list/ReverseLinkedList.java @@ -0,0 +1,21 @@ +package reverse_linked_list; + +import common.ListNode; + +public class ReverseLinkedList { + + public class Solution { + public ListNode reverseList(ListNode head) { + ListNode reversed = null; + ListNode p = head; + while (p != null) { + ListNode temp = p.next; + p.next = reversed; + reversed = p; + p = temp; + } + return reversed; + } + } +} + diff --git a/src/main/java/rotate_array/RotateArray.java b/src/main/java/rotate_array/RotateArray.java new file mode 100644 index 0000000..d1aad28 --- /dev/null +++ b/src/main/java/rotate_array/RotateArray.java @@ -0,0 +1,24 @@ +package rotate_array; + +public class RotateArray { + + public class Solution { + private void reverse(int[] nums, int begin, int end) { + while (begin < end) { + int temp = nums[begin]; + nums[begin] = nums[end]; + nums[end] = temp; + begin++; + end--; + } + } + + public void rotate(int[] nums, int k) { + k = k % nums.length; + reverse(nums, 0, nums.length - 1); + reverse(nums, 0, k - 1); + reverse(nums, k, nums.length - 1); + } + } +} + From b7e88c8bd14e647cd57d3acd9ecb9903cd295c74 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 4 Jun 2017 22:23:02 -0700 Subject: [PATCH 080/456] max points on a line --- .../MaxPointsonaLine.java | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/src/main/java/max_points_on_a_line/MaxPointsonaLine.java b/src/main/java/max_points_on_a_line/MaxPointsonaLine.java index 58c9e8e..a863fde 100644 --- a/src/main/java/max_points_on_a_line/MaxPointsonaLine.java +++ b/src/main/java/max_points_on_a_line/MaxPointsonaLine.java @@ -2,41 +2,41 @@ import java.awt.Point; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; + public class MaxPointsonaLine { public class Solution { - private boolean isOnLine(Point p1, Point p2, Point p3) { - return (p1.y - p2.y) * (p2.x - p3.x) == (p1.x - p2.x) - * (p2.y - p3.y); - } - public int maxPoints(Point[] points) { - List lines = new ArrayList(); - for (int i = 0; i < points.length; i++) { - for (int j = i + 1; j < points.length; j++) { - if (points[i].x != points[j].x - || points[i].y != points[j].y) { - lines.add(new Point[] { points[i], points[j] }); + int res = 0; + Map m = new HashMap(); + for (int i = 0; i < points.length; ++i) { + m.clear(); + m.put((float) Integer.MIN_VALUE, 0); + int duplicate = 1; + for (int j = 0; j < points.length; ++j) { + if (j == i) continue; + if (points[i].x == points[j].x && points[i].y == points[j].y) { + ++duplicate; + continue; } - } - } - if (lines.isEmpty()) { - return points.length; - } - int max = 0; - for (Point[] line : lines) { - int count = 0; - for (Point point : points) { - if (isOnLine(line[0], line[1], point)) { - count++; + float slope = (points[i].x == points[j].x) ? (float) Integer.MAX_VALUE + : (float) (points[j].y - points[i].y) / (points[j].x - points[i].x); + if (m.containsKey(slope)) { + m.put(slope, m.get(slope) + 1); + } else { + m.put(slope, 1); } } - max = Math.max(max, count); + for (Map.Entry entry : m.entrySet()) { + res = Math.max(res, entry.getValue() + duplicate); + } } - return max; + return res; } } From 72532b1a1ff7c55e24bbcedbfbaa2c9d066c198a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 5 Jun 2017 01:11:19 -0700 Subject: [PATCH 081/456] palindrome permutation --- .../PalindromePermutation.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/palindrome_permutation/PalindromePermutation.java diff --git a/src/main/java/palindrome_permutation/PalindromePermutation.java b/src/main/java/palindrome_permutation/PalindromePermutation.java new file mode 100644 index 0000000..87d6e21 --- /dev/null +++ b/src/main/java/palindrome_permutation/PalindromePermutation.java @@ -0,0 +1,31 @@ +package palindrome_permutation; + +import java.util.HashMap; +import java.util.Map; + + +public class PalindromePermutation { + + public class Solution { + public boolean palindromePermutation(String s) { + Map m = new HashMap<>(); + int cnt = 0; + for (char a : s.toCharArray()) { + if(m.containsKey(a)) { + m.put(a, m.get(a)+1); + } else { + m.put(a, 1); + } + } + for (Map.Entry entry : m.entrySet()) { + if (entry.getValue() % 2 != 0) ++cnt; + } + return cnt == 0 || (s.length() % 2 == 1 && cnt == 1); + } + } + + public static class UnitTest { + + } + +} From 574e66f88210ed00ffb6a3ea4871dbb4b93fdf97 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 10 Jul 2017 09:47:42 -0700 Subject: [PATCH 082/456] palindrome Permutations II --- .../PalindromePermutationII.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/main/java/palindrome_permutation_ii/PalindromePermutationII.java diff --git a/src/main/java/palindrome_permutation_ii/PalindromePermutationII.java b/src/main/java/palindrome_permutation_ii/PalindromePermutationII.java new file mode 100644 index 0000000..42c48a8 --- /dev/null +++ b/src/main/java/palindrome_permutation_ii/PalindromePermutationII.java @@ -0,0 +1,58 @@ +package palindrome_permutation_ii; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PalindromePermutationII { + + public class Solution { + + public List generatePalindrome(String s) { + List res = new ArrayList<>(); + Map m = new HashMap<>(); + String t = "", mid = ""; + for (Character a : s.toCharArray()) { + if (m.containsKey(a)) { + m.put(a, m.get(a) + 1); + } else { + m.put(a, 1); + } + } + for (Map.Entry e : m.entrySet()) { + if (e.getValue() % 2 == 1) mid += e.getKey(); + t += new String(new char[e.getValue() / 2]).replace("\0", e.getKey().toString()); + if (mid.length() > 1) return res; + } + permute(t, 0, mid, res); + return res; + } + + public void permute(String t, int start, String mid, List res) { + if (start >= t.length()) { + res.add(t + mid + new StringBuffer(t).reverse()); + } + for (int i = start; i < t.length(); ++i){ + if (i != start && t.charAt(i) == t.charAt(start)) continue; + swap(t, i, start); //t.charAt(i), t.charAt(start)); + permute(t, start+1, mid, res); + swap(t, i, start); //.charAt(i), t.charAt(start)); + } + } + + private String swap(String s, int a, int b) { + char[] chars = s.toCharArray(); + char tmp = chars[a]; + chars[a] = chars[b]; + chars[b] = tmp; + return new String(chars); + } + + } + + public static class UnitTest { + + } + +} From 1cb297bd74ff99efa5545cacb09ba327f9e49b4e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 9 Sep 2017 02:01:46 -0700 Subject: [PATCH 083/456] add SumOfLeftLeaves --- .../sum_of_left_leaves/SumOfLeftLeaves.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/sum_of_left_leaves/SumOfLeftLeaves.java diff --git a/src/main/java/sum_of_left_leaves/SumOfLeftLeaves.java b/src/main/java/sum_of_left_leaves/SumOfLeftLeaves.java new file mode 100644 index 0000000..560d1c3 --- /dev/null +++ b/src/main/java/sum_of_left_leaves/SumOfLeftLeaves.java @@ -0,0 +1,30 @@ +package sum_of_left_leaves; + +/** + * Created by lxie on 9/8/17. + */ +public class SumOfLeftLeaves { + + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + + class Solution { + public int sumOfLeftLeaves(TreeNode root) { + if(root == null) return 0; + if(root.left != null && root.left.left == null && root.left.right == null){ + return root.left.val + sumOfLeftLeaves(root.right); + } + return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right); + + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + } + +} From 7f721adf774b971e59ce8e6856cfbaf604132d29 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 9 Sep 2017 02:36:26 -0700 Subject: [PATCH 084/456] add findLeavesOfBinaryTree --- .../FindLeavesOfBinaryTree.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java diff --git a/src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java b/src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java new file mode 100644 index 0000000..2040500 --- /dev/null +++ b/src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java @@ -0,0 +1,40 @@ +package find_leaves_of_binary_tree; + +import java.util.ArrayList; + +/** + * Created by lxie on 9/9/17. + */ +public class FindLeavesOfBinaryTree { + + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + + class Solution { + public ArrayList> findLeaves(TreeNode root){ + ArrayList> res = new ArrayList>(); + helper(root, res); + return res; + + } + + private int helper(TreeNode root, ArrayList> res) { + if(root == null) return -1; + int depth = 1 + Math.max(helper(root.left, res), helper(root.right, res)); + if (depth >= res.size()) res.add(new ArrayList<>()); + res.get(depth).add(root.val); + return depth; + } + + } + + public static void main(String[] args) { + System.out.println("this is for test"); + } + + +} From 7b94dd3426b8f10b0a2a0f3585da84bd2de3c720 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 10 Sep 2017 00:26:50 -0700 Subject: [PATCH 085/456] add longest_substring_k_repeating_chars --- .../LongestSubstringKRepeatingChars.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java diff --git a/src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java b/src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java new file mode 100644 index 0000000..3f426e3 --- /dev/null +++ b/src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java @@ -0,0 +1,41 @@ +package longest_substring_k_repeating_chars; + +import java.util.Arrays; + + +/** + * Created by lxie on 9/9/17. + */ +public class LongestSubstringKRepeatingChars { + + public static class Solution { + public int longestSubstring(String s, int k) { + int res = 0, i = 0, n = s.length(); + while (i + k <= n) { + int[] m = new int[26]; + Arrays.fill(m, 0); + int mask = 0, max_idx = i; + for (int j = i; j < n; ++j) { + int t = s.charAt(j) - 'a'; + ++m[t]; + if (m[t] < k) mask |= (1 << t); + else mask &= (~(1 << t)); + if (mask == 0) { // existing ones all >= k + res = Math.max(res, j - i + 1); + max_idx = j; + } + + } + i = max_idx + 1; + } + return res; + } + } + + + public static void main(String[] args) { + Solution sol = new Solution(); + System.out.println("result = " + sol.longestSubstring("a", 1)); + } + +} From ad4424434b729840af4d16344c88e906742f5a26 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 11 Sep 2017 02:06:59 -0700 Subject: [PATCH 086/456] add russian_doll_envelopes --- .../RussianDollEnvelopes.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/russian_doll_envelopes/RussianDollEnvelopes.java diff --git a/src/main/java/russian_doll_envelopes/RussianDollEnvelopes.java b/src/main/java/russian_doll_envelopes/RussianDollEnvelopes.java new file mode 100644 index 0000000..6b6da34 --- /dev/null +++ b/src/main/java/russian_doll_envelopes/RussianDollEnvelopes.java @@ -0,0 +1,43 @@ +package russian_doll_envelopes; + +import java.util.Arrays; +import java.util.Comparator; + +/** + * Created by lxie on 9/10/17. + */ +public class RussianDollEnvelopes { + + public class Solution { + public int maxEnvelopes(int[][] envelopes) { + int res = 0, n = envelopes.length; + int[] dp = new int[n]; + Arrays.fill(dp, 1); + Arrays.sort(envelopes, new Comparator(){ + public int compare(int[] arr1, int[] arr2){ + if(arr1[0] == arr2[0]) + return arr1[1] - arr2[1]; + else + return arr1[0] - arr2[0]; + } + }); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + res = Math.max(res, dp[i]); + } + return res; + + } + } + + + public static void main(String[] args) { + + } + + +} From 028acf3d7a14480e213d6fd1213776aae1028815 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 13 Sep 2017 22:14:38 -0700 Subject: [PATCH 087/456] add max_sum_sub_matrix --- .../max_sum_sub_matrix/MaxSumSubMatrix.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/max_sum_sub_matrix/MaxSumSubMatrix.java diff --git a/src/main/java/max_sum_sub_matrix/MaxSumSubMatrix.java b/src/main/java/max_sum_sub_matrix/MaxSumSubMatrix.java new file mode 100644 index 0000000..6d6f3dd --- /dev/null +++ b/src/main/java/max_sum_sub_matrix/MaxSumSubMatrix.java @@ -0,0 +1,53 @@ +package max_sum_sub_matrix; + +import com.google.common.collect.BoundType; +import com.google.common.collect.Multiset; +import com.google.common.collect.TreeMultiset; + +import java.util.Arrays; + +/** + * Created by lxie on 9/11/17. + */ +public class MaxSumSubMatrix { + + public static class Solution { + public int maxSumSubmatrix(int[][] matrix, int kval) { + if (matrix.length == 0 || matrix[0].length == 0) { + return 0; + } + int m = matrix.length, n = matrix[0].length, res = Integer.MIN_VALUE; + for (int i = 0; i < n; ++i) { + int[] sum = new int[m]; + Arrays.fill(sum, 0); + for (int j = i; j < n; ++j) { + for (int k = 0; k < m; ++k) { + sum[k] += matrix[k][j]; + } + int curSum = 0, curMax = Integer.MIN_VALUE; + TreeMultiset s = TreeMultiset.create(); + s.add(0); + for(int a : sum){ + curSum += a; + Multiset.Entry it = s.tailMultiset(curSum - kval, BoundType.CLOSED).firstEntry(); + if (it != null) curMax = Math.max(curMax, curSum - it.getElement()); + s.add(curSum); + } + res = Math.max(res, curMax); + } + } + return res; + } + + + } + + + public static void main(String[] args) { + Solution sol = new Solution(); + int[][] input = {{1,0,1}, {0, -2, 3}}; + int ret = sol.maxSumSubmatrix(input, 2); + System.out.println("result = " + ret); + } + +} From 506692d8b577d2f199858b9f4fc39bb3f6fa0d57 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 14 Sep 2017 10:45:42 -0700 Subject: [PATCH 088/456] add combination_sum_IV --- .../combination_sum_IV/CombinationSumIV.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/combination_sum_IV/CombinationSumIV.java diff --git a/src/main/java/combination_sum_IV/CombinationSumIV.java b/src/main/java/combination_sum_IV/CombinationSumIV.java new file mode 100644 index 0000000..f976d33 --- /dev/null +++ b/src/main/java/combination_sum_IV/CombinationSumIV.java @@ -0,0 +1,29 @@ +package combination_sum_IV; + +import java.util.Arrays; + +/** + * Created by lxie on 9/14/17. + */ +public class CombinationSumIV { + + class Solution { + public int combinationSum4(int[] nums, int target) { + int[] dp = new int[target+1]; + dp[0] = 1; + Arrays.sort(nums); + for (int i = 1; i <= target; i++) { + for(int a : nums){ + if (i < a) break; + dp[i] += dp[i-a]; + } + } + return dp[target]; + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + } + +} From 3c0f073137a66e818a7414a414e10b3bee206edf Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 14 Sep 2017 22:58:31 -0700 Subject: [PATCH 089/456] add frog_jump --- src/main/java/frog_jump/FrogJump.java | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/frog_jump/FrogJump.java diff --git a/src/main/java/frog_jump/FrogJump.java b/src/main/java/frog_jump/FrogJump.java new file mode 100644 index 0000000..525bfcb --- /dev/null +++ b/src/main/java/frog_jump/FrogJump.java @@ -0,0 +1,44 @@ +package frog_jump; + +import java.util.HashMap; + +/** + * Created by lxie on 9/14/17. + */ +public class FrogJump { + + class Solution { + + public boolean canCross(int[] stones) { + HashMap m = new HashMap<>(); + return helper(stones, 0, 0, m); + } + + public boolean helper(int[] stones, int pos, int jump, HashMap m) { + int n = stones.length, key = pos | jump << 11; // 11 means a big left shift + if (pos >= n - 1) return true; + if (m.containsKey(key)) return m.get(key); + for (int i = pos + 1; i < n; ++i) { + int dist = stones[i] - stones[pos]; + if (dist < jump - 1) continue; + if (dist > jump + 1) { + m.put(key, false); + return false; + } + if (helper(stones, i, dist, m)) { + m.put(key, true); + return true; + } + } + m.put(key, false); + return false; + } + } + + + public static void main(String[] args) { + System.out.println("this is for test"); + } + + +} From 95af3d0caeed202c1427744a544c11462920df4d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 14 Sep 2017 22:58:31 -0700 Subject: [PATCH 090/456] add frog_jump --- src/main/java/frog_jump/FrogJump.java | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/main/java/frog_jump/FrogJump.java b/src/main/java/frog_jump/FrogJump.java index 525bfcb..90a7598 100644 --- a/src/main/java/frog_jump/FrogJump.java +++ b/src/main/java/frog_jump/FrogJump.java @@ -1,6 +1,7 @@ package frog_jump; import java.util.HashMap; +import java.util.HashSet; /** * Created by lxie on 9/14/17. @@ -33,6 +34,33 @@ public boolean helper(int[] stones, int pos, int jump, HashMap m.put(key, false); return false; } + + public boolean canCrossDP(int[] stones) { + HashMap> dp = + new HashMap>(stones.length); + for (int i = 0; i < stones.length; i++) { + dp.put(stones[i], new HashSet() ); + } + dp.get(0).add(0); + + for (int i = 0; i < stones.length - 1; ++i) { + int stone = stones[i]; + for (int k : dp.get(stone)) { + // k - 1 + if (k - 1 > 0 && dp.containsKey(stone + k - 1)) + dp.get(stone + k - 1).add(k - 1); + // k + if (dp.containsKey(stone + k)) + dp.get(stone + k).add(k); + // k + 1 + if (dp.containsKey(stone + k + 1)) + dp.get(stone + k + 1).add(k + 1); + } + } + + return !dp.get(stones[stones.length - 1]).isEmpty(); + } + } From ace4c4d7812369441435114abdaa21b798b3f430 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 16 Sep 2017 17:13:05 -0700 Subject: [PATCH 091/456] add countBattleShips --- .../BattleShipsInBoard.java | 45 +++++++++++++++++++ src/main/java/frog_jump/FrogJump.java | 2 +- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/main/java/battleships_in_board/BattleShipsInBoard.java diff --git a/src/main/java/battleships_in_board/BattleShipsInBoard.java b/src/main/java/battleships_in_board/BattleShipsInBoard.java new file mode 100644 index 0000000..0227625 --- /dev/null +++ b/src/main/java/battleships_in_board/BattleShipsInBoard.java @@ -0,0 +1,45 @@ +package battleships_in_board; + +/** + * Created by lxie on 9/16/17. + */ +public class BattleShipsInBoard { + + class Solution { + public int countBattleships(char[][] board) { + if (board.length == 0 || board[0].length == 0) return 0; + int m = board.length, n = board[0].length, res = 0; + boolean[][] visited = new boolean[m][n]; // default is all false + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (board[i][j] == 'X' && !visited[i][j]) { + int[] lineOrCol = {0, 0}; + dfs(board, visited, lineOrCol, i, j); + if (lineOrCol[0] == i || lineOrCol[1] == j) ++res; + } + } + } + return res; + } + void dfs(char[][] board, boolean[][] visited, int[] linecol, int i, int j) { + int m = board.length, n = board[0].length; + if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || board[i][j] == '.') return; + linecol[0] |= i; linecol[1] |= j; + visited[i][j] = true; + dfs(board, visited, linecol, i - 1, j); + dfs(board, visited, linecol, i + 1, j); + dfs(board, visited, linecol, i, j - 1); + dfs(board, visited, linecol, i, j + 1); + } + + } + + + public static void main(String[] args) { + System.out.println("this is for test"); + } + + + +} diff --git a/src/main/java/frog_jump/FrogJump.java b/src/main/java/frog_jump/FrogJump.java index 90a7598..a4fd362 100644 --- a/src/main/java/frog_jump/FrogJump.java +++ b/src/main/java/frog_jump/FrogJump.java @@ -60,7 +60,7 @@ public boolean canCrossDP(int[] stones) { return !dp.get(stones[stones.length - 1]).isEmpty(); } - + } From cc7cfeebb17cd1be717a304180165b7c9cd0f312 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 16 Sep 2017 17:15:18 -0700 Subject: [PATCH 092/456] add countBattleShips --- src/main/java/battleships_in_board/BattleShipsInBoard.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/battleships_in_board/BattleShipsInBoard.java b/src/main/java/battleships_in_board/BattleShipsInBoard.java index 0227625..adf2dcb 100644 --- a/src/main/java/battleships_in_board/BattleShipsInBoard.java +++ b/src/main/java/battleships_in_board/BattleShipsInBoard.java @@ -14,9 +14,9 @@ public int countBattleships(char[][] board) { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (board[i][j] == 'X' && !visited[i][j]) { - int[] lineOrCol = {0, 0}; - dfs(board, visited, lineOrCol, i, j); - if (lineOrCol[0] == i || lineOrCol[1] == j) ++res; + int[] lineAndCol = {0, 0}; + dfs(board, visited, lineAndCol, i, j); + if (lineAndCol[0] == i || lineAndCol[1] == j) ++res; } } } From dbf7c359d4d1b34c09fe36c6f01947db87454df0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 17 Sep 2017 02:30:57 -0700 Subject: [PATCH 093/456] add reconstruct_itinerary --- .../reconstruct_itinerary/findItinerary.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/java/reconstruct_itinerary/findItinerary.java diff --git a/src/main/java/reconstruct_itinerary/findItinerary.java b/src/main/java/reconstruct_itinerary/findItinerary.java new file mode 100644 index 0000000..ebd2911 --- /dev/null +++ b/src/main/java/reconstruct_itinerary/findItinerary.java @@ -0,0 +1,48 @@ +package reconstruct_itinerary; + +import com.google.common.collect.TreeMultiset; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +/** + * Created by lxie on 9/16/17. + */ +public class findItinerary { + + public static class Solution { + public List findItinerary(String[][] tickets) { + List res = new ArrayList<>(); + HashMap> m = new HashMap<>(); + for (String[] a : tickets) { + if(m.get(a[0]) == null) { + m.put(a[0], TreeMultiset.create()); + } + m.get(a[0]).add(a[1]); + } + dfs(m, "JFK", res); + Collections.reverse(res); + return res; + } + + private void dfs(HashMap> m, String s, List res) { + while (m.get(s) != null && m.get(s).size() != 0) { + String t = m.get(s).firstEntry().toString(); + m.get(s).remove(t); + dfs(m, t, res); + } + res.add(s); + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + String[][] tickets = {{"JFK", "KUL"}, {"JFK", "NRT"}, {"NRT", "JFK"}}; + List res = sol.findItinerary(tickets); + System.out.println(res.toString()); + } + +} From 9d5a3dd6f2c733b338aacd9edb9dde846a7500ed Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 17 Sep 2017 18:03:00 -0700 Subject: [PATCH 094/456] add queue_reconstruct_by_height --- .../QueueReconsByHeight.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java diff --git a/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java b/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java new file mode 100644 index 0000000..bcaff33 --- /dev/null +++ b/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java @@ -0,0 +1,43 @@ +package queue_reconstruct_by_height; + +import java.util.*; + +/** + * Created by lxie on 9/17/17. + */ +public class QueueReconsByHeight { + + public static class Solution { + public int[][] reconstructQueue(int[][] people) { + List peopleL = new LinkedList(Arrays.asList(people)); + Collections.sort(peopleL, new Comparator(){ + public int compare(int[] arr1, int[] arr2){ + if(arr1[0] == arr2[0]) + return arr1[1] - arr2[1]; + else + return arr2[0] - arr1[0]; + } + }); + + for (int i = 0; i < peopleL.size(); i++) { + int[] p = peopleL.get(i); + if (p[1] != i) { + peopleL.remove(i); + peopleL.add(p[1], p); + } + } + + return peopleL.toArray(new int[peopleL.size()][2]); + } + + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + int[][] people = {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}}; + int[][] res = sol.reconstructQueue(people); + System.out.println(res); + } + +} From c289f8e2220cce5e295d0ce92b65f34287ce118a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 18 Sep 2017 16:52:30 -0700 Subject: [PATCH 095/456] add trapping_rain_water_II --- src/main/java/frog_jump/FrogJump.java | 2 +- .../QueueReconsByHeight.java | 4 +- .../TrapRainWaterII.java | 65 +++++++++++++++++++ 3 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 src/main/java/trapping_rain_water_II/TrapRainWaterII.java diff --git a/src/main/java/frog_jump/FrogJump.java b/src/main/java/frog_jump/FrogJump.java index a4fd362..d2f78f9 100644 --- a/src/main/java/frog_jump/FrogJump.java +++ b/src/main/java/frog_jump/FrogJump.java @@ -69,4 +69,4 @@ public static void main(String[] args) { } -} +} \ No newline at end of file diff --git a/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java b/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java index bcaff33..6873469 100644 --- a/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java +++ b/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java @@ -37,7 +37,7 @@ public static void main(String[] args) { Solution sol = new Solution(); int[][] people = {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}}; int[][] res = sol.reconstructQueue(people); - System.out.println(res); + System.out.println(res.toString()); } - + } diff --git a/src/main/java/trapping_rain_water_II/TrapRainWaterII.java b/src/main/java/trapping_rain_water_II/TrapRainWaterII.java new file mode 100644 index 0000000..1dc95cf --- /dev/null +++ b/src/main/java/trapping_rain_water_II/TrapRainWaterII.java @@ -0,0 +1,65 @@ +package trapping_rain_water_II; + +import javafx.util.Pair; + +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * Created by lxie on 9/18/17. + */ +public class TrapRainWaterII { + + static class Solution { + public int trapRainWater(int[][] heightMap) { + if(heightMap.length == 0) return 0; + int m = heightMap.length, n = heightMap[0].length, res = 0, mx = Integer.MIN_VALUE; + PairComparator comparator = new PairComparator(); + PriorityQueue> q = new PriorityQueue<>(100, comparator); + boolean[][] visited = new boolean[m][n]; + int[][] dir = {{0,-1},{-1,0},{0,1},{1,0}}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + q.offer(new Pair(heightMap[i][j], i * n + j)); + visited[i][j] = true; + } + } + } + while (!q.isEmpty()) { + Pair t = q.poll(); + int h = t.getKey(), r = t.getValue() / n, c = t.getValue() % n; + mx = Math.max(mx, h); + for (int i = 0; i < dir.length; ++i) { + int x = r + dir[i][0], y = c + dir[i][1]; + if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue; + visited[x][y] = true; + if (heightMap[x][y] < mx) res += mx - heightMap[x][y]; // LC 42 + q.offer(new Pair(heightMap[x][y], x * n + y)); + } + } + return res; + + } + + class PairComparator implements Comparator> { + @Override + public int compare(Pair p1, Pair p2) { + return p1.getKey() - p2.getKey(); + } + } + + } + + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + int[][] heightMap = {{1,4,3,1,3,2}, {3,2,1,3,2,4}, {2,3,3,2,3,1}}; + int res = sol.trapRainWater(heightMap); + System.out.println(res); + } + + + +} From d1676e06099aa5f6708278cb740608739cb54690 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 19 Sep 2017 15:33:02 -0700 Subject: [PATCH 096/456] add longest_absolute_file_path --- .../LongAbsoluteFilePath.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/longest_absolute_file_path/LongAbsoluteFilePath.java diff --git a/src/main/java/longest_absolute_file_path/LongAbsoluteFilePath.java b/src/main/java/longest_absolute_file_path/LongAbsoluteFilePath.java new file mode 100644 index 0000000..167b6a1 --- /dev/null +++ b/src/main/java/longest_absolute_file_path/LongAbsoluteFilePath.java @@ -0,0 +1,33 @@ +package longest_absolute_file_path; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 9/19/17. + */ +public class LongAbsoluteFilePath { + + class Solution { + public int lengthLongestPath(String input) { + int res = 0; + Map m = new HashMap<>(); + m.put(0, 0); + for (String s : input.split("\n")) { + int level = s.lastIndexOf("\t") + 1; + int len = s.substring(level).length(); + if (s.contains(".")) { + res = Math.max(res, m.get(level) + len); + } else { + m.put(level + 1, m.get(level) + len + 1); + } + } + return res; + + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + } +} From 45125bf452c04c6328e9406a8575b97fcfe4d0b2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 20 Sep 2017 10:24:26 -0700 Subject: [PATCH 097/456] add utf8_validation --- .../java/utf8_validation/UTF8Validation.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/utf8_validation/UTF8Validation.java diff --git a/src/main/java/utf8_validation/UTF8Validation.java b/src/main/java/utf8_validation/UTF8Validation.java new file mode 100644 index 0000000..1af581e --- /dev/null +++ b/src/main/java/utf8_validation/UTF8Validation.java @@ -0,0 +1,38 @@ +package utf8_validation; + +/** + * Created by lxie on 9/20/17. + */ +public class UTF8Validation { + + class Solution { + public boolean validUtf8(int[] data) { + int cnt = 0; + for (int d : data) { + if (cnt == 0) { + if ((d >> 5) == 0b110) cnt = 1; + else if ((d >> 4) == 0b1110) cnt = 2; + else if ((d >> 3) == 0b11110) cnt = 3; + else if (d >> 7 != 0) return false; + } else { + if ((d >> 6) != 0b10) return false; + --cnt; + } + } + return cnt == 0; + + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + } + + + + + + + + +} From d0e2ffa3f90fa8fd63a3aa7bfd2634b921e9497c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 20 Sep 2017 16:51:08 -0700 Subject: [PATCH 098/456] flatten_nested_list_iterator --- .../FlattenNestListIterator.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java diff --git a/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java b/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java new file mode 100644 index 0000000..091c49a --- /dev/null +++ b/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java @@ -0,0 +1,78 @@ +package flatten_nested_list_iterator; + +import java.util.Iterator; +import java.util.List; +import java.util.Stack; + +/** + * Created by lxie on 9/20/17. + */ +public class FlattenNestListIterator { + + public interface NestedInteger { + // @return true if this NestedInteger holds a single integer, rather than a nested list. + public boolean isInteger(); + + // @return the single integer that this NestedInteger holds, if it holds a single integer + // Return null if this NestedInteger holds a nested list + public Integer getInteger(); + + // @return the nested list that this NestedInteger holds, if it holds a nested list + // Return null if this NestedInteger holds a single integer + public List getList(); + } + + + class Solution { + + public class NestedIterator implements Iterator { + + private Stack stack; + + private void pushListToStack(List nestedList) { + Stack temp = new Stack<>(); + for (NestedInteger nested : nestedList) { + temp.push(nested); + } + + while (!temp.isEmpty()) { // in reverse order + stack.push(temp.pop()); + } + } + + public NestedIterator(List nestedList) { + stack = new Stack<>(); + pushListToStack(nestedList); + } + + // @return {int} the next element in the iteration + @Override + public Integer next() { + if (!hasNext()) { + return null; + } + return stack.pop().getInteger(); + } + + // @return {boolean} true if the iteration has more element or false + @Override + public boolean hasNext() { + while (!stack.isEmpty() && !stack.peek().isInteger()) { + pushListToStack(stack.pop().getList()); + } + + return !stack.isEmpty(); + } + + @Override + public void remove() { + } + } + + public void main(String[] args) { + System.out.println("this is for test"); + } + + } + +} From f4a30258bb2f5416e6952b8bf38e1c65ea2b2670 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 22 Sep 2017 01:47:08 -0700 Subject: [PATCH 099/456] add design_phone_directory --- .../PhoneDirectory.java | 67 +++++++++++++++++++ .../FlattenNestListIterator.java | 2 +- 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 src/main/java/design_phone_directory/PhoneDirectory.java diff --git a/src/main/java/design_phone_directory/PhoneDirectory.java b/src/main/java/design_phone_directory/PhoneDirectory.java new file mode 100644 index 0000000..c7ba652 --- /dev/null +++ b/src/main/java/design_phone_directory/PhoneDirectory.java @@ -0,0 +1,67 @@ +package design_phone_directory; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 9/22/17. + */ +public class PhoneDirectory { + + private int max_num, next, idx; + private List recycle = new ArrayList<>(); + private List flag = new ArrayList<>(); + + /** Initialize your data structure here + @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ + public PhoneDirectory(int maxNumbers) { + max_num = maxNumbers; + next = idx = 0; + for (int i=0; i 0) { + int t = recycle.get(--idx); + flag.set(t, false); + return t; + } + flag.set(next, false); + return next++; + } + + /** Check if a number is available or not. */ + public boolean check(int number) { + return number >= 0 && number < max_num && flag.get(number); + } + + /** Recycle or release a number. */ + public void release(int number) { + if (number >= 0 && number < max_num && !flag.get(number)) { + recycle.add(number); + idx++; + flag.set(number, true); + } + } + + + + public static void main(String[] args) { + System.out.println("this is for test"); + PhoneDirectory phones = new PhoneDirectory(3); + System.out.println("directory.get() ->" + phones.get()); + System.out.println("directory.get() ->" + phones.get()); + System.out.println("directory.check(2) ->" + phones.check(2)); + System.out.println("directory.get() ->" + phones.get()); + System.out.println("directory.check(2) ->" + phones.check(2)); + System.out.println("directory.release(2) ->"); + phones.release(2); + System.out.println("directory.check(2) ->" + phones.check(2)); + } + +} diff --git a/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java b/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java index 091c49a..4e36580 100644 --- a/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java +++ b/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java @@ -72,7 +72,7 @@ public void remove() { public void main(String[] args) { System.out.println("this is for test"); } - + } } From 8cfafc808c175aeddfb15e86f8acc98d850c0306 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 22 Sep 2017 03:44:28 -0700 Subject: [PATCH 100/456] insert_delete_random --- .../insert_delete_random/RandomizedSet.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/main/java/insert_delete_random/RandomizedSet.java diff --git a/src/main/java/insert_delete_random/RandomizedSet.java b/src/main/java/insert_delete_random/RandomizedSet.java new file mode 100644 index 0000000..28ebefe --- /dev/null +++ b/src/main/java/insert_delete_random/RandomizedSet.java @@ -0,0 +1,73 @@ +package insert_delete_random; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 9/22/17. + */ +public class RandomizedSet { + + private List nums = new ArrayList<>(); + private Map m = new HashMap<>(); + + /** Initialize your data structure here. */ + public RandomizedSet() {} + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + public boolean insert(int val) { + if (m.containsKey(val)) return false; + nums.add(val); + m.put(val, nums.size() - 1); + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + public boolean remove(int val) { + if (!m.containsKey(val)) return false; + int last = nums.get(nums.size()-1); + m.put(last, m.get(val)); + nums.set(m.get(val), last); + nums.remove(nums.size() - 1); + m.remove(val); + return true; + } + + /** Get a random element from the set. */ + int getRandom() { + return nums.get((int)Math.random() % nums.size()); + } + + + + public static void main(String[] args) { + System.out.println("this is for test"); + RandomizedSet randomSet = new RandomizedSet(); + + // Inserts 1 to the set. Returns true as 1 was inserted successfully. + System.out.println("randomSet.insert(1) -> " + randomSet.insert(1)); + + // Returns false as 2 does not exist in the set. + System.out.println("randomSet.remove(2) -> " + randomSet.remove(2)); + + // Inserts 2 to the set, returns true. Set now contains [1,2]. + System.out.println("randomSet.insert(2) -> " + randomSet.insert(2)); + + // getRandom should return either 1 or 2 randomly. + System.out.println("randomSet.getRandom() -> " + randomSet.getRandom()); + + // Removes 1 from the set, returns true. Set now contains [2]. + System.out.println("randomSet.remove(1) -> " + randomSet.remove(1)); + + // 2 was already in the set, so return false. + System.out.println("randomSet.insert(2) -> " + randomSet.insert(2)); + + // Since 1 is the only number in the set, getRandom always return 1. + System.out.println("randomSet.getRandom() -> " + randomSet.getRandom()); + + } + + +} From 2e56d2d4a24e02b1c6a421a50f02c1ccdcb74876 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 28 Sep 2017 10:19:38 -0700 Subject: [PATCH 101/456] add insert_delete_random_II --- .../insert_delete_random/RandomizedSet.java | 2 +- .../RandomizedCollection.java | 83 +++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 src/main/java/insert_delete_random_II/RandomizedCollection.java diff --git a/src/main/java/insert_delete_random/RandomizedSet.java b/src/main/java/insert_delete_random/RandomizedSet.java index 28ebefe..8410522 100644 --- a/src/main/java/insert_delete_random/RandomizedSet.java +++ b/src/main/java/insert_delete_random/RandomizedSet.java @@ -64,7 +64,7 @@ public static void main(String[] args) { // 2 was already in the set, so return false. System.out.println("randomSet.insert(2) -> " + randomSet.insert(2)); - // Since 1 is the only number in the set, getRandom always return 1. + // Since 2 is the only number in the set, getRandom always return 2. System.out.println("randomSet.getRandom() -> " + randomSet.getRandom()); } diff --git a/src/main/java/insert_delete_random_II/RandomizedCollection.java b/src/main/java/insert_delete_random_II/RandomizedCollection.java new file mode 100644 index 0000000..eceb7dc --- /dev/null +++ b/src/main/java/insert_delete_random_II/RandomizedCollection.java @@ -0,0 +1,83 @@ +package insert_delete_random_II; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 9/23/17. + */ +public class RandomizedCollection { + private Map> map; + private List nums; + + /** Initialize your data structure here. */ + public RandomizedCollection() { + map = new HashMap<>(); + nums = new ArrayList<>(); + } + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + public boolean insert(int val) { + boolean res = !map.containsKey(val); + if(res) map.put(val, new ArrayList<>()); + map.get(val).add(nums.size()); + nums.add(new int[]{val, map.get(val).size() - 1}); + return res; + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + public boolean remove(int val) { + boolean res = map.containsKey(val); + if(res) { + List valList = map.get(val); + int valLastIndex = valList.get(valList.size() - 1); // always take the last one + + int[] swapNum = nums.get(nums.size() - 1); + int swapVal = swapNum[0], swapIndex = swapNum[1]; + + map.get(swapVal).set(swapIndex, valLastIndex); // set it to same pos + nums.set(valLastIndex, swapNum); + + if(valList.size() == 1) map.remove(val); + else valList.remove(valList.size() - 1); + + nums.remove(nums.size() - 1); + } + return res; + } + + /** Get a random element from the collection. */ + int getRandom() { + return nums.get((int)Math.random() % nums.size())[0]; + } + + public static void main(String[] args) { + System.out.println("this is for test"); + /* RandomizedCollection randomSet = new RandomizedCollection(); + + // Inserts 1 to the set. Returns true as 1 was inserted successfully. + System.out.println("randomSet.insert(1) -> " + randomSet.insert(1)); + + // Returns false as 2 does not exist in the set. + System.out.println("randomSet.remove(2) -> " + randomSet.remove(2)); + + // Inserts 2 to the set, returns true. Set now contains [1,2]. + System.out.println("randomSet.insert(2) -> " + randomSet.insert(2)); + + // getRandom should return either 1 or 2 randomly. + System.out.println("randomSet.getRandom() -> " + randomSet.getRandom()); + + // Removes 1 from the set, returns true. Set now contains [2]. + System.out.println("randomSet.remove(1) -> " + randomSet.remove(1)); + + // 2 was already in the set, so return false. + System.out.println("randomSet.insert(2) -> " + randomSet.insert(2)); + + // Since 2 is the only number in the set, getRandom always return 2. + System.out.println("randomSet.getRandom() -> " + randomSet.getRandom()); */ + + } + +} From 32b40df60ff42b7ef6a02f2fd0fba6dcb8357890 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 1 Oct 2017 19:53:41 -0700 Subject: [PATCH 102/456] add plus_one_linked_list --- .../PlusOneLinkedList.java | 44 +++++++++++++++++++ .../java/utf8_validation/UTF8Validation.java | 7 --- 2 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 src/main/java/plus_one_linked_list/PlusOneLinkedList.java diff --git a/src/main/java/plus_one_linked_list/PlusOneLinkedList.java b/src/main/java/plus_one_linked_list/PlusOneLinkedList.java new file mode 100644 index 0000000..d1eb8cf --- /dev/null +++ b/src/main/java/plus_one_linked_list/PlusOneLinkedList.java @@ -0,0 +1,44 @@ +package plus_one_linked_list; + +/** + * Created by lxie on 10/1/17. + */ +public class PlusOneLinkedList { + + /** + * Definition for singly-linked list. + **/ + public class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + class Solution { + public ListNode PlusOneLinkedList(ListNode head) { + if (head == null) return head; + int carry = helper(head); + if (carry == 1) { + ListNode res = new ListNode(1); + res.next = head; + return res; + } + return head; + } + + int helper(ListNode node) { + if (node == null) return 1; + int carry = helper(node.next); + int sum = node.val + carry; + node.val = sum % 10; + return sum/10; + } + + } + + public static class UnitTest { + + } + + +} diff --git a/src/main/java/utf8_validation/UTF8Validation.java b/src/main/java/utf8_validation/UTF8Validation.java index 1af581e..caf2eda 100644 --- a/src/main/java/utf8_validation/UTF8Validation.java +++ b/src/main/java/utf8_validation/UTF8Validation.java @@ -28,11 +28,4 @@ public static void main(String[] args) { System.out.println("this is for test"); } - - - - - - - } From a0f7247cada1901494ef2b80c830900a52dfea96 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 5 Oct 2017 10:57:28 -0700 Subject: [PATCH 103/456] add plus_one_linked_list --- src/main/java/plus_one_linked_list/PlusOneLinkedList.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/plus_one_linked_list/PlusOneLinkedList.java b/src/main/java/plus_one_linked_list/PlusOneLinkedList.java index d1eb8cf..d413e2c 100644 --- a/src/main/java/plus_one_linked_list/PlusOneLinkedList.java +++ b/src/main/java/plus_one_linked_list/PlusOneLinkedList.java @@ -35,7 +35,7 @@ int helper(ListNode node) { } } - + public static class UnitTest { } From 0d8ced053aee15f74a8392b880160f2fcc6b0378 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 16 Oct 2017 10:34:32 -0700 Subject: [PATCH 104/456] add search_for_a_range --- .../search_for_a_range/SearchforaRange.java | 36 +++++++++---------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/main/java/search_for_a_range/SearchforaRange.java b/src/main/java/search_for_a_range/SearchforaRange.java index 66efd7f..e3df0f4 100644 --- a/src/main/java/search_for_a_range/SearchforaRange.java +++ b/src/main/java/search_for_a_range/SearchforaRange.java @@ -4,29 +4,25 @@ public class SearchforaRange { public class Solution { - private int lowerBound(int[] A, int left, int right, int target) { - while (left <= right) { + public int[] searchRange(int[] nums, int target) { + int[] res = new int[] {-1, -1}; + if (nums.length == 0) return res; + int left = 0, right = nums.length - 1; + while (left < right) { int mid = left + (right - left) / 2; - if (A[mid] < target) { - left = mid + 1; - } else { - right = mid - 1; - } + if (nums[mid] < target) left = mid + 1; + else right = mid; } - return left; - } - - public int[] searchRange(int[] A, int target) { - int[] ans = new int[2]; - int begin = lowerBound(A, 0, A.length - 1, target); - if (begin < A.length && A[begin] == target) { - ans[0] = begin; - ans[1] = lowerBound(A, begin + 1, A.length - 1, target + 1) - 1; - } else { - ans[0] = -1; - ans[1] = -1; + if (nums[right] != target) return res; + res[0] = right; + right = nums.length; // edge case - left=0, right=0 + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] <= target) left = mid + 1; + else right= mid; } - return ans; + res[1] = left - 1; + return res; } } From 61cc238fe9bd8e696376876e367fed7ba2c4b8c2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 24 Oct 2017 11:58:29 -0700 Subject: [PATCH 105/456] add android_unlock_patterns --- .../AndroidUnlockPatterns.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/android_unlock_patterns/AndroidUnlockPatterns.java diff --git a/src/main/java/android_unlock_patterns/AndroidUnlockPatterns.java b/src/main/java/android_unlock_patterns/AndroidUnlockPatterns.java new file mode 100644 index 0000000..96c6a9f --- /dev/null +++ b/src/main/java/android_unlock_patterns/AndroidUnlockPatterns.java @@ -0,0 +1,46 @@ +package android_unlock_patterns; + +/** + * Created by lxie on 10/24/17. + */ +public class AndroidUnlockPatterns { + public class Solution { + + public int numberOfPatterns(int m, int n) { + int res = 0; + Boolean[] visited = new Boolean[10]; + int[][] jumps = new int[10][10]; + jumps[1][3] = jumps[3][1] = 2; + jumps[4][6] = jumps[6][4] = 5; + jumps[7][9] = jumps[9][7] = 8; + jumps[1][7] = jumps[7][1] = 4; + jumps[2][8] = jumps[8][2] = 5; + jumps[3][9] = jumps[9][3] = 6; + jumps[1][9] = jumps[9][1] = jumps[3][7] = jumps[7][3] = 5; + res += helper(1, 1, 0, m, n, jumps, visited) * 4; + res += helper(2, 1, 0, m, n, jumps, visited) * 4; + res += helper(5, 1, 0, m, n, jumps, visited); + return res; + } + + private int helper(int num, int len, int res, int m, int n, int[][] jumps, Boolean[] visited) { + if (len >= m) ++res; + ++len; + if (len > n) return res; + visited[num] = true; + for (int next = 1; next <= 9; ++next) { + int jump = jumps[num][next]; + if (!visited[next] && (jump == 0 || visited[jump])) { + res = helper(next, len, res, m, n, jumps, visited); + } + } + visited[num] = false; + return res; + } + } + + public static class UnitTest { + + } + +} From d932f9ccdbf87ed3dae618167ce7570592b7038d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 2 Nov 2017 16:20:44 -0700 Subject: [PATCH 106/456] add wiggle_subsequence --- .../wiggle_subsequence/WiggleSubsequence.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/wiggle_subsequence/WiggleSubsequence.java diff --git a/src/main/java/wiggle_subsequence/WiggleSubsequence.java b/src/main/java/wiggle_subsequence/WiggleSubsequence.java new file mode 100644 index 0000000..032b62c --- /dev/null +++ b/src/main/java/wiggle_subsequence/WiggleSubsequence.java @@ -0,0 +1,36 @@ +package wiggle_subsequence; + +/** + * Created by lxie on 11/2/17. + */ +public class WiggleSubsequence { + + public class Solution { + + public int wiggleMaxLength(int[] nums) { + int n = nums.length; + if (n == 0) return 0; + + + int[] p = new int[n]; + int[] q = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = q[i] = 1; + } + + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[i] > nums[j]) p[i] = Math.max(p[i], q[j] + 1); + else if (nums[i] < nums[j]) q[i] = Math.max(q[i], p[j] + 1); + } + } + return Math.max(p[n-1], q[n-1]); + } + } + + public static class UnitTest { + + } + + +} From eab61d88f6a0fb2c29e7fab525f4cf81e1f6dbd8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 3 Nov 2017 17:09:11 -0700 Subject: [PATCH 107/456] add kth smallest in a sorted matrix --- .../kthSmallestSortMatrix.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/kth_smallest_in_sorted_matrix/kthSmallestSortMatrix.java diff --git a/src/main/java/kth_smallest_in_sorted_matrix/kthSmallestSortMatrix.java b/src/main/java/kth_smallest_in_sorted_matrix/kthSmallestSortMatrix.java new file mode 100644 index 0000000..c55a0b9 --- /dev/null +++ b/src/main/java/kth_smallest_in_sorted_matrix/kthSmallestSortMatrix.java @@ -0,0 +1,41 @@ +package kth_smallest_in_sorted_matrix; + +/** + * Created by lxie on 11/3/17. + */ +public class kthSmallestSortMatrix { + + public class Solution { + + public int kthSmallest(int[][] matrix, int k) { + int n = matrix.length; + int left = matrix[0][0], right = matrix[n-1][n-1]; + while (left < right) { + int mid = left + (right - left) / 2; + int cnt = search_less_equal(matrix, mid); + if (cnt < k) left = mid + 1; + else right = mid; + } + return left; + } + + public int search_less_equal(int[][] matrix, int target) { + int n = matrix.length, i = n - 1, j = 0, res = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] <= target) { + res += i + 1; + ++j; + } else { + --i; + } + } + return res; + } + + } + + public static class UnitTest { + + } + +} From 0604477f92764beec0afc66d3fef06b0757ca823 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 4 Nov 2017 17:19:31 -0700 Subject: [PATCH 108/456] modify dundeon game. --- src/main/java/dungeon_game/DungeonGame.java | 22 ++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/dungeon_game/DungeonGame.java b/src/main/java/dungeon_game/DungeonGame.java index ed8ae2b..c50a7c5 100644 --- a/src/main/java/dungeon_game/DungeonGame.java +++ b/src/main/java/dungeon_game/DungeonGame.java @@ -1,5 +1,6 @@ package dungeon_game; + public class DungeonGame { public class Solution { @@ -7,21 +8,20 @@ public int calculateMinimumHP(int[][] dungeon) { int m = dungeon.length; int n = dungeon[0].length; int[][] dp = new int[m][n]; - dp[m - 1][n - 1] = 1; - for (int i = m - 2; i >= 0; i--) { - dp[i][n - 1] = Math.max(1, dp[i + 1][n - 1] - dungeon[i + 1][n - 1]); + dp[m - 1][n - 1] = Math.max(1, 1 - dungeon[m - 1][n - 1]); + for (int i = m - 2; i >= 0; --i) { + dp[i][n - 1] = Math.max(1, dp[i + 1][n - 1] - dungeon[i][n - 1]); } - for (int i = n - 2; i >= 0; i--) { - dp[m - 1][i] = Math.max(1, dp[m - 1][i + 1] - dungeon[m - 1][i + 1]); + for (int j = n - 2; j >= 0; --j) { + dp[m - 1][j] = Math.max(1, dp[m - 1][j + 1] - dungeon[m - 1][j]); } - for (int i = m - 2; i >= 0; i--) { - for (int j = n - 2; j >= 0; j--) { - dp[i][j] = Math.max(1, - Math.min(dp[i][j + 1] - dungeon[i][j + 1], dp[i + 1][j] - dungeon[i + 1][j]) - ); + for (int i = m - 2; i >= 0; --i) { + for (int j = n - 2; j >= 0; --j) { + dp[i][j] = Math.max(1, Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]); } } - return Math.max(1, dp[0][0] - dungeon[0][0]); + return dp[0][0]; + } } From 2f75e0d11c8295c3c2eb14179221233a645a6083 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 6 Nov 2017 01:01:05 -0800 Subject: [PATCH 109/456] add largest divisible subset --- .../LargestDivisibleSubset.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/largest_divisible_subset/LargestDivisibleSubset.java diff --git a/src/main/java/largest_divisible_subset/LargestDivisibleSubset.java b/src/main/java/largest_divisible_subset/LargestDivisibleSubset.java new file mode 100644 index 0000000..84f142f --- /dev/null +++ b/src/main/java/largest_divisible_subset/LargestDivisibleSubset.java @@ -0,0 +1,44 @@ +package largest_divisible_subset; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 11/6/17. + */ +public class LargestDivisibleSubset { + + public class Solution { + + public List largestDivisibleSubset(int[] nums) { + Arrays.sort(nums); + List res = new ArrayList<>(); + int[] dp = new int[nums.length]; + int[] parent = new int[nums.length]; + int mx = 0, mx_idx = 0; + for (int i = nums.length - 1; i >= 0; --i) { + for (int j = i; j < nums.length; ++j) { + if (nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) { + dp[i] = dp[j] + 1; + parent[i] = j; + if (mx < dp[i]) { + mx = dp[i]; + mx_idx = i; + } + } + } + } + for (int i = 0; i < mx; ++i) { + res.add(nums[mx_idx]); + mx_idx = parent[mx_idx]; // a good way to track + } + return res; + } + } + + public static class UnitTest { + + } + +} From 642211cb4560a61ba450ac9a5d222e2624811d0d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 8 Nov 2017 02:25:20 -0800 Subject: [PATCH 110/456] change word_ladder I --- src/main/java/word_ladder/WordLadder.java | 68 +++++++++-------------- 1 file changed, 27 insertions(+), 41 deletions(-) diff --git a/src/main/java/word_ladder/WordLadder.java b/src/main/java/word_ladder/WordLadder.java index 8f61281..63df681 100644 --- a/src/main/java/word_ladder/WordLadder.java +++ b/src/main/java/word_ladder/WordLadder.java @@ -1,57 +1,43 @@ package word_ladder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; public class WordLadder { - public class Solution { - public int ladderLength(String start, String end, HashSet dict) { - if (start.equals(end)) { - return 1; - } - List queue = new ArrayList(); - int level = 1; - queue.add(start); - int begin = 0; - char[] endCharArray = end.toCharArray(); - Set used = new HashSet(); - used.add(start); - while (begin < queue.size()) { - int tail = queue.size(); - for (int i = begin; i < tail; i++) { - char[] word = queue.get(i).toCharArray(); - for (int j = 0; j < word.length; j++) { - char currentChar = word[j]; - for (char c = 'a'; c <= 'z'; c++) { - if (c == currentChar) { - continue; - } - word[j] = c; - if (Arrays.equals(word, endCharArray)) { - return level + 1; - } - String nextWord = new String(word); - if (dict.contains(nextWord) - && !used.contains(nextWord)) { - used.add(nextWord); - queue.add(nextWord); - } - word[j] = currentChar; + public static class Solution { + public int ladderLength(String beginWord, String endWord, List wordList) { + if (!wordList.contains(endWord)) return 0; + Map m = new HashMap<>(); + Queue q = new LinkedList<>(); + m.put(beginWord, 1); + q.add(beginWord); + while (!q.isEmpty()) { + String word = q.remove(); + for (int i = 0; i < word.length(); ++i) { + String newWord = word; + for (char ch = 'a'; ch <= 'z'; ++ch) { + newWord = newWord.substring(0, i) + ch + newWord.substring(i + 1); + if (newWord.compareTo(endWord) == 0) return m.get(word) + 1; + if (wordList.contains(newWord) && !m.containsKey(newWord)) { + q.add(newWord); + m.put(newWord, m.get(word) + 1); } } } - level++; - begin = tail; } return 0; } + } - public static class UnitTest { + public static void main(String[] args) { + Solution sol = new Solution(); + List dict = new ArrayList( + Arrays.asList("hot","dot","dog","lot","log", "cog")); + int ret = sol.ladderLength("hit", "cog", dict); + System.out.println("test result is " + ret); } + + } From 313847096e1b022407748c36ada95a55599b1540 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 13 Nov 2017 00:51:38 -0800 Subject: [PATCH 111/456] add word_ladder_ii --- src/main/java/word_ladder/WordLadder.java | 1 + .../java/word_ladder_ii/WordLadderII.java | 155 +++++------------- 2 files changed, 44 insertions(+), 112 deletions(-) diff --git a/src/main/java/word_ladder/WordLadder.java b/src/main/java/word_ladder/WordLadder.java index 63df681..0a8ec12 100644 --- a/src/main/java/word_ladder/WordLadder.java +++ b/src/main/java/word_ladder/WordLadder.java @@ -16,6 +16,7 @@ public int ladderLength(String beginWord, String endWord, List wordList) for (int i = 0; i < word.length(); ++i) { String newWord = word; for (char ch = 'a'; ch <= 'z'; ++ch) { + if (newWord.charAt(i) == ch) continue; newWord = newWord.substring(0, i) + ch + newWord.substring(i + 1); if (newWord.compareTo(endWord) == 0) return m.get(word) + 1; if (wordList.contains(newWord) && !m.containsKey(newWord)) { diff --git a/src/main/java/word_ladder_ii/WordLadderII.java b/src/main/java/word_ladder_ii/WordLadderII.java index 3e8b77c..bb8f3b4 100644 --- a/src/main/java/word_ladder_ii/WordLadderII.java +++ b/src/main/java/word_ladder_ii/WordLadderII.java @@ -1,128 +1,59 @@ package word_ladder_ii; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; +import java.util.*; public class WordLadderII { - /** - * "Time Limit Exceeded". Is there a perfect Java solution to pass the - * tests? - */ - public class Solution { - - private HashMap> searchNeighbors(String[] nodes) { - HashMap indices = new HashMap( - nodes.length); - int i = 0; - for (String word : nodes) { - indices.put(word, i++); - } - - HashMap> neighbors = new HashMap>(); - - i = 0; - for (String word : nodes) { - List neighbor = neighbors.get(word); - if (neighbor == null) { - neighbor = new ArrayList(); - neighbors.put(i, neighbor); + public static class Solution { + + public List> findLadders(String beginWord, String endWord, List wordList) { + List> res = new ArrayList<>(new ArrayList<>()); + Set dict = new HashSet<>(wordList); + List p = new ArrayList<>(Arrays.asList(beginWord)); + Queue> paths = new LinkedList<>(); + paths.add(p); + int level = 1, minLevel = Integer.MAX_VALUE; + Set words = new HashSet<>(); + while (!paths.isEmpty()) { + List t = paths.remove(); + if (t.size() > level) { // enters a new level + for (String w : words) dict.remove(w); // removes words used in the last level + words.clear(); + level = t.size(); + if (level > minLevel) + break; } - char[] temp = word.toCharArray(); - for (int j = 0; j < temp.length; j++) { - char oldC = temp[j]; - for (char c = 'a'; c <= 'z'; c++) { - if (c != oldC) { - temp[j] = c; - String newS = new String(temp); - Integer index = indices.get(newS); - if (index != null) { - neighbor.add(index); - } + String last = t.get(t.size() - 1); + for (int i = 0; i < last.length(); ++i) { + // String newLast = last; + for (char ch = 'a'; ch <= 'z'; ++ch) { + if (last.charAt(i) == ch) continue; + String newLast = last.substring(0, i) + ch + last.substring(i + 1); + if (!dict.contains(newLast)) continue; + words.add(newLast); + List nextPath = new ArrayList<>(t); + nextPath.add(newLast); + if (newLast.compareTo(endWord) == 0) { + res.add(nextPath); + minLevel = level; + } else { + paths.add(nextPath); } - } - temp[j] = oldC; - } - i++; - } - return neighbors; - } - - public ArrayList> findLadders(String start, - String end, HashSet dict) { - ArrayList> ans = new ArrayList>(); - - if (start.equals(end)) { - ArrayList l = new ArrayList(); - l.add(start); - ans.add(l); - return ans; - } - ArrayList queue = new ArrayList(); - ArrayList prev = new ArrayList(); - - dict.add(start); - dict.add(end); - - String[] nodes = new String[dict.size()]; - int j = 0; - int startIndex = 0; - int endIndex = 0; - for (String word : dict) { - if (word.equals(start)) { - startIndex = j; - } - if (word.equals(end)) { - endIndex = j; - } - nodes[j++] = word; - } - HashMap> neighbors = searchNeighbors(nodes); - System.gc(); // To avoid "Memory Limit Exceeded" - - queue.add(startIndex); - prev.add(-1); - boolean[] used = new boolean[nodes.length]; - used[startIndex] = true; - int begin = 0; - boolean find = false; - while (!find && begin < queue.size()) { - int tail = queue.size(); - for (int i = begin; i < tail; i++) { - int s = queue.get(i); - for (int indexInNode : neighbors.get(s)) { - if (indexInNode == endIndex) { - find = true; - ArrayList path = new ArrayList(); - path.add(end); - int index = i; - while (index >= 0) { - path.add(nodes[queue.get(index)]); - index = prev.get(index); - } - Collections.reverse(path); - ans.add(path); - break; - } - if (!find && !used[indexInNode]) { - queue.add(indexInNode); - prev.add(i); - } } } - begin = tail; - for (int i = begin; i < tail; i++) { - used[queue.get(i)] = true; - } } - return ans; + return res; } } - public static class UnitTest { + public static void main(String[] args) { + Solution sol = new Solution(); + List dict = new ArrayList( + Arrays.asList("hot","dot","dog","lot","log", "cog")); + List> ret = sol.findLadders("hit", "cog", dict); + System.out.println("test result is " + ret.toString()); + } + } From 5c0738a074f75d6110690a55fc3b3f781b91111c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Nov 2017 02:38:47 -0800 Subject: [PATCH 112/456] add coin_change --- src/main/java/coin_change/CoinChange.java | 27 +++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/coin_change/CoinChange.java diff --git a/src/main/java/coin_change/CoinChange.java b/src/main/java/coin_change/CoinChange.java new file mode 100644 index 0000000..4c543f1 --- /dev/null +++ b/src/main/java/coin_change/CoinChange.java @@ -0,0 +1,27 @@ +package coin_change; + +/** + * Created by lxie on 11/15/17. + */ +public class CoinChange { + public class Solution { + public int coinChange(int[] coins, int amount) { + int[] dp = new int[amount+1]; + for(int i=0; i< dp.length; ++i) dp[i] = amount+1; + dp[0] = 0; + for (int i = 1; i <= amount; ++i) { + for (int j = 0; j < coins.length; ++j) { + if (coins[j] <= i) { + dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); + } + } + } + return dp[amount] > amount ? -1 : dp[amount]; + } + + } + + public static class UnitTest { + + } +} From 3fe560c831389a1b26e1947f4651fa8bd9bf07f2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 16 Nov 2017 23:23:59 -0800 Subject: [PATCH 113/456] add coin change ii --- .../java/coin_change_ii/CoinChangeII.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/coin_change_ii/CoinChangeII.java diff --git a/src/main/java/coin_change_ii/CoinChangeII.java b/src/main/java/coin_change_ii/CoinChangeII.java new file mode 100644 index 0000000..8766cbb --- /dev/null +++ b/src/main/java/coin_change_ii/CoinChangeII.java @@ -0,0 +1,28 @@ +package coin_change_ii; + +/** + * Created by lxie on 11/16/17. + */ +public class CoinChangeII { + + public class Solution { + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; + dp[0] = 1; + for (int coin : coins) { + for (int i = coin; i <= amount; ++i) { + dp[i] += dp[i - coin]; + } + } + return dp[amount]; + } + + } + + public static class UnitTest { + + } + + + +} From 4f1171887a9e9a1869b5998804f63108fea8fad4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 17 Nov 2017 02:08:42 -0800 Subject: [PATCH 114/456] add remove_duplicate_letters. --- .../RemoveDuplicateLetters.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/remove_duplicate_letters/RemoveDuplicateLetters.java diff --git a/src/main/java/remove_duplicate_letters/RemoveDuplicateLetters.java b/src/main/java/remove_duplicate_letters/RemoveDuplicateLetters.java new file mode 100644 index 0000000..a2f9b88 --- /dev/null +++ b/src/main/java/remove_duplicate_letters/RemoveDuplicateLetters.java @@ -0,0 +1,34 @@ +package remove_duplicate_letters; + +/** + * Created by lxie on 11/17/17. + */ +public class RemoveDuplicateLetters { + + public class Solution { + public String removeDuplicateLetters(String s) { + int[] m = new int[256]; + int[] visited = new int[256]; + String res = "0"; + for (char a : s.toCharArray()) { + ++m[a]; + } + for (char a : s.toCharArray()) { + --m[a]; + if (visited[a] != 0) continue; + while (a < res.charAt(res.length()-1) && m[res.charAt(res.length()-1)] != 0) { + visited[res.charAt(res.length()-1)] = 0; + res = res.substring(0, res.length()-1); + } + res += a; + visited[a] = 1; + } + return res.substring(1); + } + + } + + public static class UnitTest { + + } +} From f50404cdb005bb1c4ef9acddc00adc43fdb1e0d6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 19 Nov 2017 02:06:21 -0800 Subject: [PATCH 115/456] add integer_replacement --- .../IntegerReplacement.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/main/java/integer_replacement/IntegerReplacement.java diff --git a/src/main/java/integer_replacement/IntegerReplacement.java b/src/main/java/integer_replacement/IntegerReplacement.java new file mode 100644 index 0000000..e051bc8 --- /dev/null +++ b/src/main/java/integer_replacement/IntegerReplacement.java @@ -0,0 +1,26 @@ +package integer_replacement; + +/** + * Created by lxie on 11/19/17. + */ +public class IntegerReplacement { + + public static class Solution { + public int integerReplacement(int n) { + if (n == 1) return 0; + if (n % 2 == 0) return 1 + integerReplacement(n / 2); + else { + long t = n; + return 2 + Math.min(integerReplacement((int) ((t + 1) / 2)), + integerReplacement((int) ((t - 1) / 2))); + } + } + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int n = 2147483647; + System.out.println("result is " + sol.integerReplacement(n)); + } +} From 5801fb0f2f903ce9ce3f87579eed9caae9598e9c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 23 Nov 2017 02:17:35 -0800 Subject: [PATCH 116/456] add lru_cache. --- src/main/java/lru_cache/LRUCache.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/lru_cache/LRUCache.java b/src/main/java/lru_cache/LRUCache.java index 91454c0..fc22901 100644 --- a/src/main/java/lru_cache/LRUCache.java +++ b/src/main/java/lru_cache/LRUCache.java @@ -10,8 +10,7 @@ public class LRUCache { public LRUCache(final int capacity) { assert capacity > 0; map = new LinkedHashMap(16, 0.75f, true) { - protected boolean removeEldestEntry( - Map.Entry eldest) { + protected boolean removeEldestEntry(Map.Entry eldest) { return size() > capacity; } }; @@ -25,7 +24,7 @@ public int get(int key) { return value; } - public void set(int key, int value) { + public void put(int key, int value) { map.put(key, value); } } From f4915f998ab607a0e3fb0f21ce0f656304ede595 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 23 Nov 2017 11:18:07 -0800 Subject: [PATCH 117/456] add surrounded regions. --- .../surrounded_regions/SurroundedRegions.java | 73 ++++++------------- 1 file changed, 23 insertions(+), 50 deletions(-) diff --git a/src/main/java/surrounded_regions/SurroundedRegions.java b/src/main/java/surrounded_regions/SurroundedRegions.java index 3858356..f76a951 100644 --- a/src/main/java/surrounded_regions/SurroundedRegions.java +++ b/src/main/java/surrounded_regions/SurroundedRegions.java @@ -1,63 +1,36 @@ package surrounded_regions; -import java.util.ArrayDeque; - public class SurroundedRegions { public class Solution { - private class Pos { - int x; - int y; - - Pos(int x, int y) { - this.x = x; - this.y = y; - } - } - - private boolean isOutOfBound(int x, int y, int rows, int columns) { - return x < 0 || y < 0 || x >= rows || y >= columns; - } - + public void solve(char[][] board) { - if (board.length == 0 || board[0].length == 0) { - return; - } - int rows = board.length; - int columns = board[0].length; - - ArrayDeque stack = new ArrayDeque(); - for (int i = 0; i < rows; i++) { - stack.offerLast(new Pos(i, 0)); - stack.offerLast(new Pos(i, columns - 1)); - } - for (int i = 0; i < columns; i++) { - stack.offerLast(new Pos(0, i)); - stack.offerLast(new Pos(rows - 1, i)); + for (int i = 0; i < board.length; ++i) { + for (int j = 0; j < board[i].length; ++j) { + if ((i == 0 || i == board.length - 1 || j == 0 || + j == board[i].length - 1) && board[i][j] == 'O') + solveDFS(board, i, j); + } } - - while (!stack.isEmpty()) { - Pos pos = stack.removeLast(); - int x = pos.x; - int y = pos.y; - if (isOutOfBound(x, y, rows, columns) || board[x][y] != 'O') { - continue; + for (int i = 0; i < board.length; ++i) { + for (int j = 0; j < board[i].length; ++j) { + if (board[i][j] == 'O') board[i][j] = 'X'; + if (board[i][j] == '$') board[i][j] = 'O'; } - board[x][y] = 'N'; - stack.offerLast(new Pos(x - 1, y)); - stack.offerLast(new Pos(x + 1, y)); - stack.offerLast(new Pos(x, y - 1)); - stack.offerLast(new Pos(x, y + 1)); } + } - for (int i = 0; i < rows; i++) { - for (int j = 0; j < columns; j++) { - if (board[i][j] == 'O') { - board[i][j] = 'X'; - } else if (board[i][j] == 'N') { - board[i][j] = 'O'; - } - } + private void solveDFS(char[][]board, int i, int j) { + if (board[i][j] == 'O') { + board[i][j] = '$'; + if (i > 0 && board[i - 1][j] == 'O') + solveDFS(board, i - 1, j); + if (j < board[i].length - 1 && board[i][j + 1] == 'O') + solveDFS(board, i, j + 1); + if (i < board.length - 1 && board[i + 1][j] == 'O') + solveDFS(board, i + 1, j); + if (j > 1 && board[i][j - 1] == 'O') + solveDFS(board, i, j - 1); } } } From 0e658960925a193aaada5c94f59b706ebcff7be8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 26 Nov 2017 01:04:26 -0800 Subject: [PATCH 118/456] add verify_preorder_btree --- .../surrounded_regions/SurroundedRegions.java | 2 +- .../VerifyPreorderBTree.java | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 src/main/java/verify_preorder_btree/VerifyPreorderBTree.java diff --git a/src/main/java/surrounded_regions/SurroundedRegions.java b/src/main/java/surrounded_regions/SurroundedRegions.java index f76a951..8118ced 100644 --- a/src/main/java/surrounded_regions/SurroundedRegions.java +++ b/src/main/java/surrounded_regions/SurroundedRegions.java @@ -3,7 +3,7 @@ public class SurroundedRegions { public class Solution { - + public void solve(char[][] board) { for (int i = 0; i < board.length; ++i) { for (int j = 0; j < board[i].length; ++j) { diff --git a/src/main/java/verify_preorder_btree/VerifyPreorderBTree.java b/src/main/java/verify_preorder_btree/VerifyPreorderBTree.java new file mode 100644 index 0000000..27ef296 --- /dev/null +++ b/src/main/java/verify_preorder_btree/VerifyPreorderBTree.java @@ -0,0 +1,28 @@ +package verify_preorder_btree; + +/** + * Created by lxie on 11/26/17. + */ +public class VerifyPreorderBTree { + public class Solution { + public boolean isPreorderBTree(String preorder) { + if (preorder.isEmpty()) return false; + String[] v = preorder.split(","); + int d = 0; + for (int i = 0; i < v.length - 1; ++i) { + if (v[i] == "#") { + if (d == 0) return false; + else --d; + } + else ++d; + } + return d != 0 ? false : v[v.length - 1] == "#"; + } + + } + + public static class UnitTest { + + } + +} From d9b336d3af101dd587a891f05a6a62090d3fdcf1 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 26 Nov 2017 17:09:45 -0800 Subject: [PATCH 119/456] add largest_bst_subtree --- .../LargestBSTSubtree.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/largest_bst_subtree/LargestBSTSubtree.java diff --git a/src/main/java/largest_bst_subtree/LargestBSTSubtree.java b/src/main/java/largest_bst_subtree/LargestBSTSubtree.java new file mode 100644 index 0000000..c998183 --- /dev/null +++ b/src/main/java/largest_bst_subtree/LargestBSTSubtree.java @@ -0,0 +1,54 @@ +package largest_bst_subtree; + +import common.TreeNode; + +/** + * Created by lxie on 11/26/17. + */ +public class LargestBSTSubtree { + public static class Solution { + public int largest(TreeNode root) { + int[] params = new int[3]; + params[0] = Integer.MIN_VALUE; params[1] = Integer.MAX_VALUE; params[2] = 0; // mn, mx, res + boolean d = isValidBST(root, params); + return params[2]; + } + + boolean isValidBST(TreeNode root, int[] params) { + if (root == null) return true; + + int[] leftParams = new int[3]; + leftParams[0] = Integer.MIN_VALUE; leftParams[1] = Integer.MAX_VALUE; leftParams[2] = 0; + boolean left = isValidBST(root.left, leftParams); + int[] rightParams = new int[3]; + rightParams[0] = Integer.MIN_VALUE; rightParams[1] = Integer.MAX_VALUE; rightParams[2] = 0; + boolean right = isValidBST(root.right, rightParams); + + if (left && right) { + if ((root.left == null || root.val >= leftParams[1]) && (root.right == null || root.val <= rightParams[0])) { + params[2] = leftParams[2] + rightParams[2] + 1; + params[0] = root.left != null ? leftParams[0] : root.val; // update ranges + params[1] = root.right != null ? rightParams[1] : root.val; + return true; + } + } + params[2] = Integer.max(leftParams[2], rightParams[2]); + return false; + } + + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + TreeNode root = new TreeNode(10); + root.left = new TreeNode(5); root.right = new TreeNode(15); + root.left.left = new TreeNode(1); root.left.right = new TreeNode(8); + root.right.right = new TreeNode(7); + + int res = sol.largest(root); + + System.out.println("result is " + res); + } +} From 35e1a2b085cfc901ce8320e89e67dd970af8a28f Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 29 Nov 2017 10:20:03 -0800 Subject: [PATCH 120/456] add find_duplicate_number --- .../FindDuplicateNumber.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/find_duplicate_number/FindDuplicateNumber.java diff --git a/src/main/java/find_duplicate_number/FindDuplicateNumber.java b/src/main/java/find_duplicate_number/FindDuplicateNumber.java new file mode 100644 index 0000000..e8bf18d --- /dev/null +++ b/src/main/java/find_duplicate_number/FindDuplicateNumber.java @@ -0,0 +1,30 @@ +package find_duplicate_number; + +/** + * Created by lxie on 11/29/17. + */ +public class FindDuplicateNumber { + + public class Solution { + public int findDuplicate(int[] nums) { + int low = 1, high = nums.length - 1; // from 1 to n + while (low < high) { + int mid = low + (high - low) / 2; + int cnt = 0; + for (int a : nums) { + if (a <= mid) ++cnt; + } + if (cnt <= mid) low = mid + 1; + else high = mid; + } + return low; + + } + } + + public static class UnitTest { + + } + + +} From 280f228772b0ebec744901077c5f01afc2acc196 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 29 Nov 2017 10:46:34 -0800 Subject: [PATCH 121/456] add flatten_2d_vector --- .../flatten_2d_vector/Flatten2DVector.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/flatten_2d_vector/Flatten2DVector.java diff --git a/src/main/java/flatten_2d_vector/Flatten2DVector.java b/src/main/java/flatten_2d_vector/Flatten2DVector.java new file mode 100644 index 0000000..05e07bc --- /dev/null +++ b/src/main/java/flatten_2d_vector/Flatten2DVector.java @@ -0,0 +1,37 @@ +package flatten_2d_vector; + +import java.util.Iterator; +import java.util.List; + +/** + * Created by lxie on 11/29/17. + */ +public class Flatten2DVector implements Iterator { + + private Iterator> i; + private Iterator j; + + public Flatten2DVector(List> vec2d) { + // Initialize your data structure here + i = vec2d.iterator(); + j = null; + } + + @Override + public Integer next() { + // Write your code here + hasNext(); + return j.next(); + } + + @Override + public boolean hasNext() { + // Write your code here + while ((j == null || !j.hasNext()) && i.hasNext()) + j = i.next().iterator(); + return j != null && j.hasNext(); + } + + @Override + public void remove() {} +} From d4ca659964b1ba0214616b36ead390b0b744ff0a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 2 Dec 2017 17:33:12 -0800 Subject: [PATCH 122/456] add longest_substring_most_k_distinct --- .../LongestSubstringKMost.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/longest_substring_most_k_distinct/LongestSubstringKMost.java diff --git a/src/main/java/longest_substring_most_k_distinct/LongestSubstringKMost.java b/src/main/java/longest_substring_most_k_distinct/LongestSubstringKMost.java new file mode 100644 index 0000000..2baa60a --- /dev/null +++ b/src/main/java/longest_substring_most_k_distinct/LongestSubstringKMost.java @@ -0,0 +1,38 @@ +package longest_substring_most_k_distinct; + +import java.util.HashMap; +import java.util.Map; + +import static java.lang.Math.max; + +/** + * Created by lxie on 12/2/17. + */ +public class LongestSubstringKMost { + public static class Solution { + private int LongestSubstringKMost(String s, int k) { + int res = 0, left = 0; + Map m = new HashMap<>(); + for (int i = 0; i < s.length(); ++i) { + if (!m.containsKey(s.charAt(i))) m.put(s.charAt(i), 1); + else + m.put(s.charAt(i), m.get(s.charAt(i))+1); + while (m.size() > k) { + if (m.get(s.charAt(left)) == 1) m.remove(s.charAt(left)); + else + m.put(s.charAt(left), m.get(s.charAt(left))-1); + ++left; + } + res = max(res, i - left + 1); + } + return res; + + } + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + System.out.println("result = " + sol.LongestSubstringKMost("eceba", 2)); + } +} From 3318f761b5ff13bf619270c7233f7fb3dd3e68b8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 3 Dec 2017 21:29:18 -0800 Subject: [PATCH 123/456] first_bad_version --- .../first_bad_version/FirstBadVersion.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/first_bad_version/FirstBadVersion.java diff --git a/src/main/java/first_bad_version/FirstBadVersion.java b/src/main/java/first_bad_version/FirstBadVersion.java new file mode 100644 index 0000000..85cfdea --- /dev/null +++ b/src/main/java/first_bad_version/FirstBadVersion.java @@ -0,0 +1,29 @@ +package first_bad_version; + +/** + * Created by lxie on 12/3/17. + */ +public class FirstBadVersion { + + public static class Solution { + public int firstBadVersion(int n) { + int left = 1, right = n; + while (left < right) { + int mid = left + (right - left) / 2; + if (isBadVersion(mid)) right = mid; + else left = mid + 1; + } + return left; + + } + + // stub function here + private boolean isBadVersion(int version) { + return false; + } + } + + public static class UnitTest { + + } +} From a2847c203c85b118ffd24e2ef1568da22e586d87 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 3 Dec 2017 23:19:38 -0800 Subject: [PATCH 124/456] add sliding_window_maximum --- .../SlidingWindowMax.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/sliding_window_maximum/SlidingWindowMax.java diff --git a/src/main/java/sliding_window_maximum/SlidingWindowMax.java b/src/main/java/sliding_window_maximum/SlidingWindowMax.java new file mode 100644 index 0000000..1f56ad0 --- /dev/null +++ b/src/main/java/sliding_window_maximum/SlidingWindowMax.java @@ -0,0 +1,31 @@ +package sliding_window_maximum; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * Created by lxie on 12/3/17. + */ +public class SlidingWindowMax { + + public static class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + List res = new ArrayList<>(); + LinkedList q = new LinkedList<>(); // idx + for (int i = 0; i < nums.length; ++i) { + // remove when nums[i-k] is maximum, otherwise already removed + if (!q.isEmpty() && q.getFirst() == i - k) q.removeFirst(); + while (!q.isEmpty() && nums[q.getLast()] < nums[i]) q.removeLast(); + q.add(i); + if (i >= k - 1) res.add(nums[q.getFirst()]); + } + return res.stream().mapToInt(i->i).toArray(); + } + } + + public static class UnitTest { + + } + +} From 798ab93a1da83cc06c45e1d368be85c088d7ad0e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 4 Dec 2017 23:42:31 -0800 Subject: [PATCH 125/456] add house_robber_II --- src/main/java/house_robber/HouseRobber.java | 24 ++++++-------- .../java/house_robber_II/HouseRobberII.java | 31 +++++++++++++++++++ 2 files changed, 41 insertions(+), 14 deletions(-) create mode 100644 src/main/java/house_robber_II/HouseRobberII.java diff --git a/src/main/java/house_robber/HouseRobber.java b/src/main/java/house_robber/HouseRobber.java index 00d62ad..41f9a33 100644 --- a/src/main/java/house_robber/HouseRobber.java +++ b/src/main/java/house_robber/HouseRobber.java @@ -4,22 +4,18 @@ public class HouseRobber { public class Solution { public int rob(int[] nums) { - if (nums.length == 0) { - return 0; + if (nums.length <= 1) return nums.length == 0 ? 0 : nums[0]; + int[] dp = new int[nums.length]; + dp[0] = nums[0]; dp[1] = Integer.max(nums[0], nums[1]); + for (int i = 2; i < nums.length; ++i) { + dp[i] = Integer.max(nums[i] + dp[i - 2], dp[i - 1]); } - if (nums.length < 2) { - return nums[0]; - } - int f1 = nums[0]; - int f2 = Math.max(nums[0], nums[1]); - for (int i = 2; i < nums.length; i++) { - // f(i) = max { f(i - 2) + nums[i], f(i - 1) } - int f = Math.max(f1 + nums[i], f2); - f1 = f2; - f2 = f; - } - return f2; + return dp[nums.length - 1]; } } + + public static class UnitTest { + + } } diff --git a/src/main/java/house_robber_II/HouseRobberII.java b/src/main/java/house_robber_II/HouseRobberII.java new file mode 100644 index 0000000..fb06d2f --- /dev/null +++ b/src/main/java/house_robber_II/HouseRobberII.java @@ -0,0 +1,31 @@ +package house_robber_II; + +/** + * Created by lxie on 12/4/17. + */ +public class HouseRobberII { + + public class Solution { + public int rob(int[] nums) { + if (nums.length <= 1) return nums.length == 0 ? 0 : nums[0]; + + return Integer.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1)); + } + + int rob(int[]nums, int left, int right) { + if (right == left) return nums[left]; + int[] dp = new int[right + 1]; + dp[left] = nums[left]; + dp[left + 1] = Integer.max(nums[left], nums[left + 1]); + for (int i = left + 2; i <= right; ++i) { + dp[i] = Integer.max(nums[i] + dp[i - 2], dp[i - 1]); + } + return dp[right]; + } + + } + + public static class UnitTest { + + } +} From 28ee4b1d50f63b07bccbceced9a3d116d18c303b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 6 Dec 2017 00:06:25 -0800 Subject: [PATCH 126/456] add house_robber_iii --- .../java/house_robber_III/HouseRobberIII.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/house_robber_III/HouseRobberIII.java diff --git a/src/main/java/house_robber_III/HouseRobberIII.java b/src/main/java/house_robber_III/HouseRobberIII.java new file mode 100644 index 0000000..d0d9026 --- /dev/null +++ b/src/main/java/house_robber_III/HouseRobberIII.java @@ -0,0 +1,39 @@ +package house_robber_III; + +import common.TreeNode; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 12/5/17. + */ +public class HouseRobberIII { + + public class Solution { + public int rob(TreeNode root) { + Map m = new HashMap(); + return dfs(root, m); + } + + int dfs(TreeNode root, Map m) { + if (root == null) return 0; + if (m.containsKey(root)) return m.get(root); + int val = 0; + if (root.left != null) { + val += dfs(root.left.left, m) + dfs(root.left.right, m); + } + if (root.right != null) { + val += dfs(root.right.left, m) + dfs(root.right.right, m); + } + val = Integer.max(val + root.val, dfs(root.left, m) + dfs(root.right, m)); + m.put(root, val); + return val; + } + + } + + public static class UnitTest { + + } +} From da3c2f65341e91c94c6b0c567228945dfd582343 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 6 Dec 2017 01:41:20 -0800 Subject: [PATCH 127/456] add lca_binary_tree --- .../LCABinaryTree.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/main/java/lowest_common_ancestor_BTree/LCABinaryTree.java diff --git a/src/main/java/lowest_common_ancestor_BTree/LCABinaryTree.java b/src/main/java/lowest_common_ancestor_BTree/LCABinaryTree.java new file mode 100644 index 0000000..dcb1b33 --- /dev/null +++ b/src/main/java/lowest_common_ancestor_BTree/LCABinaryTree.java @@ -0,0 +1,26 @@ +package lowest_common_ancestor_BTree; + +import common.TreeNode; + +/** + * Created by lxie on 12/6/17. + */ +public class LCABinaryTree { + + public class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || p == root || q == root) return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p , q); + if (left != null && right != null) return root; + return left != null ? left : right; + } + + } + + public static class UnitTest { + + } + + +} From 9389157c3c85f9650726b41553616fff47d1e765 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 7 Dec 2017 00:39:42 -0800 Subject: [PATCH 128/456] add LCA_BST --- .../LCABinarySearchTree.java | 24 +++++++++++++++++++ .../LCABinaryTree.java | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java rename src/main/java/{lowest_common_ancestor_BTree => LCA_Binary_Tree}/LCABinaryTree.java (93%) diff --git a/src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java b/src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java new file mode 100644 index 0000000..ae86927 --- /dev/null +++ b/src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java @@ -0,0 +1,24 @@ +package LCA_Binary_Search_Tree; + +import common.TreeNode; + +/** + * Created by lxie on 12/6/17. + */ +public class LCABinarySearchTree { + + public class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + while (true) { + if (root.val > Integer.max(p.val, q.val)) root = root.left; + else if (root.val < Integer.min(p.val, q.val)) root = root.right; + else break; + } + return root; + } + } + + public static class UnitTest { + + } +} diff --git a/src/main/java/lowest_common_ancestor_BTree/LCABinaryTree.java b/src/main/java/LCA_Binary_Tree/LCABinaryTree.java similarity index 93% rename from src/main/java/lowest_common_ancestor_BTree/LCABinaryTree.java rename to src/main/java/LCA_Binary_Tree/LCABinaryTree.java index dcb1b33..7f60229 100644 --- a/src/main/java/lowest_common_ancestor_BTree/LCABinaryTree.java +++ b/src/main/java/LCA_Binary_Tree/LCABinaryTree.java @@ -1,4 +1,4 @@ -package lowest_common_ancestor_BTree; +package LCA_Binary_Tree; import common.TreeNode; From 422f9c1ed2d3d49b164069bef423e58a854115c9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 7 Dec 2017 00:42:04 -0800 Subject: [PATCH 129/456] refactor LCA_xxx --- src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java | 2 +- src/main/java/LCA_Binary_Tree/LCABinaryTree.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java b/src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java index ae86927..a2e80d6 100644 --- a/src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java +++ b/src/main/java/LCA_Binary_Search_Tree/LCABinarySearchTree.java @@ -1,4 +1,4 @@ -package LCA_Binary_Search_Tree; +package lca_binary_search_tree; import common.TreeNode; diff --git a/src/main/java/LCA_Binary_Tree/LCABinaryTree.java b/src/main/java/LCA_Binary_Tree/LCABinaryTree.java index 7f60229..3bfa401 100644 --- a/src/main/java/LCA_Binary_Tree/LCABinaryTree.java +++ b/src/main/java/LCA_Binary_Tree/LCABinaryTree.java @@ -1,4 +1,4 @@ -package LCA_Binary_Tree; +package lca_binary_tree; import common.TreeNode; From 1754efc33f370467f38609421e5a73875bab20b3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 7 Dec 2017 01:20:18 -0800 Subject: [PATCH 130/456] add bomb_enemy --- src/main/java/bomb_enemy/BombEnemy.java | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/bomb_enemy/BombEnemy.java diff --git a/src/main/java/bomb_enemy/BombEnemy.java b/src/main/java/bomb_enemy/BombEnemy.java new file mode 100644 index 0000000..b87daac --- /dev/null +++ b/src/main/java/bomb_enemy/BombEnemy.java @@ -0,0 +1,40 @@ +package bomb_enemy; + +/** + * Created by lxie on 12/7/17. + */ +public class BombEnemy { + + public class Solution { + public int maxKilledEnemies(char[][] grid) { + if (grid == null || grid[0] == null) return 0; + int m = grid.length, n = grid[0].length, res = 0, rowCnt = 0; + int[] colCnt = new int[n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (j == 0 || grid[i][j - 1] == 'W') { + rowCnt = 0; + for (int k = j; k < n && grid[i][k] != 'W'; ++k) { + rowCnt += grid[i][k] == 'E' ? 1 : 0; + } + } + if (i == 0 || grid[i - 1][j] == 'W') { + colCnt[j] = 0; + for (int k = i; k < m && grid[k][j] != 'W'; ++k) { + colCnt[j] += grid[k][j] == 'E' ? 1 : 0; + } + } + if (grid[i][j] == '0') { + res = Integer.max(res, rowCnt + colCnt[j]); + } + } + } + return res; + + } + } + + public static class UnitTest { + + } +} From 700abf6f80c919124fe994d069d9f1c4eb488d18 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 8 Dec 2017 02:09:56 -0800 Subject: [PATCH 131/456] add serialize_deserialize_binary_tree --- .../SerializeDeserializeBTree.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java diff --git a/src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java b/src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java new file mode 100644 index 0000000..1a849fb --- /dev/null +++ b/src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java @@ -0,0 +1,70 @@ +package serialize_deserialize_binary_tree; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 12/7/17. + */ +public class SerializeDeserializeBTree { + + public static class Solution { + public static class Codec { + + // Encodes a tree to a single string. + public static String serialize(TreeNode root) { + String[] out = {""}; + serialize(root, out); + return out[0]; + } + + private static void serialize(TreeNode root, String[] out) { + if (root != null) { + out[0] += Integer.toString(root.val) + ' '; + serialize(root.left, out); + serialize(root.right, out); + } else { + out[0] += "# "; + } + } + + + // Decodes your encoded data to tree. + public static TreeNode deserialize(String data) { + if (data == null) return null; + String[] input = data.split("\\s+"); + List in = new ArrayList(Arrays.asList(input)); + TreeNode root = deserialize(in); + return root; + } + + private static TreeNode deserialize(List in) { + if (in == null || in.size() == 0) return null; + String val = in.get(0); in.remove(0); + if (val.compareTo("#") == 0 || val.compareTo("") == 0) + return null; + TreeNode root = new TreeNode(Integer.valueOf(val)); + root.left = deserialize(in); + root.right = deserialize(in); + return root; + } + + + } + + } + + public static void main(String[] args) { + TreeNode root = new TreeNode(1); + TreeNode left = new TreeNode(2); + TreeNode right = new TreeNode(3); + root.left = left; + root.right = right; + + System.out.println("result1 = " + Solution.Codec.serialize(root)); + System.out.println("result2 = " + Solution.Codec.deserialize("1 2 # # 3 # #")); + } +} From be866b2c70dcf256d7f6fb81d20eacaafe2a8bf9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 8 Dec 2017 11:44:47 -0800 Subject: [PATCH 132/456] modify serialize_deserialize_binary_tree --- .../SerializeDeserializeBTree.java | 91 ++++++++++++------- 1 file changed, 60 insertions(+), 31 deletions(-) diff --git a/src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java b/src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java index 1a849fb..2faf68f 100644 --- a/src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java +++ b/src/main/java/serialize_deserialize_binary_tree/SerializeDeserializeBTree.java @@ -2,9 +2,7 @@ import common.TreeNode; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.LinkedList; /** * Created by lxie on 12/7/17. @@ -14,41 +12,72 @@ public class SerializeDeserializeBTree { public static class Solution { public static class Codec { - // Encodes a tree to a single string. public static String serialize(TreeNode root) { - String[] out = {""}; - serialize(root, out); - return out[0]; - } + if(root==null){ + return ""; + } + + StringBuilder sb = new StringBuilder(); - private static void serialize(TreeNode root, String[] out) { - if (root != null) { - out[0] += Integer.toString(root.val) + ' '; - serialize(root.left, out); - serialize(root.right, out); - } else { - out[0] += "# "; + LinkedList queue = new LinkedList(); + + queue.add(root); + while(!queue.isEmpty()){ + TreeNode t = queue.poll(); + if(t!=null){ + sb.append(String.valueOf(t.val) + ","); + queue.add(t.left); + queue.add(t.right); + }else{ + sb.append("#,"); + } } - } + sb.deleteCharAt(sb.length()-1); + System.out.println(sb.toString()); + return sb.toString(); + } // Decodes your encoded data to tree. public static TreeNode deserialize(String data) { - if (data == null) return null; - String[] input = data.split("\\s+"); - List in = new ArrayList(Arrays.asList(input)); - TreeNode root = deserialize(in); - return root; - } - - private static TreeNode deserialize(List in) { - if (in == null || in.size() == 0) return null; - String val = in.get(0); in.remove(0); - if (val.compareTo("#") == 0 || val.compareTo("") == 0) + if(data==null || data.length()==0) return null; - TreeNode root = new TreeNode(Integer.valueOf(val)); - root.left = deserialize(in); - root.right = deserialize(in); + + String[] arr = data.split(","); + TreeNode root = new TreeNode(Integer.parseInt(arr[0])); + + + LinkedList queue = new LinkedList(); + queue.add(root); + + int i=1; + while(!queue.isEmpty()){ + TreeNode t = queue.poll(); + + if(t==null) + continue; + + if(!arr[i].equals("#")){ + t.left = new TreeNode(Integer.parseInt(arr[i])); + queue.offer(t.left); + + }else{ + t.left = null; + queue.offer(null); + } + i++; + + if(!arr[i].equals("#")){ + t.right = new TreeNode(Integer.parseInt(arr[i])); + queue.offer(t.right); + + }else{ + t.right = null; + queue.offer(null); + } + i++; + } + return root; } @@ -65,6 +94,6 @@ public static void main(String[] args) { root.right = right; System.out.println("result1 = " + Solution.Codec.serialize(root)); - System.out.println("result2 = " + Solution.Codec.deserialize("1 2 # # 3 # #")); + System.out.println("result2 = " + Solution.Codec.deserialize("1,2,3,#,#,#,#")); } } From af5f3c39c564192842d560b0a170e1af71fa3542 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 9 Dec 2017 15:41:33 -0800 Subject: [PATCH 133/456] add moving_average_data_stream --- .../MovingAvgDataStream.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/moving_average_data_stream/MovingAvgDataStream.java diff --git a/src/main/java/moving_average_data_stream/MovingAvgDataStream.java b/src/main/java/moving_average_data_stream/MovingAvgDataStream.java new file mode 100644 index 0000000..e710226 --- /dev/null +++ b/src/main/java/moving_average_data_stream/MovingAvgDataStream.java @@ -0,0 +1,30 @@ +package moving_average_data_stream; + +import java.util.LinkedList; + +/** + * Created by lxie on 12/9/17. + */ +public class MovingAvgDataStream { + private LinkedList queue = new LinkedList<>(); + private int size; + private double sum; + + public MovingAvgDataStream(int size) { + this.size = size; + } + + public double next(int val) { + if (queue.size() >= size) { + sum -= queue.getFirst(); + queue.remove(0); + } + queue.add(val); + sum += val; + return sum/queue.size(); + } + + public static class UnitTest { + + } +} From e0e5c715e29c4b73133eabe2dad18d5144a5e05a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 9 Dec 2017 20:28:41 -0800 Subject: [PATCH 134/456] add rearrange_string_k_distance --- .../RearrangeStringKDistance.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java diff --git a/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java b/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java new file mode 100644 index 0000000..71a62ff --- /dev/null +++ b/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java @@ -0,0 +1,54 @@ +package rearrange_string_k_distance; + +import javafx.util.Pair; + +import java.util.*; + +/** + * Created by lxie on 12/9/17. + */ +public class RearrangeStringKDistance { + public static class Solution { + public String RearrangeString(String str, int k) { + if (k == 0) return str; + String res = ""; + int len = str.length(); + Map m = new HashMap<>(); + PriorityQueue> q = new PriorityQueue<>(); + for (char a : str.toCharArray()) { + if (!m.containsKey(a)) m.put(a, 1); + else + m.put(a, m.get(a)+1); + }; + for (Map.Entry entry : m.entrySet()) { + q.add(new Pair(entry.getValue(), entry.getKey())); + } + while (!q.isEmpty()) { + List> v = new ArrayList<>(); // for temp store + int cnt = Integer.min(k, len); + for (int i = 0; i < cnt; ++i) { + if (q.isEmpty()) return ""; + Pair t = q.peek(); q.poll(); // highest count first + res += t.getValue(); + int count = t.getKey(); + if (--count > 0) v.add(t); + --len; + } + for (Pair a : v) q.add(a); + } + return res; + + } + } + + public static class UnitTest { + + } + + + + + + + +} From 9473d74d9573c34c23561db275ed581b38f02129 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 11 Dec 2017 10:25:37 -0800 Subject: [PATCH 135/456] add product_array_except_self --- .../ProductArrayExceptSelf.java | 29 +++++++++++++++++++ .../RearrangeStringKDistance.java | 6 ---- 2 files changed, 29 insertions(+), 6 deletions(-) create mode 100644 src/main/java/product_array_except_self/ProductArrayExceptSelf.java diff --git a/src/main/java/product_array_except_self/ProductArrayExceptSelf.java b/src/main/java/product_array_except_self/ProductArrayExceptSelf.java new file mode 100644 index 0000000..a1bd7ad --- /dev/null +++ b/src/main/java/product_array_except_self/ProductArrayExceptSelf.java @@ -0,0 +1,29 @@ +package product_array_except_self; + +/** + * Created by lxie on 12/11/17. + */ +public class ProductArrayExceptSelf { + + public class Solution { + public int[] productExceptSelf(int[] nums) { + int[] res = new int[nums.length]; + for (int i = 0; i < nums.length; ++i) res[i] = 1; + for (int i = 1; i < nums.length; ++i) { + res[i] = res[i-1] * nums[i-1]; + } + int right = 1; + for (int i = nums.length - 1; i >= 0; --i) { + res[i] *= right; + right *= nums[i]; + } + return res; + + } + } + + public static class UnitTest { + + } + +} diff --git a/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java b/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java index 71a62ff..e6f3726 100644 --- a/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java +++ b/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java @@ -45,10 +45,4 @@ public static class UnitTest { } - - - - - - } From 987fee3292476e4d55d09a5d642e4ca287981479 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 11 Dec 2017 22:39:06 -0800 Subject: [PATCH 136/456] ways_to_add_parentheses --- .../DiffWaysAddParentheses.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/ways_to_add_parentheses/DiffWaysAddParentheses.java diff --git a/src/main/java/ways_to_add_parentheses/DiffWaysAddParentheses.java b/src/main/java/ways_to_add_parentheses/DiffWaysAddParentheses.java new file mode 100644 index 0000000..cf401f6 --- /dev/null +++ b/src/main/java/ways_to_add_parentheses/DiffWaysAddParentheses.java @@ -0,0 +1,36 @@ +package ways_to_add_parentheses; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 12/11/17. + */ +public class DiffWaysAddParentheses { + public class Solution { + public List diffWaysToCompute(String input) { + List res = new ArrayList<>(); + char[] input1 = input.toCharArray(); + for (int i = 0; i < input.length(); ++i) { + if (input1[i] == '+' || input1[i] == '-' || input1[i] == '*') { + List left = diffWaysToCompute(input.substring(0, i)); + List right = diffWaysToCompute(input.substring(i + 1)); + for (int j = 0; j < left.size(); ++j) { + for (int k = 0; k < right.size(); ++k) { + if (input1[i] == '+') res.add(left.get(j) + right.get(k)); + else if (input1[i] == '-') res.add(left.get(j) - right.get(k)); + else res.add(left.get(j) * right.get(k)); + } + } + } + } + if (res.isEmpty()) res.add(Integer.parseInt(input)); // input is an integer + return res; + } + } + + public static class UnitTest { + + } + +} From 017793f3fa78e8fcac8535fb66f33d690b391708 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 16 Dec 2017 14:58:14 -0800 Subject: [PATCH 137/456] add shortest_palindrome --- .../ShortestPalindrome.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/main/java/shortest_palindrome/ShortestPalindrome.java diff --git a/src/main/java/shortest_palindrome/ShortestPalindrome.java b/src/main/java/shortest_palindrome/ShortestPalindrome.java new file mode 100644 index 0000000..6c237a1 --- /dev/null +++ b/src/main/java/shortest_palindrome/ShortestPalindrome.java @@ -0,0 +1,26 @@ +package shortest_palindrome; + +/** + * Created by lxie on 12/15/17. + */ +public class ShortestPalindrome { + public class Solution { + public String shortestPalindrome(String s) { + String r = s; + r = new StringBuilder(r).reverse().toString(); + char[] t = (s + "#" + r).toCharArray(); + int[] p = new int[t.length]; + for (int i = 1; i < t.length; ++i) { + int j = p[i - 1]; + while (j > 0 && t[i] != t[j]) j = p[j - 1]; + p[i] = (j += (t[i] == t[j] ? 1 : 0)); + } + return r.substring(0, s.length() - p[t.length - 1]) + s; + } + + } + + public static class UnitTest { + + } +} From e061a6a03014b23eb9e87e972cd329222bbe5afa Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 2 Jan 2018 14:35:38 -0800 Subject: [PATCH 138/456] add skyline problem --- .../java/skyline_problem/SkylineProblem.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/main/java/skyline_problem/SkylineProblem.java diff --git a/src/main/java/skyline_problem/SkylineProblem.java b/src/main/java/skyline_problem/SkylineProblem.java new file mode 100644 index 0000000..9d34d3f --- /dev/null +++ b/src/main/java/skyline_problem/SkylineProblem.java @@ -0,0 +1,64 @@ +package skyline_problem; + +import com.google.common.collect.TreeMultiset; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +/** + * Created by lxie on 1/2/18. + */ +public class SkylineProblem { + + public static class Solution { + public List getSkyline(int[][] buildings) { + List h = new ArrayList<>(); + List res = new ArrayList<>(); + TreeMultiset m = TreeMultiset.create(); // sort elements + int pre = 0, cur = 0; + for (int[] a : buildings) { + int[] aa = {a[0], -a[2]}; + h.add(aa); + int[] bb = {a[1], a[2]}; + h.add(bb); + } + + Collections.sort(h, new Comparator() { + public int compare(int[] arr1, int[] arr2) { + if (arr1[0] == arr2[0]) + return arr1[1] - arr2[1]; + else + return arr1[0] - arr2[0]; + } + }); + + m.add(0); + for (int[] a : h) { + if (a[1] < 0) m.add(-a[1]); + else m.remove(a[1]); + cur = m.lastEntry().getElement(); + if (cur != pre) { + int[] aa = {a[0], cur}; + res.add(aa); + pre = cur; + } + } + return res; + } + + } + + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + int[][] buildings = {{2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8}}; + List result = sol.getSkyline(buildings); + for (int[] a : result) { + System.out.println("[" + a[0] + ", " + a[1] + "], "); + } + + } +} \ No newline at end of file From 646e555bf3ec45e85e95e5ec9fb5a1dd0da2a39f Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 2 Jan 2018 14:35:38 -0800 Subject: [PATCH 139/456] add skyline problem --- src/main/java/.DS_Store | Bin 0 -> 6148 bytes .../java/skyline_problem/SkylineProblem.java | 9 +++------ 2 files changed, 3 insertions(+), 6 deletions(-) create mode 100644 src/main/java/.DS_Store diff --git a/src/main/java/.DS_Store b/src/main/java/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..174012ef3236396299aa481bdfedbba93e562c7f GIT binary patch literal 6148 zcmeH~F-`+P3`OmbA`(qX%DF%a#07>`a)Mld0x1m&5)#zgac%y$ohaEAqN9kuCC}gW z*t6PKtk-7d!{_Ux+1kujaH@TCnH%@%Gh0;T4(dGP?frPjYdh`DiY5WpE^K4ZU;B^a zRsF_>NzCnO5}6#PTM-Ze5fA|p5P?4lpl8!o_o-S%Km|%S&n$Cyk0t{X1RF{7+z2InovBRj`LfjoA*?$ zA|L|S1UP%c*6jZ~_%HK6b7UeQ0yj#)m)rezz{^!{oxLV|ZG*qSPlnt`#}cg=8m$;N eY{d^3d5zcD@1=&s3 literal 0 HcmV?d00001 diff --git a/src/main/java/skyline_problem/SkylineProblem.java b/src/main/java/skyline_problem/SkylineProblem.java index 9d34d3f..5b1ba83 100644 --- a/src/main/java/skyline_problem/SkylineProblem.java +++ b/src/main/java/skyline_problem/SkylineProblem.java @@ -19,10 +19,8 @@ public List getSkyline(int[][] buildings) { TreeMultiset m = TreeMultiset.create(); // sort elements int pre = 0, cur = 0; for (int[] a : buildings) { - int[] aa = {a[0], -a[2]}; - h.add(aa); - int[] bb = {a[1], a[2]}; - h.add(bb); + h.add(new int[] {a[0], -a[2]}); + h.add(new int[] {a[1], a[2]}); } Collections.sort(h, new Comparator() { @@ -40,8 +38,7 @@ public int compare(int[] arr1, int[] arr2) { else m.remove(a[1]); cur = m.lastEntry().getElement(); if (cur != pre) { - int[] aa = {a[0], cur}; - res.add(aa); + res.add(new int[] {a[0], cur} ); pre = cur; } } From f1667df3a014acc209683db3231fc1a5ac86dc7d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 2 Jan 2018 16:57:59 -0800 Subject: [PATCH 140/456] add palindrome linked list. --- .../PalindromeLinkedList.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/palindrome_linked_list/PalindromeLinkedList.java diff --git a/src/main/java/palindrome_linked_list/PalindromeLinkedList.java b/src/main/java/palindrome_linked_list/PalindromeLinkedList.java new file mode 100644 index 0000000..56b5ea7 --- /dev/null +++ b/src/main/java/palindrome_linked_list/PalindromeLinkedList.java @@ -0,0 +1,31 @@ +package palindrome_linked_list; + +import common.ListNode; + +/** + * Created by lxie on 1/2/18. + */ +public class PalindromeLinkedList { + + public boolean isPalindrome(ListNode head) { + if (head == null || head.next == null) return true; + ListNode slow = head, fast = head; + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + } + ListNode last = slow.next, pre = head; + while (last.next != null) { + ListNode tmp = last.next; + last.next = tmp.next; + tmp.next = slow.next; + slow.next = tmp; + } + while (slow.next != null) { + slow = slow.next; + if (pre.val != slow.val) return false; + pre = pre.next; + } + return true; + } +} From f0c4ad15443a02382f97c6c97558802ffbc600c9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 8 Jan 2018 10:51:03 -0800 Subject: [PATCH 141/456] add wiggle_sort --- src/main/java/wiggle_sort/WiggleSort.java | 24 +++++++++++++++++ .../java/wiggle_sort_II/WiggleSortII.java | 27 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/main/java/wiggle_sort/WiggleSort.java create mode 100644 src/main/java/wiggle_sort_II/WiggleSortII.java diff --git a/src/main/java/wiggle_sort/WiggleSort.java b/src/main/java/wiggle_sort/WiggleSort.java new file mode 100644 index 0000000..f19138f --- /dev/null +++ b/src/main/java/wiggle_sort/WiggleSort.java @@ -0,0 +1,24 @@ +package wiggle_sort; + +/** + * Created by lxie on 1/8/18. + */ +public class WiggleSort { + + public void wiggleSort(int[] nums) { + // Write your code here + for(int i=1; i nums[i-1]))) { + swap(nums, i-1, i); + } + } + } + + public void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } + +} diff --git a/src/main/java/wiggle_sort_II/WiggleSortII.java b/src/main/java/wiggle_sort_II/WiggleSortII.java new file mode 100644 index 0000000..7eef9df --- /dev/null +++ b/src/main/java/wiggle_sort_II/WiggleSortII.java @@ -0,0 +1,27 @@ +package wiggle_sort_II; + +import java.util.Arrays; + +/** + * Created by lxie on 1/8/18. + */ +public class WiggleSortII { + + public static void wiggleSort(int[] nums) { + int[] tmp = Arrays.copyOf(nums, nums.length) ; + int n = nums.length, k = (n + 1) / 2, j = n; + Arrays.sort(tmp); + for (int i = 0; i < n; ++i) { + nums[i] = (i & 1) != 0 ? tmp[--j] : tmp[--k]; + } + } + + public static void main(String[] args) { + int[] nums = {1, 5, 1, 1, 6, 4}; + wiggleSort(nums); + for (int i : nums) { + System.out.print(i + ", "); + } + + } +} From c09d2b209c6eaba05f835da159d3a6ff66eadee9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 8 Jan 2018 16:05:38 -0800 Subject: [PATCH 142/456] add perfect_squares --- .../java/PerfectSquares/PerfectSquares.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/PerfectSquares/PerfectSquares.java diff --git a/src/main/java/PerfectSquares/PerfectSquares.java b/src/main/java/PerfectSquares/PerfectSquares.java new file mode 100644 index 0000000..e284ee7 --- /dev/null +++ b/src/main/java/PerfectSquares/PerfectSquares.java @@ -0,0 +1,22 @@ +package PerfectSquares; + +/** + * Created by lxie on 1/8/18. + */ +public class PerfectSquares { + + public class Solution { + public int numSquares(int n) { + int[] dp = new int[n+1]; + for (int i=0; i Date: Mon, 8 Jan 2018 16:05:38 -0800 Subject: [PATCH 143/456] add perfect_squares --- .../java/perfect_squares/PerfectSquares.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/java/perfect_squares/PerfectSquares.java diff --git a/src/main/java/perfect_squares/PerfectSquares.java b/src/main/java/perfect_squares/PerfectSquares.java new file mode 100644 index 0000000..a1fa2eb --- /dev/null +++ b/src/main/java/perfect_squares/PerfectSquares.java @@ -0,0 +1,22 @@ +package perfect_squares; + +/** + * Created by lxie on 1/8/18. + */ +public class PerfectSquares { + + public class Solution { + public int numSquares(int n) { + int[] dp = new int[n+1]; + for (int i=0; i Date: Mon, 8 Jan 2018 16:05:38 -0800 Subject: [PATCH 144/456] add perfect_squares --- .../java/PerfectSquares/PerfectSquares.java | 22 ------------------- 1 file changed, 22 deletions(-) delete mode 100644 src/main/java/PerfectSquares/PerfectSquares.java diff --git a/src/main/java/PerfectSquares/PerfectSquares.java b/src/main/java/PerfectSquares/PerfectSquares.java deleted file mode 100644 index e284ee7..0000000 --- a/src/main/java/PerfectSquares/PerfectSquares.java +++ /dev/null @@ -1,22 +0,0 @@ -package PerfectSquares; - -/** - * Created by lxie on 1/8/18. - */ -public class PerfectSquares { - - public class Solution { - public int numSquares(int n) { - int[] dp = new int[n+1]; - for (int i=0; i Date: Tue, 9 Jan 2018 01:02:49 -0800 Subject: [PATCH 145/456] add best_time_to_buy_and_sell_stock_cool_down --- .../BestTimetoBuyandSellStockCoolDown.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/best_time_to_buy_and_sell_stock_cool_down/BestTimetoBuyandSellStockCoolDown.java diff --git a/src/main/java/best_time_to_buy_and_sell_stock_cool_down/BestTimetoBuyandSellStockCoolDown.java b/src/main/java/best_time_to_buy_and_sell_stock_cool_down/BestTimetoBuyandSellStockCoolDown.java new file mode 100644 index 0000000..4dd1eb8 --- /dev/null +++ b/src/main/java/best_time_to_buy_and_sell_stock_cool_down/BestTimetoBuyandSellStockCoolDown.java @@ -0,0 +1,18 @@ +package best_time_to_buy_and_sell_stock_cool_down; + +public class BestTimetoBuyandSellStockCoolDown { + + public class Solution { + public int maxProfit(int[] prices) { + int buy = Integer.MIN_VALUE, pre_buy = 0, sell = 0, pre_sell = 0; + for (int price : prices) { + pre_buy = buy; + buy = Integer.max(pre_sell - price, pre_buy); + pre_sell = sell; + sell = Integer.max(pre_buy + price, pre_sell); + } + return sell; + } + } +} + From 25bf2141f9f2fe4c06ae53c63d50f99483c622e0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 9 Jan 2018 14:10:51 -0800 Subject: [PATCH 146/456] add minimum_height_trees --- .../MinimumHeightTrees.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/minimum_height_trees/MinimumHeightTrees.java diff --git a/src/main/java/minimum_height_trees/MinimumHeightTrees.java b/src/main/java/minimum_height_trees/MinimumHeightTrees.java new file mode 100644 index 0000000..22b3fe0 --- /dev/null +++ b/src/main/java/minimum_height_trees/MinimumHeightTrees.java @@ -0,0 +1,40 @@ +package minimum_height_trees; + +import java.util.*; + +/** + * Created by lxie on 1/9/18. + */ +public class MinimumHeightTrees { + + class Solution { + public List findMinHeightTrees(int n, int[][] edges) { + if (n == 1) return Collections.singletonList(0); + List leaves = new ArrayList<>(); + List> adj = new ArrayList<>(n); + for (int i = 0; i < n; ++i) adj.add(new HashSet<>()); + for (int[] edge : edges) { + adj.get(edge[0]).add(edge[1]); + adj.get(edge[1]).add(edge[0]); + } + for (int i = 0; i < n; ++i) { + if (adj.get(i).size() == 1) leaves.add(i); + } + while (n > 2) { + n -= leaves.size(); + List newLeaves = new ArrayList<>(); + for (int i : leaves) { + int t = adj.get(i).iterator().next(); + adj.get(t).remove(i); + if (adj.get(t).size() == 1) newLeaves.add(t); + } + leaves = newLeaves; + } + return leaves; + } + } + + public static class UnitTest { + + } +} From ef7333db1b3c3ac4d88eeb1c2dd67168354c4cdf Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 10 Jan 2018 10:34:03 -0800 Subject: [PATCH 147/456] add number_connected_components_in_undirected_graph --- .../ConnectedComponentsGraph.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/connected_components_in_undirected_graph/ConnectedComponentsGraph.java diff --git a/src/main/java/connected_components_in_undirected_graph/ConnectedComponentsGraph.java b/src/main/java/connected_components_in_undirected_graph/ConnectedComponentsGraph.java new file mode 100644 index 0000000..b104a57 --- /dev/null +++ b/src/main/java/connected_components_in_undirected_graph/ConnectedComponentsGraph.java @@ -0,0 +1,52 @@ +package connected_components_in_undirected_graph; + +import java.util.*; + +/** + * Created by lxie on 1/10/18. + */ +public class ConnectedComponentsGraph { + + class Solution { + public int NumberOfConnectedComponents(int n, int[][] edges) { + if (n == 0) return 0; + int res = 0; + List> g = new ArrayList<>(n); + List v = new ArrayList<>(n); + for (int i = 0; i < n; ++i) { + g.add(new HashSet<>()); + v.add(false); + } + for (int[] edge : edges) { + g.get(edge[0]).add(edge[1]); + g.get(edge[1]).add(edge[0]); + } + + for (int i = 0; i < n; ++i) { + if (v.get(i) == false) { + ++res; + dfs(g, v, i); + } + } + return res; + } + + void dfs(List> g, List v, int i) { + if (v.get(i) == true) return; + v.set(i, true); + for (int j : g.get(i)) { + dfs(g, v, j); + } + } + + + } + + public static class UnitTest { + + } + + + + +} From de71bbb0cc9b3afd78e0ce7cc53e0092a054f1aa Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 10 Jan 2018 16:34:41 -0800 Subject: [PATCH 148/456] topk_frequent_elements --- .../TopkFrequentElements.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/topk_frequent_elements/TopkFrequentElements.java diff --git a/src/main/java/topk_frequent_elements/TopkFrequentElements.java b/src/main/java/topk_frequent_elements/TopkFrequentElements.java new file mode 100644 index 0000000..ae4a77d --- /dev/null +++ b/src/main/java/topk_frequent_elements/TopkFrequentElements.java @@ -0,0 +1,44 @@ +package topk_frequent_elements; + +import java.util.*; + +/** + * Created by lxie on 1/10/18. + */ +public class TopkFrequentElements { + + class Solution { + public List topKFrequent(int[] nums, int k) { + List res = new ArrayList<>(); + Map m = new HashMap<>(); + PairComparator comparator = new PairComparator(); + PriorityQueue q = new PriorityQueue<>(100, comparator); + for (int a : nums) { + if (!m.containsKey(a)) m.put(a, 1); + else + m.put(a, m.get(a)+1); + }; + for (Map.Entry entry : m.entrySet()) { + q.add(new int[] {entry.getValue(), entry.getKey()}); + } + while (!q.isEmpty() && k > 0) { + res.add(q.poll()[1]); + k--; + } + + return res; + } + + class PairComparator implements Comparator { + @Override + public int compare(int[] p1, int[] p2) { + return p2[0] - p1[0]; // from high to low + } + } + } + + public static class UnitTest { + + } + +} From d93ec2eab5c6fb421020b9fe93ac219dbd7fd2e6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 11 Jan 2018 01:50:33 -0800 Subject: [PATCH 149/456] stream_disjoint_intervals --- .../StreamAsDisjointIntervals.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/main/java/stream_disjoint_intervals/StreamAsDisjointIntervals.java diff --git a/src/main/java/stream_disjoint_intervals/StreamAsDisjointIntervals.java b/src/main/java/stream_disjoint_intervals/StreamAsDisjointIntervals.java new file mode 100644 index 0000000..4ee1ed1 --- /dev/null +++ b/src/main/java/stream_disjoint_intervals/StreamAsDisjointIntervals.java @@ -0,0 +1,61 @@ +package stream_disjoint_intervals; + +import common.Interval; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 1/11/18. + */ +public class StreamAsDisjointIntervals { + + /** + * Definition for an interval. + * public class Interval { + * int start; + * int end; + * Interval() { start = 0; end = 0; } + * Interval(int s, int e) { start = s; end = e; } + * } + */ + class SummaryRanges { + + private List v = new ArrayList<>(); + + /** Initialize your data structure here. */ + public SummaryRanges() { + + } + + public void addNum(int val) { + Interval cur = new Interval(val, val); + List res = new ArrayList<>(); + int pos = 0; + for (Interval a : v) { + if (cur.end + 1 < a.start) { + res.add(a); + } else if (cur.start > a.end + 1) { + res.add(a); + ++pos; + } else { + cur.start = Integer.min(cur.start, a.start); + cur.end = Integer.max(cur.end, a.end); + } + } + res.add(pos, cur); + v = res; + } + + public List getIntervals() { + return v; + } + } + + + public static class UnitTest { + + } + + +} From ada15b96af15110c2db1be48c93abb3fa066cf87 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 11 Jan 2018 11:34:30 -0800 Subject: [PATCH 150/456] add intersection_of_xxx --- .../IntersectionOfTwoArrays.java | 40 +++++++++++++++++++ .../IntersectionofTwoLinkedLists.java | 34 +++------------- 2 files changed, 46 insertions(+), 28 deletions(-) create mode 100644 src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java diff --git a/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java b/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java new file mode 100644 index 0000000..4bae03b --- /dev/null +++ b/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java @@ -0,0 +1,40 @@ +package intersection_of_two_arrays; + +import com.google.common.primitives.Ints; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 1/11/18. + */ +public class IntersectionOfTwoArrays { + + public class Solution { + public int[] intersection(int[] nums1, int[] nums2) { + List res = new ArrayList<>(); + Arrays.sort(nums1); Arrays.sort(nums2); + + int i = 0, j = 0; + while (i < nums1.length && j < nums2.length) { + if (nums1[i] < nums2[j]) ++i; + else if (nums1[i] > nums2[j]) ++j; + else { + if (res.size() == 0 || res.get(res.size()-1) != nums1[i]) { + res.add(nums1[i]); + } + ++i; ++j; + } + } + return Ints.toArray(res); + } + + } + + public static class UnitTest { + + + + } +} diff --git a/src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java b/src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java index 8a54dc6..383be9a 100644 --- a/src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java +++ b/src/main/java/intersection_of_two_linked_lists/IntersectionofTwoLinkedLists.java @@ -6,35 +6,13 @@ public class IntersectionofTwoLinkedLists { public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { - if (headA == null) { - return null; + if (headA == null || headB == null) return null; + ListNode a = headA, b = headB; + while (a != b) { + a = (a != null) ? a.next : headB; + b = (b != null) ? b.next : headA; } - ListNode tailA = headA; - while (tailA.next != null) { - tailA = tailA.next; - } - tailA.next = headB; - - // Find the beginning of the cycle - ListNode fast = headA; - ListNode slow = headA; - do { - if (fast == null || fast.next == null) { - tailA.next = null; - return null; - } - fast = fast.next.next; - slow = slow.next; - if (slow == fast) { - fast = headA; - while (fast != slow) { - fast = fast.next; - slow = slow.next; - } - tailA.next = null; - return fast; - } - } while (true); + return a; // either intersection or null } } From 1e5b9591003ae3a2e9d269ff3bbf77e05f41da02 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 11 Jan 2018 17:00:32 -0800 Subject: [PATCH 151/456] add intersection_of_xxx --- .../IntersectionOfTwoArrays.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java b/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java index 4bae03b..9440bf4 100644 --- a/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java +++ b/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java @@ -1,7 +1,12 @@ package intersection_of_two_arrays; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List;<<<<<<< HEAD import com.google.common.primitives.Ints; +======= +>>>>>>> add intersection_of_xxx import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -27,7 +32,7 @@ public int[] intersection(int[] nums1, int[] nums2) { ++i; ++j; } } - return Ints.toArray(res); + return res.stream().mapToInt(k->k).toArray(); } } From eec357ddb2ef9d9208e959fbe6b09a2c4be790d6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 11 Jan 2018 17:00:32 -0800 Subject: [PATCH 152/456] add intersection_of_xxx --- .../intersection_of_two_arrays/IntersectionOfTwoArrays.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java b/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java index 4bae03b..956e1d0 100644 --- a/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java +++ b/src/main/java/intersection_of_two_arrays/IntersectionOfTwoArrays.java @@ -1,7 +1,5 @@ package intersection_of_two_arrays; -import com.google.common.primitives.Ints; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -27,7 +25,7 @@ public int[] intersection(int[] nums1, int[] nums2) { ++i; ++j; } } - return Ints.toArray(res); + return res.stream().mapToInt(k->k).toArray(); } } From 87f284ec1e6ba7e45cd14c2a63c81fccd792e482 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 12 Jan 2018 10:31:22 -0800 Subject: [PATCH 153/456] add comments for alien_dict --- .../alien_dictionary/AlienDictionary.java | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/main/java/alien_dictionary/AlienDictionary.java diff --git a/src/main/java/alien_dictionary/AlienDictionary.java b/src/main/java/alien_dictionary/AlienDictionary.java new file mode 100644 index 0000000..0a8d8d1 --- /dev/null +++ b/src/main/java/alien_dictionary/AlienDictionary.java @@ -0,0 +1,86 @@ +package alien_dictionary; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by lxie on 1/12/18. + */ +public class AlienDictionary { + + public class Solution { + public class Node { + public int degree; + public ArrayList neighbour = new ArrayList(); + void Node() { + degree = 0; + } + } + public String alienOrder(String[] words) { + Node[] node = new Node[26]; + boolean[] happen = new boolean[26]; // avoid duplicates, false by default + for (int i = 0; i < 26; i++) { + node[i] = new Node(); + } + //Build the Graph + for (int i = 0; i < words.length; i++) { + int startPoint = 0, endPoint = 0; + for (int j = 0; j < words[i].length(); j++) { + happen[charToInt(words[i].charAt(j))] = true; + } + if (i != words.length - 1) { + for (int j = 0; j < Math.min(words[i].length(), words[i + 1].length()); j++) { + if (words[i].charAt(j) != words[i + 1].charAt(j)) { + startPoint = charToInt(words[i].charAt(j)); + endPoint = charToInt(words[i + 1].charAt(j)); + break; + } + } + } + if (startPoint != endPoint) { + node[startPoint].neighbour.add(endPoint); + node[endPoint].degree++; + } + } + //Topological Sort + Queue queue = new LinkedList(); + String ans = ""; + for (int i = 0; i < 26; i++) { + if (node[i].degree == 0 && happen[i]) { + queue.offer(i); + ans = ans + intToChar(i); + } + } + while (!queue.isEmpty()) { + int now = queue.poll(); + for (int i : node[now].neighbour) { + node[i].degree--; + if (node[i].degree == 0) { + queue.offer(i); + ans = ans + intToChar(i); + } + } + } + for (int i = 0; i < 26; i++) { + if (node[i].degree != 0) { + return ""; + } + } + return ans; + } + public char intToChar(int i) { + return (char)('a' + i); + } + public int charToInt(char ch) { + return ch - 'a'; + } + + } + + public static class UnitTest { + + } + + +} From 5a0263ba422c1ef19538781ba68ad7e9bfde2c7c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 14 Jan 2018 00:46:48 -0800 Subject: [PATCH 154/456] add gas_station. --- src/main/java/gas_station/GasStation.java | 27 ++++++++--------------- 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/src/main/java/gas_station/GasStation.java b/src/main/java/gas_station/GasStation.java index ab4c4cc..34ec7e7 100644 --- a/src/main/java/gas_station/GasStation.java +++ b/src/main/java/gas_station/GasStation.java @@ -4,26 +4,17 @@ public class GasStation { public class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { - int start = 0; - while (start < gas.length) { - int end = start; - int rest = 0; - do { - rest += gas[end] - cost[end]; - end = (end + 1) % gas.length; - if (rest < 0) { - if (end <= start) { - return -1; - } - break; - } - } while (end != start); - if (end == start) { - return start; + int total = 0, sum = 0, start = 0; + for (int i = 0; i < gas.length; ++i) { + total += gas[i] - cost[i]; + sum += gas[i] - cost[i]; + if (sum < 0) { + start = i + 1; + sum = 0; } - start = end; } - return -1; + if (total < 0) return -1; + else return start; } } From d6eb131be7cd73fe672a9f9e04bc44c51abb30a4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 16 Jan 2018 00:39:36 -0800 Subject: [PATCH 155/456] modify min stack --- src/main/java/min_stack/MinStack.java | 61 +++++++-------------------- 1 file changed, 16 insertions(+), 45 deletions(-) diff --git a/src/main/java/min_stack/MinStack.java b/src/main/java/min_stack/MinStack.java index 036a224..dbcb875 100644 --- a/src/main/java/min_stack/MinStack.java +++ b/src/main/java/min_stack/MinStack.java @@ -1,67 +1,38 @@ package min_stack; -public class MinStack { - - private static class IntStack { - private int[] items = new int[16]; - private int size = 0; +import java.util.Stack; - private void ensureSize(int newSize) { - if (items.length < newSize) { - int[] newItems = new int[items.length * 2]; - System.arraycopy(items, 0, newItems, 0, items.length); - items = newItems; - } - } +public class MinStack { - public void push(int v) { - ensureSize(size + 1); - items[size++] = v; - } + private Stack _stack = new Stack(); + private Stack _minStack = new Stack(); - public void pop() { - if (size == 0) { - throw new IllegalStateException("The stack is empty"); - } - size--; - } - public int top() { - if (size == 0) { - throw new IllegalStateException("The stack is empty"); - } - return items[size - 1]; - } + /** initialize your data structure here. */ + public MinStack() { - public boolean isEmpty() { - return size == 0; - } } - private IntStack minStack = new IntStack(); - private IntStack stack = new IntStack(); - - public void push(int x) { - if (stack.isEmpty() || x <= minStack.top()) { - minStack.push(x); - } - stack.push(x); + public void push(Integer x) { + _stack.push(x); + if (_minStack.empty() || x <= _minStack.peek()) _minStack.push(x); } public void pop() { - int x = stack.top(); - stack.pop(); - if (x == minStack.top()) { - minStack.pop(); + if (!_stack.empty()) { + if (_stack.peek() == _minStack.peek()) _minStack.pop(); + _stack.pop(); } } public int top() { - return stack.top(); + if (!_stack.empty()) return _stack.peek(); + return 0; } public int getMin() { - return minStack.top(); + if (!_minStack.empty()) return _minStack.peek(); + return 0; } } From 1e32ce1097c566654b1f106937c67547a87cd4f4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 16 Jan 2018 13:59:36 -0800 Subject: [PATCH 156/456] modify implement_trie --- .../java/implement_trie/ImplementTrie.java | 85 +++++++++---------- 1 file changed, 38 insertions(+), 47 deletions(-) diff --git a/src/main/java/implement_trie/ImplementTrie.java b/src/main/java/implement_trie/ImplementTrie.java index a19d30f..dd867bc 100644 --- a/src/main/java/implement_trie/ImplementTrie.java +++ b/src/main/java/implement_trie/ImplementTrie.java @@ -3,66 +3,57 @@ public class ImplementTrie { class TrieNode { - private TrieNode[] children = new TrieNode[26]; + public TrieNode[] child = new TrieNode[26]; + public boolean isWord; - private boolean end = false; - - private TrieNode getChild(char c) { - return children[c - 'a']; - } - - private TrieNode getOrCreateChild(char c) { - if (children[c - 'a'] == null) { - children[c - 'a'] = new TrieNode(); - } - return children[c - 'a']; + public void TrieNode() { + for (TrieNode a : child) a = null; } - public void insert(int start, String word) { - if (start == word.length()) { - end = true; - } else { - TrieNode child = getOrCreateChild(word.charAt(start)); - child.insert(start + 1, word); - } - } - - public boolean search(int start, String word, boolean prefixSearch) { - if (start == word.length()) { - return end || prefixSearch; - } - TrieNode child = getChild(word.charAt(start)); - if (child != null) { - return child.search(start + 1, word, prefixSearch); - } - return false; - } } public class Trie { - private TrieNode root = new TrieNode(); + private TrieNode root = null; + + public Trie() { + root = new TrieNode(); + } - /** - * Inserts a word into the trie. - */ - public void insert(String word) { - root.insert(0, word); + // Inserts a word into the trie. + public void insert(String s) { + TrieNode p = root; + for (char a : s.toCharArray()) { + int i = a - 'a'; + if (p.child[i] == null) + p.child[i] = new TrieNode(); + p = p.child[i]; + } + p.isWord = true; } - /** - * Returns if the word is in the trie. - */ - public boolean search(String word) { - return root.search(0, word, false); + // Returns if the word is in the trie. + public boolean search(String key) { + TrieNode p = root; + for (char a : key.toCharArray()) { + int i = a - 'a'; + if (p.child[i] == null) return false; + p = p.child[i]; + } + return p.isWord; } - /** - * Returns if there is any word in the trie - * that starts with the given prefix. - */ + // Returns if there is any word in the trie + // that starts with the given prefix. public boolean startsWith(String prefix) { - return root.search(0, prefix, true); + TrieNode p = root; + for (char a : prefix.toCharArray()) { + int i = a - 'a'; + if (p.child[i] == null) return false; + p = p.child[i]; + } + return true; } + } } From 5ac8ae48af3bd3c3c373ef3931564fdca47782b2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 18 Jan 2018 10:16:53 -0800 Subject: [PATCH 157/456] modify jump_game --- src/main/java/jump_game/JumpGame.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/jump_game/JumpGame.java b/src/main/java/jump_game/JumpGame.java index 8d41fd7..308efbd 100644 --- a/src/main/java/jump_game/JumpGame.java +++ b/src/main/java/jump_game/JumpGame.java @@ -4,12 +4,12 @@ public class JumpGame { public class Solution { public boolean canJump(int[] A) { - assert A != null; - int far = 0; - for (int i = 0; i < A.length && i <= far; i++) { - far = Math.max(far, A[i] + i); + int[] dp = new int[A.length]; + for (int i = 1; i < A.length; ++i) { + dp[i] = Integer.max(dp[i - 1], A[i - 1]) - 1; + if (dp[i] < 0) return false; } - return far >= A.length - 1; + return dp[A.length - 1] >= 0; } } From 5c48aff145bafa940bba499219680a31733b3894 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 18 Jan 2018 10:26:52 -0800 Subject: [PATCH 158/456] modify jump_game --- src/main/java/jump_game_ii/JumpGameII.java | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/jump_game_ii/JumpGameII.java b/src/main/java/jump_game_ii/JumpGameII.java index 2e667ef..089b66f 100644 --- a/src/main/java/jump_game_ii/JumpGameII.java +++ b/src/main/java/jump_game_ii/JumpGameII.java @@ -3,19 +3,20 @@ public class JumpGameII { public class Solution { - public int jump(int[] A) { - int step = 0; - int next = 0; - int current = 0; - for (int i = 0; i < A.length; i++) { - if (i > current) { - current = next; - step++; + int jump(int A[]) { + int res = 0, i = 0, cur = 0; + while (cur < A.length - 1) { + int pre = cur; + while (i <= pre) { + cur = Integer.max(cur, i + A[i]); + ++i; } - next = Math.max(next, i + A[i]); + ++res; + if (pre == cur) return -1; // May not need this } - return step; + return res; } + } public static class UnitTest { From 2016261a449c6d8b6a484dd65ce29d44522cca99 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 18 Jan 2018 14:49:43 -0800 Subject: [PATCH 159/456] modify triangle --- src/main/java/triangle/Triangle.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/triangle/Triangle.java b/src/main/java/triangle/Triangle.java index 72b60e0..187fca9 100644 --- a/src/main/java/triangle/Triangle.java +++ b/src/main/java/triangle/Triangle.java @@ -2,12 +2,13 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.List; public class Triangle { public class Solution { - public int minimumTotal(ArrayList> triangle) { - ArrayList sum = new ArrayList(); + public int minimumTotal(List> triangle) { + List sum = new ArrayList(); if (triangle.isEmpty()) { return 0; } From 2659a1410317f1ba839d343815e110d4877dd7a2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 19 Jan 2018 10:47:29 -0800 Subject: [PATCH 160/456] modify postorder traversal --- .../BinaryTreePostorderTraversal.java | 63 ++++++------------- 1 file changed, 20 insertions(+), 43 deletions(-) diff --git a/src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java b/src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java index 390a90d..7e52452 100644 --- a/src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java +++ b/src/main/java/binary_tree_postorder_traversal/BinaryTreePostorderTraversal.java @@ -1,56 +1,33 @@ package binary_tree_postorder_traversal; -import java.util.ArrayDeque; -import java.util.ArrayList; - import common.TreeNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + public class BinaryTreePostorderTraversal { public class Solution { - private void postorderTraversal(TreeNode root, - ArrayList postorder) { - if (root == null) { - return; - } - postorderTraversal(root.left, postorder); - postorderTraversal(root.right, postorder); - postorder.add(root.val); - } - - public ArrayList postorderTraversal(TreeNode root) { - ArrayList postorder = new ArrayList(); - postorderTraversal(root, postorder); - return postorder; - } - - public ArrayList postorderTraversalWithIterative(TreeNode root) { - ArrayList postorder = new ArrayList(); - if (root == null) { - return postorder; - } - ArrayDeque stack = new ArrayDeque(); - TreeNode pre = null; - stack.offerLast(root); - while (!stack.isEmpty()) { - TreeNode p = stack.peekLast(); - if (pre == null || pre.left == p || pre.right == p) { - if (p.left != null) { - stack.offerLast(p.left); - } else if (p.right != null) { - stack.offerLast(p.right); - } - } else if (p.left == pre) { - if (p.right != null) { - stack.offerLast(p.right); - } + public List postorderTraversal(TreeNode root) { + List res = new ArrayList<>(); + if (root == null) return res; + Stack s = new Stack<>(); + s.push(root); + TreeNode head = root; + while (!s.empty()) { + TreeNode t = s.peek(); + if ((t.left == null && t.right == null) || + t.left == head || t.right == head) { + res.add(t.val); + s.pop(); + head = t; // set head to t after added to res } else { - postorder.add(p.val); - stack.removeLast(); + if (t.right != null) s.push(t.right); + if (t.left != null) s.push(t.left); } - pre = p; } - return postorder; + return res; } } From a0400364092d82f4a746dbd60d39cdb72467cca3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 19 Jan 2018 11:39:51 -0800 Subject: [PATCH 161/456] modify pretorder traversal --- .../BinaryTreePreorderTraversal.java | 50 ++++++------------- 1 file changed, 15 insertions(+), 35 deletions(-) diff --git a/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java b/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java index fba129e..4214ac1 100644 --- a/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java +++ b/src/main/java/binary_tree_preorder_traversal/BinaryTreePreorderTraversal.java @@ -1,46 +1,26 @@ package binary_tree_preorder_traversal; -import java.util.ArrayDeque; -import java.util.ArrayList; - import common.TreeNode; +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + public class BinaryTreePreorderTraversal { public class Solution { - private void preorderTraversal(TreeNode root, - ArrayList preorder) { - if (root == null) { - return; - } - preorder.add(root.val); - preorderTraversal(root.left, preorder); - preorderTraversal(root.right, preorder); - } - - public ArrayList preorderTraversal(TreeNode root) { - ArrayList preorder = new ArrayList(); - preorderTraversal(root, preorder); - return preorder; - } - - public ArrayList preorderTraversalWithIterative(TreeNode root) { - ArrayList preorder = new ArrayList(); - ArrayDeque stack = new ArrayDeque(); - if (root != null) { - stack.offerLast(root); - while (!stack.isEmpty()) { - TreeNode p = stack.removeLast(); - while (p != null) { - preorder.add(p.val); - if (p.right != null) { - stack.offerLast(p.right); - } - p = p.left; - } - } + public List preorderTraversal(TreeNode root) { + List res = new ArrayList<>(); + if (root == null) return res; + Stack s = new Stack<>(); + s.push(root); + while (!s.empty()) { + TreeNode t = s.peek(); s.pop(); + res.add(t.val); + if (t.right != null) s.push(t.right); + if (t.left != null) s.push(t.left); } - return preorder; + return res; } } From 922f83f5f4e49e46c5751bbb11bfa284f5432134 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 19 Jan 2018 15:14:05 -0800 Subject: [PATCH 162/456] add split_array_largest_sum --- .../SplitArrayLargestSum.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/split_array_largest_sum/SplitArrayLargestSum.java diff --git a/src/main/java/split_array_largest_sum/SplitArrayLargestSum.java b/src/main/java/split_array_largest_sum/SplitArrayLargestSum.java new file mode 100644 index 0000000..4c654d4 --- /dev/null +++ b/src/main/java/split_array_largest_sum/SplitArrayLargestSum.java @@ -0,0 +1,39 @@ +package split_array_largest_sum; + +/** + * Created by lxie on 1/19/18. + */ +public class SplitArrayLargestSum { + + public class Solution { + public int splitArray(int[] nums, int m) { + int n = nums.length; + int[] sums = new int[n+1]; + int[][] dp = new int[m+1][n+1]; + for (int i=0; i<=m; ++i) + for(int j=0; j<=n; ++j) + dp[i][j] = Integer.MAX_VALUE; + + dp[0][0] = 0; + for (int i = 1; i <= n; ++i) { + sums[i] = sums[i - 1] + nums[i - 1]; + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + for (int k = i - 1; k < j; ++k) { + int val = Integer.max(dp[i - 1][k], sums[j] - sums[k]); + dp[i][j] = Integer.min(dp[i][j], val); + } + } + } + return dp[m][n]; + + } + } + + public static class UnitTest { + + } + + +} From ada16b32cdda1edd6885dad41c7633cdc69961a0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 20 Jan 2018 18:35:05 -0800 Subject: [PATCH 163/456] add thirdMax --- .../third_max_number/ThirdMaximumNumber.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/third_max_number/ThirdMaximumNumber.java diff --git a/src/main/java/third_max_number/ThirdMaximumNumber.java b/src/main/java/third_max_number/ThirdMaximumNumber.java new file mode 100644 index 0000000..86176a0 --- /dev/null +++ b/src/main/java/third_max_number/ThirdMaximumNumber.java @@ -0,0 +1,31 @@ +package third_max_number; + +/** + * Created by lxie on 1/20/18. + */ +public class ThirdMaximumNumber { + + public class Solution { + + public int thirdMax(int[] nums) { + long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE; + for (int num : nums) { + if (num > first) { + third = second; + second = first; + first = num; + } else if (num > second && num < first) { + third = second; + second = num; + } else if (num > third && num < second) { + third = num; + } + } + return (third == Long.MIN_VALUE || third == second) ? (int)first : (int)third; + } + } + + public static class UnitTest { + + } +} From c98473fe0ac9e1dfb23ea3fbe34e4993338ed7ea Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 21 Jan 2018 18:27:25 -0800 Subject: [PATCH 164/456] sparse matrix multiplication --- .../SparseMatrixMultiplication.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java diff --git a/src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java b/src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java new file mode 100644 index 0000000..483aacc --- /dev/null +++ b/src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java @@ -0,0 +1,49 @@ +package sparse_matrix_multiplication; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 1/21/18. + */ +public class SparseMatrixMultiplication { + + public class Solution { + + public int[][] multiply(int[][] A, int[][] B) { + // Write your code here + int n = A.length; + int m = B[0].length; + int t = A[0].length; + int[][] C = new int[n][m]; + + List> col = new ArrayList<>(); + for (int i = 0; i < t; i++) { + col.add(new ArrayList<>()); + for (int j = 0; j < m; j++) { + if (B[i][j] != 0) { + col.get(i).add(j); + } + } + } + for (int i = 0; i < n; i++) { + for (int k = 0; k < t; k++) { + if (A[i][k] == 0) { + continue; + } + for (int p = 0; p < col.get(k).size(); p++) { + int j = col.get(k).get(p); + C[i][j] += A[i][k] * B[k][j]; + } + } + } + return C; + } + + } + + public static class UnitTest { + + } + +} From 536780e6325a1e2b50fbb283b4d34cca80c38cd1 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 22 Jan 2018 01:27:58 -0800 Subject: [PATCH 165/456] add burst_balloon --- .../java/burst_balloons/BurstBalloons.java | 38 +++++++++++++++++++ .../SparseMatrixMultiplication.java | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/main/java/burst_balloons/BurstBalloons.java diff --git a/src/main/java/burst_balloons/BurstBalloons.java b/src/main/java/burst_balloons/BurstBalloons.java new file mode 100644 index 0000000..ba7b6ee --- /dev/null +++ b/src/main/java/burst_balloons/BurstBalloons.java @@ -0,0 +1,38 @@ +package burst_balloons; + +/** + * Created by lxie on 1/22/18. + */ +public class BurstBalloons { + + public class Solution { + public int maxCoins(int[] nums) { + if(nums == null || nums.length == 0) return 0; + int n = nums.length; + //开数组到n+2是为了保证k-1 k+1不溢出 + int[][] dp = new int[n+2][n+2]; + for(int i=1;i<=n;i++){ + int left = i-2 >= 0?nums[i-2]:1; + int right = i < n?nums[i]:1; + dp[i][i] = left*nums[i-1]*right; + } + for(int len = 2;len<=n;len++){ + for(int i=1;i+len-1<=n;i++){ + int j = i+len-1; + int left = i-2 >= 0?nums[i-2]:1; + int right = j < n?nums[j]:1; + dp[i][j] = Integer.MIN_VALUE; + for(int k=i;k<=j;k++){ + dp[i][j] = Math.max(dp[i][j], dp[i][k-1]+dp[k+1][j]+left*right*nums[k-1]); + } + } + } + return dp[1][n]; + } + } + + public static class UniTest { + + } + +} diff --git a/src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java b/src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java index 483aacc..5f75a9f 100644 --- a/src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java +++ b/src/main/java/sparse_matrix_multiplication/SparseMatrixMultiplication.java @@ -43,7 +43,7 @@ public int[][] multiply(int[][] A, int[][] B) { } public static class UnitTest { - + } } From 7e7c0c2e6788f32dfc612e79baf3a169f4145004 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 23 Jan 2018 10:43:54 -0800 Subject: [PATCH 166/456] add number_of_islands i and ii --- .../number_of_islands/NumberOfIslands.java | 21 ++++++++ .../NumberOfIslandsII.java | 54 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/main/java/number_of_islands/NumberOfIslands.java create mode 100644 src/main/java/number_of_islands_ii/NumberOfIslandsII.java diff --git a/src/main/java/number_of_islands/NumberOfIslands.java b/src/main/java/number_of_islands/NumberOfIslands.java new file mode 100644 index 0000000..39e0d1d --- /dev/null +++ b/src/main/java/number_of_islands/NumberOfIslands.java @@ -0,0 +1,21 @@ +package number_of_islands; + +/** + * Created by lxie on 1/23/18. + */ +public class NumberOfIslands { + + public class Solution { + + + + } + + public static class UnitTest { + + + + + } + +} diff --git a/src/main/java/number_of_islands_ii/NumberOfIslandsII.java b/src/main/java/number_of_islands_ii/NumberOfIslandsII.java new file mode 100644 index 0000000..5852c2e --- /dev/null +++ b/src/main/java/number_of_islands_ii/NumberOfIslandsII.java @@ -0,0 +1,54 @@ +package number_of_islands_ii; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 1/23/18. + */ +public class NumberOfIslandsII { + + public class Solution { + + public List numIslands2(int m, int n, int[][] positions) { + List res = new ArrayList<>(); + if (m <= 0 || n <= 0) return res; + int[] roots = new int[m*n]; + for (int i=0; i= m || y < 0 || y >= n || roots[cur_id] == -1) continue; + int new_id = findRoots(roots, cur_id); + if (id != new_id) { + roots[id] = new_id; + id = new_id; + --cnt; + } + } + res.add(cnt); + } + return res; + } + + // union find + private int findRoots(int[] roots, int id) { + while (id != roots[id]) { + roots[id] = roots[roots[id]]; // path compression + id = roots[id]; + } + return id; + } + } + + public static class UnitTest { + + } + +} From 8ef61f0c4ff0536f1f982f0627c2e32524a7d3df Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 23 Jan 2018 10:50:08 -0800 Subject: [PATCH 167/456] add number_of_islands i --- .../number_of_islands/NumberOfIslands.java | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/main/java/number_of_islands/NumberOfIslands.java b/src/main/java/number_of_islands/NumberOfIslands.java index 39e0d1d..59ade04 100644 --- a/src/main/java/number_of_islands/NumberOfIslands.java +++ b/src/main/java/number_of_islands/NumberOfIslands.java @@ -6,8 +6,32 @@ public class NumberOfIslands { public class Solution { - - + public int numIslands(char[][] grid) { + if (grid.length == 0 || grid[0].length == 0) return 0; + int m = grid.length, n = grid[0].length, res = 0; + boolean[][] visited = new boolean[m][n]; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1' && !visited[i][j]) { + numIslandsDFS(grid, visited, i, j); + ++res; + } + } + } + return res; + } + + public void numIslandsDFS(char[][] grid, boolean[][] visited, int x, int y) { + if (x < 0 || x >= grid.length) return; + if (y < 0 || y >= grid[0].length) return; + if (grid[x][y] != '1' || visited[x][y]) return; + visited[x][y] = true; + numIslandsDFS(grid, visited, x - 1, y); + numIslandsDFS(grid, visited, x + 1, y); + numIslandsDFS(grid, visited, x, y - 1); + numIslandsDFS(grid, visited, x, y + 1); + } } From 36c8ec149e8b9ae5ac1b7314fae02a626c91f764 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 23 Jan 2018 16:07:46 -0800 Subject: [PATCH 168/456] longest increasing path in matrix --- .../LongestIncreasingPathMatrix.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/longest_increasing_path_in_matrix/LongestIncreasingPathMatrix.java diff --git a/src/main/java/longest_increasing_path_in_matrix/LongestIncreasingPathMatrix.java b/src/main/java/longest_increasing_path_in_matrix/LongestIncreasingPathMatrix.java new file mode 100644 index 0000000..da2034a --- /dev/null +++ b/src/main/java/longest_increasing_path_in_matrix/LongestIncreasingPathMatrix.java @@ -0,0 +1,47 @@ +package longest_increasing_path_in_matrix; + +/** + * Created by lxie on 1/23/18. + */ +public class LongestIncreasingPathMatrix { + + public class Solution { + + public final int[][] dirs = new int[][] {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; + + + public int longestIncreasingPath(int[][] matrix) { + if (matrix.length == 0 || matrix[0].length == 0) return 0; + int res = 1, m = matrix.length, n = matrix[0].length; + int[][] dp = new int[m][n]; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + res = Integer.max(res, dfs(matrix, dp, i, j)); + } + } + return res; + } + + + private int dfs(int[][] matrix, int[][] dp, int i, int j) { + if (dp[i][j] != 0) return dp[i][j]; + int mx = 1, m = matrix.length, n = matrix[0].length; + for (int[] a : dirs) { + int x = i + a[0], y = j + a[1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[i][j]) continue; + int len = 1 + dfs(matrix, dp, x, y); + mx = Integer.max(mx, len); + } + dp[i][j] = mx; + return mx; + } + + } + + public static class UnitTest { + + + + } +} From 8366327eacfaa90fd940bdb1e70c98dc8d4743ce Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 24 Jan 2018 01:29:02 -0800 Subject: [PATCH 169/456] add palindrome pairs --- .../java/palindrom_pairs/PalindromePairs.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/palindrom_pairs/PalindromePairs.java diff --git a/src/main/java/palindrom_pairs/PalindromePairs.java b/src/main/java/palindrom_pairs/PalindromePairs.java new file mode 100644 index 0000000..0e50fc9 --- /dev/null +++ b/src/main/java/palindrom_pairs/PalindromePairs.java @@ -0,0 +1,54 @@ +package palindrom_pairs; + +import java.util.*; + +/** + * Created by lxie on 1/23/18. + */ +public class PalindromePairs { + + public class Solution { + + public List> palindromePairs(String[] words) { + List> res = new ArrayList<>(); + Map m = new HashMap(); + Set s = new TreeSet(); + for (int i = 0; i < words.length; ++i) { + m.put(words[i], i); + s.add(words[i].length()); + } + for (int i = 0; i < words.length; ++i) { + String t = words[i]; + int len = t.length(); + t = new StringBuilder(t).reverse().toString(); + if (m.containsKey(t) && m.get(t) != i) { // not self + res.add(Arrays.asList(i, m.get(t))); + } + + for (int d : s) { + if (d >= len) break; + if (isValid(t, 0, len - d - 1) && m.containsKey(t.substring(len - d))) { + res.add(Arrays.asList(i, m.get(t.substring(len - d)))); // abcdd - cba, t is reversed + } + if (isValid(t, d, len - 1) && m.containsKey(t.substring(0, d))) { + res.add(Arrays.asList(m.get(t.substring(0, d)), i)); // aabcd - dcb, t is reversed + } + } + } + return res; + } + + private boolean isValid(String t, int left, int right) { + while (left < right) { + if (t.toCharArray()[left++] != t.toCharArray()[right--]) return false; + } + return true; + } + + } + + public static class UnitTest { + + } + +} From e5cc419294e5dad0fb1ed4b36e2a618070720dd1 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 24 Jan 2018 14:09:06 -0800 Subject: [PATCH 170/456] design tic-tac-toe --- .../design_tic_tac_toe/DesignTicTacToe.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/design_tic_tac_toe/DesignTicTacToe.java diff --git a/src/main/java/design_tic_tac_toe/DesignTicTacToe.java b/src/main/java/design_tic_tac_toe/DesignTicTacToe.java new file mode 100644 index 0000000..b1fc06e --- /dev/null +++ b/src/main/java/design_tic_tac_toe/DesignTicTacToe.java @@ -0,0 +1,35 @@ +package design_tic_tac_toe; + +import static java.lang.StrictMath.abs; + +/** + * Created by lxie on 1/24/18. + */ +public class DesignTicTacToe { + + public class Solution { + + public class TicTacToe { + private final int N = 3; + private int[] rows = new int[N]; + private int[] cols = new int[N]; + private int diag = 0, rev_diag = 0; + + public int move(int row, int col, int player) { + int add = player == 1 ? 1 : -1; + rows[row] += add; cols[col] += add; + diag += (row == col ? add : 0); + rev_diag += (row == N - col - 1 ? add : 0); + return (abs(rows[row]) == N || abs(cols[col]) == N || abs(diag) == N + || abs(rev_diag) == N) ? player : 0; + } + + } + } + + + public static class UnitTest { + + } + +} From 3ce706ae853c892b535940a84ea7dee7040a95f5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 24 Jan 2018 14:20:00 -0800 Subject: [PATCH 171/456] design tic-tac-toe --- src/main/java/design_tic_tac_toe/DesignTicTacToe.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/design_tic_tac_toe/DesignTicTacToe.java b/src/main/java/design_tic_tac_toe/DesignTicTacToe.java index b1fc06e..cf09c70 100644 --- a/src/main/java/design_tic_tac_toe/DesignTicTacToe.java +++ b/src/main/java/design_tic_tac_toe/DesignTicTacToe.java @@ -10,11 +10,15 @@ public class DesignTicTacToe { public class Solution { public class TicTacToe { - private final int N = 3; + private int N = 3; private int[] rows = new int[N]; private int[] cols = new int[N]; private int diag = 0, rev_diag = 0; + public void TicTacToe(int n) { + this.N = n; + } + public int move(int row, int col, int player) { int add = player == 1 ? 1 : -1; rows[row] += add; cols[col] += add; From c1668e8091855c3fd38b8a1c26ed467b59d4fc33 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 24 Jan 2018 16:58:33 -0800 Subject: [PATCH 172/456] add line_reflection --- .../java/line_reflection/LineReflection.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/line_reflection/LineReflection.java diff --git a/src/main/java/line_reflection/LineReflection.java b/src/main/java/line_reflection/LineReflection.java new file mode 100644 index 0000000..1f935df --- /dev/null +++ b/src/main/java/line_reflection/LineReflection.java @@ -0,0 +1,39 @@ +package line_reflection; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Created by lxie on 1/24/18. + */ +public class LineReflection { + + public class Solution { + public boolean isReflected(int[][] points) { + Map> m = new HashMap<>(); + int mx = Integer.MIN_VALUE, mn = Integer.MIN_VALUE; + for (int[] a : points) { + mx = Integer.max(mx, a[0]); + mn = Integer.min(mn, a[0]); + m.get(a[0]).add(a[1]); + } + double y = (double)(mx + mn) / 2; + for (int[] a : points) { + double t = 2 * y - a[0]; + if (!m.containsKey(t) || !m.get(t).contains(a[1])) { + return false; + } + } + return true; + } + } + + public static class UnitTest { + + + + } + + +} From 7d2f67ba06f56a3f70c241bf88c45965b97ec5dc Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 25 Jan 2018 12:30:50 -0800 Subject: [PATCH 173/456] add snake_game --- src/main/java/snake_game/DesignSnakeGame.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/main/java/snake_game/DesignSnakeGame.java diff --git a/src/main/java/snake_game/DesignSnakeGame.java b/src/main/java/snake_game/DesignSnakeGame.java new file mode 100644 index 0000000..758ac30 --- /dev/null +++ b/src/main/java/snake_game/DesignSnakeGame.java @@ -0,0 +1,64 @@ +package snake_game; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 1/25/18. + */ +public class DesignSnakeGame { + + public class Solution { + + public class SnakeGame { + + private int width, height, score; + private List food = new ArrayList<>(); + private List pos = new ArrayList<>(); + + public void SnakeGame(int width, int height, List food) { + this.width = width; + this.height = height; + this.food = food; + score = 0; + pos.add(new int[] {0, 0}); + } + + public int move(String direction) { + int[] head = pos.get(0), tail = pos.get(pos.size()-1); + pos.remove(pos.size()-1); + if (direction == "U") --head[0]; + else if (direction == "L") --head[1]; + else if (direction == "R") ++head[1]; + else if (direction == "D") ++head[0]; + if (count(pos, head) > 0 || head[0] < 0 || head[0] >= height || head[1] < 0 || head[1] >= width) { + return -1; + } + pos.add(0, head); + if (food.size() != 0 && head == food.get(0)) { + food.remove(0); + pos.add(tail); + ++score; + } + return score; + } + + private int count(List pos, int[] head) { + int count = 0; + for (int[] a : pos) { + if (a == head) count++; + } + return count; + } + + } + + } + + public static class UnitTest { + + + } + + +} From ec67f9435ef71990c65a788355aa2747754cb3ac Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 27 Jan 2018 09:31:33 -0800 Subject: [PATCH 174/456] add nested_list_weight_sum i & ii. --- src/main/java/common/NestedInteger.java | 19 +++++++++ .../FlattenNestListIterator.java | 16 +------ .../NestedListWeightSum.java | 30 +++++++++++++ .../NestedListWeightSumII.java | 42 +++++++++++++++++++ 4 files changed, 93 insertions(+), 14 deletions(-) create mode 100644 src/main/java/common/NestedInteger.java create mode 100644 src/main/java/nested_list_weight_sum/NestedListWeightSum.java create mode 100644 src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java diff --git a/src/main/java/common/NestedInteger.java b/src/main/java/common/NestedInteger.java new file mode 100644 index 0000000..77ec2e3 --- /dev/null +++ b/src/main/java/common/NestedInteger.java @@ -0,0 +1,19 @@ +package common; + +import java.util.List; + +/** + * Created by lxie on 1/27/18. + */ +public interface NestedInteger { + // @return true if this NestedInteger holds a single integer, rather than a nested list. + public boolean isInteger(); + + // @return the single integer that this NestedInteger holds, if it holds a single integer + // Return null if this NestedInteger holds a nested list + public Integer getInteger(); + + // @return the nested list that this NestedInteger holds, if it holds a nested list + // Return null if this NestedInteger holds a single integer + public List getList(); +} diff --git a/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java b/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java index 4e36580..f68ba6e 100644 --- a/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java +++ b/src/main/java/flatten_nested_list_iterator/FlattenNestListIterator.java @@ -1,5 +1,7 @@ package flatten_nested_list_iterator; +import common.NestedInteger; + import java.util.Iterator; import java.util.List; import java.util.Stack; @@ -9,20 +11,6 @@ */ public class FlattenNestListIterator { - public interface NestedInteger { - // @return true if this NestedInteger holds a single integer, rather than a nested list. - public boolean isInteger(); - - // @return the single integer that this NestedInteger holds, if it holds a single integer - // Return null if this NestedInteger holds a nested list - public Integer getInteger(); - - // @return the nested list that this NestedInteger holds, if it holds a nested list - // Return null if this NestedInteger holds a single integer - public List getList(); - } - - class Solution { public class NestedIterator implements Iterator { diff --git a/src/main/java/nested_list_weight_sum/NestedListWeightSum.java b/src/main/java/nested_list_weight_sum/NestedListWeightSum.java new file mode 100644 index 0000000..9411934 --- /dev/null +++ b/src/main/java/nested_list_weight_sum/NestedListWeightSum.java @@ -0,0 +1,30 @@ +package nested_list_weight_sum; + +import common.NestedInteger; + +import java.util.List; + +/** + * Created by lxie on 1/27/18. + */ +public class NestedListWeightSum { + + public class Solution { + + public int depthSum(List nestedList) { + return helper(nestedList, 1); + } + int helper(List nl, int depth) { + int res = 0; + for (NestedInteger a : nl) { + res += a.isInteger() ? a.getInteger() * depth : helper(a.getList(), depth + 1); + } + return res; + } + } + + public static class UnitTest { + + } + +} diff --git a/src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java b/src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java new file mode 100644 index 0000000..d7b0c62 --- /dev/null +++ b/src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java @@ -0,0 +1,42 @@ +package nested_list_weight_sum_ii; + +import common.NestedInteger; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 1/27/18. + */ +public class NestedListWeightSumII { + + public class Solution { + + public int depthSumInverse(List nestedList) { + int res = 0; + List v = new ArrayList<>(); + for (NestedInteger a : nestedList) { + helper(a, 0, v); + } + for (int i = v.size() - 1; i >= 0; --i) { + res += v.get(i) * (v.size() - i); + } + return res; + } + void helper(NestedInteger ni, int depth, List v) { + if (depth >= v.size()) v.add(0); + if (ni.isInteger()) { + v.set(depth, v.get(depth) + ni.getInteger()); + } else { + for (NestedInteger a : ni.getList()) { + helper(a, depth + 1, v); + } + } + } + } + + public static class UnitTest { + + } + +} From 9154678055cb74dd5b989d023a3d070ffd6eeff9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 28 Jan 2018 00:23:31 -0800 Subject: [PATCH 175/456] add find_k_smallest_pairs --- .../KPairsSmallestSum.java | 48 +++++++++++++++++++ .../NestedListWeightSumII.java | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 src/main/java/find_k_pairs_smallest_sum/KPairsSmallestSum.java diff --git a/src/main/java/find_k_pairs_smallest_sum/KPairsSmallestSum.java b/src/main/java/find_k_pairs_smallest_sum/KPairsSmallestSum.java new file mode 100644 index 0000000..3c868f5 --- /dev/null +++ b/src/main/java/find_k_pairs_smallest_sum/KPairsSmallestSum.java @@ -0,0 +1,48 @@ +package find_k_pairs_smallest_sum; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +/** + * Created by lxie on 1/27/18. + */ +public class KPairsSmallestSum { + + public class Solution { + + public List kSmallestPairs(int[] nums1, int[] nums2, int k) { + List res = new ArrayList<>(); + PairComparator comparator = new PairComparator(); + PriorityQueue q = new PriorityQueue<>(100, comparator); + for (int i = 0; i < Integer.min((int)nums1.length, k); ++i) { + for (int j = 0; j < Integer.min((int)nums2.length, k); ++j) { + if (q.size() < k) { + q.add(new int[] {nums1[i], nums2[j]}); + } else if (nums1[i] + nums2[j] < q.peek()[0] + q.peek()[1]) { + q.add(new int[]{nums1[i], nums2[j]}); q.poll(); + } + } + } + while (!q.isEmpty()) { + res.add(q.peek()); q.poll(); + } + return res; + } + + class PairComparator implements Comparator { + @Override + public int compare(int[] p1, int[] p2) { + return (p2[0] + p2[1]) - (p1[0] + p1[1]); + } + } + + } + + public static class UnitTest { + + + } + +} diff --git a/src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java b/src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java index d7b0c62..68ca554 100644 --- a/src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java +++ b/src/main/java/nested_list_weight_sum_ii/NestedListWeightSumII.java @@ -36,7 +36,7 @@ void helper(NestedInteger ni, int depth, List v) { } public static class UnitTest { - + } } From 6e7767a1913d4cd9201e1b54c39935e107792148 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 28 Jan 2018 18:27:25 -0800 Subject: [PATCH 176/456] add guess_number_ii --- .../java/guess_number_ii/GuessNumberII.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/guess_number_ii/GuessNumberII.java diff --git a/src/main/java/guess_number_ii/GuessNumberII.java b/src/main/java/guess_number_ii/GuessNumberII.java new file mode 100644 index 0000000..69ce668 --- /dev/null +++ b/src/main/java/guess_number_ii/GuessNumberII.java @@ -0,0 +1,31 @@ +package guess_number_ii; + +/** + * Created by lxie on 1/28/18. + */ +public class GuessNumberII { + + public class Solution { + public int getMoneyAmount(int n) { + int[][] dp = new int[n+1][n+1]; + for (int i = 2; i <= n; ++i) { + for (int j = i - 1; j > 0; --j) { + int global_min = Integer.MAX_VALUE; + for (int k = j + 1; k < i; ++k) { + int local_max = k + Integer.max(dp[j][k - 1], dp[k + 1][i]); + global_min = Integer.min(global_min, local_max); + } + dp[j][i] = j + 1 == i ? j : global_min; + } + } + return dp[1][n]; + } + + } + + public static class UnitTest { + + } + + +} From 3c27cc9f90354e343711e54706d1ca2a1b0834a9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 29 Jan 2018 01:32:38 -0800 Subject: [PATCH 177/456] add btree_vertical_traversal --- .../BinaryTreeVerticalTraversal.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/binary_tree_vertical_traversal/BinaryTreeVerticalTraversal.java diff --git a/src/main/java/binary_tree_vertical_traversal/BinaryTreeVerticalTraversal.java b/src/main/java/binary_tree_vertical_traversal/BinaryTreeVerticalTraversal.java new file mode 100644 index 0000000..2503e88 --- /dev/null +++ b/src/main/java/binary_tree_vertical_traversal/BinaryTreeVerticalTraversal.java @@ -0,0 +1,56 @@ +package binary_tree_vertical_traversal; + +import common.TreeNode; + +import java.util.*; + +/** + * Created by lxie on 1/29/18. + */ +public class BinaryTreeVerticalTraversal { + + public class Solution { + + public List> verticalOrder(TreeNode root) { + List> results = new ArrayList<>(); + if (root == null) { + return results; + } + Map> map = new TreeMap>(); + Queue qCol = new LinkedList<>(); + Queue queue = new LinkedList<>(); + queue.offer(root); + qCol.offer(0); + + while(!queue.isEmpty()) { + TreeNode curr = queue.poll(); + int col = qCol.poll(); + if(!map.containsKey(col)) { + map.put(col, new ArrayList(Arrays.asList(curr.val))); + } else { + map.get(col).add(curr.val); + } + if(curr.left != null) { + queue.offer(curr.left); + qCol.offer(col - 1); + } + if(curr.right != null) { + queue.offer(curr.right); + qCol.offer(col + 1); + } + } + for(int n : map.keySet()) { + results.add(map.get(n)); + } + return results; + } + + } + + public static class UnitTest { + + + } + + +} From 28d6f5843f107997acbb33d3181c24ae414d381d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 30 Jan 2018 10:15:20 -0800 Subject: [PATCH 178/456] add shortest distance from all buildings --- .../ShortestDistanceToBuildings.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/shortest_distance_from_all_buildings/ShortestDistanceToBuildings.java diff --git a/src/main/java/shortest_distance_from_all_buildings/ShortestDistanceToBuildings.java b/src/main/java/shortest_distance_from_all_buildings/ShortestDistanceToBuildings.java new file mode 100644 index 0000000..a8abcf7 --- /dev/null +++ b/src/main/java/shortest_distance_from_all_buildings/ShortestDistanceToBuildings.java @@ -0,0 +1,50 @@ +package shortest_distance_from_all_buildings; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by lxie on 1/30/18. + */ +public class ShortestDistanceToBuildings { + + public class Solution { + + public int shortestDistance(int[][] grid) { + int res = Integer.MAX_VALUE, val = 0, m = grid.length, n = grid[0].length; + int[][] sum = grid; + int[][] dirs = {{0,-1},{-1,0},{0,1},{1,0}}; + for (int i = 0; i < grid.length; ++i) { + for (int j = 0; j < grid[i].length; ++j) { + if (grid[i][j] == 1) { + res = Integer.MAX_VALUE; + int[][] dist = grid; + Queue q = new LinkedList<>(); + q.add(new int[]{i, j}); + while (!q.isEmpty()) { + int a = q.peek()[0], b = q.peek()[1]; q.poll(); + for (int k = 0; k < dirs.length; ++k) { + int x = a + dirs[k][0], y = b + dirs[k][1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == val) { + --grid[x][y]; + dist[x][y] = dist[a][b] + 1; + sum[x][y] += dist[x][y] - 1; + q.add(new int[]{x, y}); + res = Integer.min(res, sum[x][y]); + } + } + } + --val; // empty land changes in each BFS + } + } + } + return res == Integer.MAX_VALUE ? -1 : res; + } + } + + + public static class UnitTest { + + } + +} From 9c1868a9af6a3e570ca2e5ba879e04763b62d3d6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 1 Feb 2018 01:01:48 -0800 Subject: [PATCH 179/456] add binary_tree_upside_down --- .../UpsideDownBinaryTree.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/binary_tree_upside_down/UpsideDownBinaryTree.java diff --git a/src/main/java/binary_tree_upside_down/UpsideDownBinaryTree.java b/src/main/java/binary_tree_upside_down/UpsideDownBinaryTree.java new file mode 100644 index 0000000..46675c3 --- /dev/null +++ b/src/main/java/binary_tree_upside_down/UpsideDownBinaryTree.java @@ -0,0 +1,43 @@ +package binary_tree_upside_down; + +import common.TreeNode; + +/** + * Created by lxie on 2/1/18. + */ +public class UpsideDownBinaryTree { + + public class Solution { + TreeNode upsideDownBinaryTree(TreeNode root) { + if (root == null || root.left == null) return root; + TreeNode l = root.left, r = root.right; + TreeNode res = upsideDownBinaryTree(l); + l.left = r; + l.right = root; + root.left = null; + root.right = null; + return res; + } + + TreeNode upsideDownBinaryTree1(TreeNode root) { + TreeNode cur = root, pre = null, next = null, tmp = null; + while (cur != null) { + next = cur.left; + cur.left = tmp; + tmp = cur.right; + cur.right = pre; + pre = cur; + cur = next; + } + return pre; + } + + } + + public static class UnitTest { + + + } + + +} From 44df8437f8038b03074808affc8f422045f95467 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 1 Feb 2018 10:09:25 -0800 Subject: [PATCH 180/456] add longest_substr_at_most_two_distinct_chars --- .../LongestStrTwoDistinct.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/longest_substr_at_most_two_distinct_chars/LongestStrTwoDistinct.java diff --git a/src/main/java/longest_substr_at_most_two_distinct_chars/LongestStrTwoDistinct.java b/src/main/java/longest_substr_at_most_two_distinct_chars/LongestStrTwoDistinct.java new file mode 100644 index 0000000..abfee10 --- /dev/null +++ b/src/main/java/longest_substr_at_most_two_distinct_chars/LongestStrTwoDistinct.java @@ -0,0 +1,43 @@ +package longest_substr_at_most_two_distinct_chars; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 2/1/18. + */ +public class LongestStrTwoDistinct { + + public static class Solution { + + public int lengthOfLongestSubstringTwoDistinct(String s) { + int res = 0, left = 0; + Map m = new HashMap<>(); + char[] s1 = s.toCharArray(); + + for (int i = 0; i < s.length(); ++i) { + if (!m.containsKey(s1[i])) { + m.put(s1[i], 1); + } else { + m.put(s1[i], m.get(s1[i])+1); + } + + while (m.size() > 2) { + m.put(s1[left], m.get(s1[left])-1); + if (m.get(s1[left]) == 0) m.remove(s1[left]); + ++left; + } + res = Integer.max(res, i - left + 1); + } + return res; + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + int res = sol.lengthOfLongestSubstringTwoDistinct("eceba"); + System.out.println(res); + } + +} From a0957a81ddc1a1f3f1c07a04757fce8a2454c785 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 1 Feb 2018 12:08:56 -0800 Subject: [PATCH 181/456] add maximum_gap --- src/main/java/maximum_gap/MaximumGap.java | 76 +++++++++-------------- 1 file changed, 31 insertions(+), 45 deletions(-) diff --git a/src/main/java/maximum_gap/MaximumGap.java b/src/main/java/maximum_gap/MaximumGap.java index 7aff947..0d72f75 100644 --- a/src/main/java/maximum_gap/MaximumGap.java +++ b/src/main/java/maximum_gap/MaximumGap.java @@ -1,58 +1,44 @@ package maximum_gap; -import java.util.*; - -import org.junit.*; - -import static org.junit.Assert.*; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; public class MaximumGap { public class Solution { - public int maximumGap(int[] num) { - if (num.length < 2) { - return 0; - } - int min = num[0]; - int max = num[0]; - for (int i = 1; i < num.length; i++) { - min = Math.min(min, num[i]); - max = Math.max(max, num[i]); - } - if (min == max) { - return 0; - } - // ceil( (max - min) / (n - 1) ) - int gap = (max - min + num.length - 2) / (num.length - 1); - int bucketNum = (max - min) / gap + 1; - int[] minInBucket = new int[bucketNum]; - int[] maxInBucket = new int[bucketNum]; - Arrays.fill(minInBucket, -1); - Arrays.fill(maxInBucket, -1); - for (int i = 0; i < num.length; i++) { - int bucketId = (num[i] - min) / gap; - if (minInBucket[bucketId] < 0) { - minInBucket[bucketId] = maxInBucket[bucketId] = num[i]; - } else { - minInBucket[bucketId] = Math.min(minInBucket[bucketId], num[i]); - maxInBucket[bucketId] = Math.max(maxInBucket[bucketId], num[i]); - } + public int maximumGap(int[] numss) { + if (numss.length == 0) return 0; + int mx = Integer.MIN_VALUE, mn = Integer.MAX_VALUE, n = numss.length; + for (int d : numss) { + mx = Integer.max(mx, d); + mn = Integer.min(mn, d); } - int currentMax; - int i = 0; - while (i < bucketNum && minInBucket[i] < 0) { - i++; + int size = (mx - mn) / n + 1; + int bucket_nums = (mx - mn) / size + 1; + + int[] bucket_min = new int[bucket_nums]; + int[] bucket_max = new int[bucket_nums]; + Arrays.fill(bucket_min, Integer.MAX_VALUE); + Arrays.fill(bucket_max, Integer.MIN_VALUE); + + Set s = new HashSet<>(); + + for (int d : numss) { + int idx = (d - mn) / size; + bucket_min[idx] = Integer.min(bucket_min[idx], d); + bucket_max[idx] = Integer.max(bucket_max[idx], d); + s.add(idx); } - currentMax = maxInBucket[i]; - gap = 0; - for (i++; i < bucketNum; i++) { - if (minInBucket[i] >= 0) { - gap = Math.max(gap, minInBucket[i] - currentMax); - currentMax = maxInBucket[i]; - } + int pre = 0, res = 0; + for (int i = 1; i < n; ++i) { + if (!s.contains(i)) continue; + res = Integer.max(res, bucket_min[i] - bucket_max[pre]); + pre = i; } - return gap; + return res; } + } public static class UnitTest { From f210f4b7b14060c2d04c69d484c3c8f1d7c1f7f8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 2 Feb 2018 10:39:36 -0800 Subject: [PATCH 182/456] add fraction_to_recurring_decimal --- .../FractiontoRecurringDecimal.java | 81 ++++++------------- 1 file changed, 25 insertions(+), 56 deletions(-) diff --git a/src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java b/src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java index 09786d3..104a52f 100644 --- a/src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java +++ b/src/main/java/fraction_to_recurring_decimal/FractiontoRecurringDecimal.java @@ -2,7 +2,8 @@ import org.junit.Test; -import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; import static org.junit.Assert.assertEquals; @@ -10,64 +11,32 @@ public class FractiontoRecurringDecimal { public class Solution { - private String fraction(long mod, long divider) { - ArrayList mods = new ArrayList(); - mods.add(mod); - ArrayList remainders = new ArrayList(); - int i; - while (true) { - mod *= 10; - remainders.add(mod / divider); - mod = mod % divider; - if (mod == 0) { - i = -1; - break; - } - i = mods.indexOf(mod); - if (i >= 0) { - break; - } - mods.add(mod); - } - StringBuilder builder = new StringBuilder(); - if (i < 0) { - for (long r : remainders) { - builder.append(r); - } - } else { - int j = 0; - for (; j < i; j++) { - builder.append(remainders.get(j)); - } - builder.append('('); - for (; j < remainders.size(); j++) { - builder.append(remainders.get(j)); - } - builder.append(')'); - } - return builder.toString(); - } - public String fractionToDecimal(int numerator, int denominator) { - boolean negative = (numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0); - long num = Math.abs((long) numerator); - long denom = Math.abs((long) denominator); - long remainder = num / denom; - long mod = num % denom; - if (mod == 0) { - if (negative) { - return "-" + remainder; - } else { - return Long.toString(remainder); - } - } else { - if (negative) { - return "-" + remainder + "." + fraction(mod, denom); - } else { - return remainder + "." + fraction(mod, denom); + int s1 = numerator >= 0 ? 1 : -1; + int s2 = denominator >= 0 ? 1 : -1; + long num = Math.abs((long)numerator); + long den = Math.abs((long)denominator); + long out = num / den; + long rem = num % den; + Map m = new HashMap<>(); + String res = Long.toString(out); + if (s1 * s2 == -1 && (out > 0 || rem > 0)) res = "-" + res; + if (rem == 0) return res; + res += "."; + StringBuilder s = new StringBuilder(""); + int pos = 0; + while (rem != 0) { + if (m.containsKey(rem)) { + s.insert(m.get(rem), "("); + s.append(")"); + return res + s; } + m.put(rem, pos); + s.append(Long.toString((rem * 10) / den)); + rem = (rem * 10) % den; + ++pos; } - + return res + s; } } From 3d0e81b923b2b6f0ad16b1a7b86de112249f568d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 2 Feb 2018 23:43:48 -0800 Subject: [PATCH 183/456] modified reverse_words_in_a_string --- .../ReverseWordsinaString.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java b/src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java index c58ff0c..bf4855b 100644 --- a/src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java +++ b/src/main/java/reverse_words_in_a_string/ReverseWordsinaString.java @@ -21,6 +21,27 @@ public String reverseWords(String s) { } return r.toString(); } + + public String reverseWords1(String s0) { + int left = 0; char[] s = s0.toCharArray(); + for (int i = 0; i <= s.length; ++i) { + if (i == s.length || s[i] == ' ') { + reverse(s, left, i - 1); + left = i + 1; + } + } + return new String(reverse(s, 0, s.length - 1)); + } + + public char[] reverse(char[] s, int left, int right) { + while (left < right) { + char t = s[left]; + s[left] = s[right]; + s[right] = t; + ++left; --right; + } + return s; + } } public static class UnitTest { From 5cfb368c4416b3d589a8e430d534bc3f26e4b9ad Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 4 Feb 2018 16:12:46 -0800 Subject: [PATCH 184/456] modify repeated_dna_sequences --- .../RepeatedDNASequences.java | 37 +++++++++++-------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/main/java/repeated_dna_sequences/RepeatedDNASequences.java b/src/main/java/repeated_dna_sequences/RepeatedDNASequences.java index f387212..29ca795 100644 --- a/src/main/java/repeated_dna_sequences/RepeatedDNASequences.java +++ b/src/main/java/repeated_dna_sequences/RepeatedDNASequences.java @@ -1,27 +1,32 @@ package repeated_dna_sequences; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; public class RepeatedDNASequences { public class Solution { - public List findRepeatedDnaSequences(String s) { - Set sequences = new HashSet(); - Set result = new HashSet(); - for (int i = 0; i + 10 <= s.length(); i++) { - String substring = s.substring(i, i + 10); - if (sequences.contains(substring)) { - result.add(substring); - } else { - sequences.add(substring); - } + public List findRepeatedDnaSequences1(String s) { + if (s.length() < 10) return new ArrayList<>(); + char[] si = s.toCharArray(); + Set res = new HashSet<>(); + Set st= new HashSet<>(); + Map m = new HashMap<> (); + m.put('A', 0); m.put('C', 1); m.put('G', 2); m.put('T', 3); + int cur = 0, i = 0; + while (i < 9) cur = cur << 2 | m.get(si[i++]); + while (i < s.length()) { + cur = ((cur & 0x3ffff) << 2) | (m.get(si[i++])); // 20 bits for 10-letter-long + if (st.contains(cur)) res.add(s.substring(i - 10, i)); + else st.add(cur); } - System.gc(); - return new ArrayList(result); + return new ArrayList<>(res); + } + + } + + public static class UnitTest { + } } From 3599f50a806c5200f348d1655a909f08152ddaf9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 5 Feb 2018 23:10:25 -0800 Subject: [PATCH 185/456] add remove_linked_list_elements --- .../RemoveLinkedListElement.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java diff --git a/src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java b/src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java new file mode 100644 index 0000000..9018a58 --- /dev/null +++ b/src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java @@ -0,0 +1,32 @@ +package remove_linked_list_elements; + +import common.ListNode; + +/** + * Created by lxie on 2/5/18. + */ +public class RemoveLinkedListElement { + + public class Solution { + ListNode removeElements(ListNode head, int val) { + ListNode dummy = new ListNode(-1); + ListNode pre = dummy; + dummy.next = head; + while (pre.next != null) { + if (pre.next.val == val) { + ListNode t = pre.next; + pre.next = t.next; + t.next = null; + } else { + pre = pre.next; + } + } + return dummy.next; + } + } + + public static class UnitTest { + + } + +} From 9b853843e6dc979ef07a6f50e98789cdbdb5c186 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 6 Feb 2018 10:37:32 -0800 Subject: [PATCH 186/456] modified course_schedule --- src/main/java/course_schedule/CourseSchedule.java | 3 +-- .../remove_linked_list_elements/RemoveLinkedListElement.java | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/course_schedule/CourseSchedule.java b/src/main/java/course_schedule/CourseSchedule.java index 537e809..8eb9346 100644 --- a/src/main/java/course_schedule/CourseSchedule.java +++ b/src/main/java/course_schedule/CourseSchedule.java @@ -22,8 +22,7 @@ public boolean canFinish(int numCourses, int[][] prerequisites) { int from = edge[1]; int to = edge[0]; inDegree[to]++; - List nodes = outNodes.get(from); - nodes.add(to); + outNodes.get(from).add(to); } while (!courses.isEmpty()) { List toRemoved = new ArrayList(); diff --git a/src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java b/src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java index 9018a58..79cccb8 100644 --- a/src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java +++ b/src/main/java/remove_linked_list_elements/RemoveLinkedListElement.java @@ -26,7 +26,7 @@ ListNode removeElements(ListNode head, int val) { } public static class UnitTest { - + } } From d24e66e8583679eba385721d3b53067fd42d63cf Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 6 Feb 2018 22:51:21 -0800 Subject: [PATCH 187/456] add course_schedule_ii --- .../course_schedule_ii/CourseScheduleII.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/course_schedule_ii/CourseScheduleII.java diff --git a/src/main/java/course_schedule_ii/CourseScheduleII.java b/src/main/java/course_schedule_ii/CourseScheduleII.java new file mode 100644 index 0000000..6d134ad --- /dev/null +++ b/src/main/java/course_schedule_ii/CourseScheduleII.java @@ -0,0 +1,50 @@ +package course_schedule_ii; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +/** + * Created by lxie on 2/6/18. + */ +public class CourseScheduleII { + + public class Solution { + public int[] findOrder(int numCourses, int[][] prerequisites) { + List res = new ArrayList<>(); + List> graph = new ArrayList<>(); + for (int i=0; i()); + int[] in = new int[numCourses]; + for (int[] a : prerequisites) { + graph.get(a[1]).add(a[0]); + ++in[a[0]]; + } + Queue q = new LinkedList<>(); + for (int i = 0; i < numCourses; ++i) { + if (in[i] == 0) q.add(i); + } + while (q.isEmpty() == false) { + int t = q.peek(); + res.add(t); // get result + q.poll(); + for (int a : graph.get(t)) { + --in[a]; + if (in[a] == 0) q.add(a); + } + } + if (res.size() != numCourses) res.clear(); // clear if cannot finish + return res.stream().mapToInt(i->i).toArray(); + + } + + } + + public static class UnitTest { + + + + } + +} From 065c44ecf28539f1070333a99be4d8842d5904d2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 7 Feb 2018 10:30:42 -0800 Subject: [PATCH 188/456] add word_dictionary --- .../java/add_search_word/AddSearchWord.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/main/java/add_search_word/AddSearchWord.java diff --git a/src/main/java/add_search_word/AddSearchWord.java b/src/main/java/add_search_word/AddSearchWord.java new file mode 100644 index 0000000..5156cf2 --- /dev/null +++ b/src/main/java/add_search_word/AddSearchWord.java @@ -0,0 +1,61 @@ +package add_search_word; + +/** + * Created by lxie on 2/7/18. + */ +public class AddSearchWord { + + public class WordDictionary { + + class TrieNode { + public TrieNode[] child = new TrieNode[26]; + public boolean isWord; + + public void TrieNode() { + for (TrieNode a : child) a = null; + } + + } + + public TrieNode root; + + public void WordDictionary(){ + root = new TrieNode(); + } + + public void addWord(String word) { + TrieNode p = root; + for (char a : word.toCharArray()) { + int i = a - 'a'; + if (p.child[i] == null) p.child[i] = new TrieNode(); + p = p.child[i]; + } + p.isWord = true; + } + + public boolean search(String word) { + return searchWord(word, root, 0); + } + + // use recursion for search to deal with wildcards + private boolean searchWord(String word, TrieNode p, int i) { + if (i == word.length()) return p.isWord; + if (word.toCharArray()[i] == '.') { + for (TrieNode a : p.child) { + if (a != null && searchWord(word, a, i + 1)) return true; + } + return false; + } else { + return p.child[word.toCharArray()[i] - 'a'] != null && + searchWord(word, p.child[word.toCharArray()[i] - 'a'], i + 1); + } + } + + } + + public static class UnitTest { + + + } + +} From 4d22b001173418791226bab571767e8a415581bd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 8 Feb 2018 10:03:59 -0800 Subject: [PATCH 189/456] add word_search_ii --- .../java/add_search_word/AddSearchWord.java | 6 +- .../java/word_search_ii/WordSearchII.java | 80 +++++++++++++++++++ 2 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 src/main/java/word_search_ii/WordSearchII.java diff --git a/src/main/java/add_search_word/AddSearchWord.java b/src/main/java/add_search_word/AddSearchWord.java index 5156cf2..52c11b8 100644 --- a/src/main/java/add_search_word/AddSearchWord.java +++ b/src/main/java/add_search_word/AddSearchWord.java @@ -11,7 +11,7 @@ class TrieNode { public TrieNode[] child = new TrieNode[26]; public boolean isWord; - public void TrieNode() { + public TrieNode() { for (TrieNode a : child) a = null; } @@ -19,7 +19,7 @@ public void TrieNode() { public TrieNode root; - public void WordDictionary(){ + public WordDictionary(){ root = new TrieNode(); } @@ -57,5 +57,5 @@ public static class UnitTest { } - + } diff --git a/src/main/java/word_search_ii/WordSearchII.java b/src/main/java/word_search_ii/WordSearchII.java new file mode 100644 index 0000000..27a3588 --- /dev/null +++ b/src/main/java/word_search_ii/WordSearchII.java @@ -0,0 +1,80 @@ +package word_search_ii; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 2/7/18. + */ +public class WordSearchII { + + public class Solution { + + public class TrieNode { + public TrieNode[] child = new TrieNode[26]; + public String str; + + public TrieNode() { + for (TrieNode a : child) a = null; + str = ""; + } + } + + public class Trie { + public TrieNode root; + + public Trie() { + root = new TrieNode(); + } + + public void insert(String s) { + TrieNode p = root; + for (char a : s.toCharArray()) { + int i = a - 'a'; + if (p.child[i] == null) p.child[i] = new TrieNode(); + p = p.child[i]; + } + p.str = s; + } + } + + public List findWords(char[][] board, String[] words) { + List res = new ArrayList<>(); + if (words.length == 0 || board.length == 0 || board[0].length == 0) return res; + boolean[][] visit = new boolean[board.length][board[0].length]; + + Trie T = new Trie(); + for (String a : words) T.insert(a); + for (int i = 0; i < board.length; ++i) { + for (int j = 0; j < board[i].length; ++j) { + if (T.root.child[board[i][j] - 'a'] != null) { + search(board, T.root.child[board[i][j] - 'a'], i, j, visit, res); + } + } + } + return res; + } + + private void search(char[][] board, TrieNode p, int i, int j, boolean[][] visit, List res) { + if (!p.str.isEmpty()) { + res.add(p.str); + p.str = ""; + } + int[][] d = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + visit[i][j] = true; + for (int[] a : d) { + int nx = a[0] + i, ny = a[1] + j; + if (nx >= 0 && nx < board.length && ny >= 0 && ny < board[0].length + && !visit[nx][ny] && p.child[board[nx][ny] - 'a'] != null) { + search(board, p.child[board[nx][ny] - 'a'], nx, ny, visit, res); + } + } + visit[i][j] = false; + } + } + + public class UnitTest { + + } + +} From 1f4291f876af03662056f1479817df1a42af6c87 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 9 Feb 2018 00:38:56 -0800 Subject: [PATCH 190/456] add combination sum iii --- .../CombinationSumIII.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/combination_sum_iii/CombinationSumIII.java diff --git a/src/main/java/combination_sum_iii/CombinationSumIII.java b/src/main/java/combination_sum_iii/CombinationSumIII.java new file mode 100644 index 0000000..c362e90 --- /dev/null +++ b/src/main/java/combination_sum_iii/CombinationSumIII.java @@ -0,0 +1,39 @@ +package combination_sum_iii; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 2/8/18. + */ +public class CombinationSumIII { + + public static class Solution { + // public List> res = new ArrayList<>(); + + public List> combinationSum3(int k, int n) { + List> res = new ArrayList<>(); + List out = new ArrayList<>(); + combinationSum3DFS(k, n, 1, out, res); + return res; + } + void combinationSum3DFS(int k, int n, int level, List out, List> res) { + if (n < 0 || out.size() > k) return; + if (n == 0 && out.size() == k) + res.add(new ArrayList(out)); + for (int i = level; i <= 9; ++i) { + out.add(i); + combinationSum3DFS(k, n - i, i + 1, out, res); + out.remove(out.size()-1); + } + } + } + + public static void main(String[] args) { + Solution s = new Solution(); + List> res = s.combinationSum3(3, 7); + System.out.println(res); + } + + +} From 0986001eeddc9e07a7843bdf20d19f417d525abe Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 9 Feb 2018 16:01:52 -0800 Subject: [PATCH 191/456] add max_square. --- src/main/java/max_square/MaxSquare.java | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/max_square/MaxSquare.java diff --git a/src/main/java/max_square/MaxSquare.java b/src/main/java/max_square/MaxSquare.java new file mode 100644 index 0000000..0d95cb8 --- /dev/null +++ b/src/main/java/max_square/MaxSquare.java @@ -0,0 +1,38 @@ +package max_square; + +/** + * Created by lxie on 2/9/18. + */ +public class MaxSquare { + + public class Solution { + public int maximalSquare(char[][] matrix) { + int res = 0; + for (int i = 0; i < matrix.length; ++i) { + int[] v = new int[matrix[i].length]; + for (int j = i; j < matrix.length; ++j) { + for (int k = 0; k < matrix[j].length; ++k) { + if (matrix[j][k] == '1') ++v[k]; + } + res = Integer.max(res, getSquareArea(v, j - i + 1)); + } + } + return res; + } + int getSquareArea(int[]v, int k) { + if (v.length < k) return 0; + int count = 0; + for (int i = 0; i < v.length; ++i) { + if (v[i] != k) count = 0; + else ++count; + if (count == k) return k * k; + } + return 0; + } + } + + public static class UnitTest { + + } + +} From 8b109c94149a56ecc9a37cdb88721beb495b5aa0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 10 Feb 2018 15:33:22 -0800 Subject: [PATCH 192/456] changes for best_time_to_buy_and_sell_stocks --- .../BestTimetoBuyandSellStock.java | 14 +++--- .../BestTimetoBuyandSellStockIII.java | 44 ++++++++++++------- 2 files changed, 34 insertions(+), 24 deletions(-) diff --git a/src/main/java/best_time_to_buy_and_sell_stock/BestTimetoBuyandSellStock.java b/src/main/java/best_time_to_buy_and_sell_stock/BestTimetoBuyandSellStock.java index 9ea71b8..2a320aa 100644 --- a/src/main/java/best_time_to_buy_and_sell_stock/BestTimetoBuyandSellStock.java +++ b/src/main/java/best_time_to_buy_and_sell_stock/BestTimetoBuyandSellStock.java @@ -4,16 +4,12 @@ public class BestTimetoBuyandSellStock { public class Solution { public int maxProfit(int[] prices) { - if (prices.length == 0) { - return 0; + int res = 0, buy = Integer.MAX_VALUE; + for (int price : prices) { + buy = Math.min(buy, price); + res = Math.max(res, price - buy); } - int maxProfit = 0; - int minPrice = prices[0]; - for (int i = 1; i < prices.length; i++) { - maxProfit = Math.max(maxProfit, prices[i] - minPrice); - minPrice = Math.min(minPrice, prices[i]); - } - return maxProfit; + return res; } } diff --git a/src/main/java/best_time_to_buy_and_sell_stock_iii/BestTimetoBuyandSellStockIII.java b/src/main/java/best_time_to_buy_and_sell_stock_iii/BestTimetoBuyandSellStockIII.java index 6c3a9fe..7632e55 100644 --- a/src/main/java/best_time_to_buy_and_sell_stock_iii/BestTimetoBuyandSellStockIII.java +++ b/src/main/java/best_time_to_buy_and_sell_stock_iii/BestTimetoBuyandSellStockIII.java @@ -4,24 +4,38 @@ public class BestTimetoBuyandSellStockIII { public class Solution { public int maxProfit(int[] prices) { - if (prices.length == 0) { - return 0; - } - int[] profit = new int[prices.length]; - profit[0] = 0; - int minPrice = prices[0]; - for (int i = 1; i < prices.length; i++) { - profit[i] = Math.max(profit[i - 1], prices[i] - minPrice); - minPrice = Math.min(minPrice, prices[i]); + int len = prices.length; + if (len==0) return 0; + + int[] historyProfit = new int[len]; + int[] futureProfit = new int[len]; + + int valley = prices[0]; + int peak = prices[len-1]; + int maxProfit = 0; + + // forward, calculate max profit until this time + for (int i = 0; i0) + { + historyProfit[i] = Integer.max(historyProfit[i-1],prices[i]-valley); + } } - int maxPrice = prices[prices.length - 1]; - int maxProfit = profit[prices.length - 1]; - for (int i = prices.length - 2; i > 0; i--) { - maxProfit = Math.max(maxProfit, profit[i - 1] + maxPrice - - prices[i]); - maxPrice = Math.max(maxPrice, prices[i]); + + // backward, calculate max profit from now, and then sum with history + for (int i = len-1; i>=0; --i) + { + peak = Integer.max(peak, prices[i]); + if (i Date: Sun, 11 Feb 2018 23:07:01 -0800 Subject: [PATCH 193/456] modify reverse_bits --- src/main/java/reverse_bits/ReverseBits.java | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/main/java/reverse_bits/ReverseBits.java b/src/main/java/reverse_bits/ReverseBits.java index 89d4510..1798c0c 100644 --- a/src/main/java/reverse_bits/ReverseBits.java +++ b/src/main/java/reverse_bits/ReverseBits.java @@ -3,18 +3,13 @@ public class ReverseBits { public class Solution { - public int reverseBits(int n) { - int reversed = 0; - int i; - for (i = 32; i > 0 && n != 0; i--) { - reversed = (reversed << 1) + (n & 1); - n >>= 1; + int res = 0; + for (int i = 0; i < 32; ++i) { + res |= ((n >> i) & 1) << (31 - i); } - reversed <<= i; - return reversed; + return res; } } - } From 1a020d144bd740f1d985dc08349cfd948d45086a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 11 Feb 2018 23:55:58 -0800 Subject: [PATCH 194/456] modify bitwise_and_of_all_numbers --- .../BitwiseANDofNumbersRange.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java b/src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java index 831ad07..b453547 100644 --- a/src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java +++ b/src/main/java/bitwise_and_of_numbers_range/BitwiseANDofNumbersRange.java @@ -4,15 +4,12 @@ public class BitwiseANDofNumbersRange { public class Solution { public int rangeBitwiseAnd(int m, int n) { - int r = 0; - for (int i = 0; i < 32 && n != 0; i++) { - if ((m & 1) != 0 && n == m) { - r |= (1 << i); - } - n >>>= 1; - m >>>= 1; + int d = Integer.MAX_VALUE; + while ((m & d) != (n & d)) { + d <<= 1; } - return r; + return m & d; + } } } From a1e596e6da37158acdb442cf1182bb745bffe9b4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 12 Feb 2018 00:13:58 -0800 Subject: [PATCH 195/456] modified isomorphic_strings --- .../isomorphic_strings/IsomorphicStrings.java | 51 +++++++++++++------ 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/src/main/java/isomorphic_strings/IsomorphicStrings.java b/src/main/java/isomorphic_strings/IsomorphicStrings.java index 3dd593a..573004c 100644 --- a/src/main/java/isomorphic_strings/IsomorphicStrings.java +++ b/src/main/java/isomorphic_strings/IsomorphicStrings.java @@ -1,32 +1,51 @@ package isomorphic_strings; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; public class IsomorphicStrings { public class Solution { - public boolean isIsomorphic(String s, String t) { - Map mapping = new HashMap(); - Set mapped = new HashSet(); - for (int i = 0; i < s.length(); i++) { - char c1 = s.charAt(i); - char c2 = t.charAt(i); - if (mapping.containsKey(c1)) { - if (mapping.get(c1) != c2) { - return false; + public boolean isIsomorphic(String str1, String str2) { + if (str1 == null || str2 == null) { + return false; + } + else if (str1.length() != str2.length()) { + return false; + } + else if (str1.length() < 2) { + // lengths are equal; empty string & 1 character strings are isomorphic + return true; + } + else { + char[] str1Chars = str1.toCharArray(); + char[] str2Chars = str2.toCharArray(); + + Map isoMap = new HashMap(); + Map isoMapRev = new HashMap(); + + + int length = str1Chars.length; + for (int index = 0; index < length; index++) { + + Character aCharacterFromFirstWord = str1Chars[index]; + Character aCharacterFromSecondWord = str2Chars[index]; + + if (isoMap.containsKey(aCharacterFromFirstWord)) { + if (!isoMap.get(aCharacterFromFirstWord).equals(aCharacterFromSecondWord)) { + return false; + } } - } else { - if (mapped.contains(c2)) { + else if (isoMapRev.containsKey(aCharacterFromSecondWord)) { return false; + } else { + isoMap.put(aCharacterFromFirstWord, aCharacterFromSecondWord); + isoMapRev.put(aCharacterFromSecondWord, aCharacterFromFirstWord); } - mapped.add(c2); - mapping.put(c1, c2); } + return true; } - return true; + } } } From 4c3f38a5084771433776ded6133a404f4b400fcd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 12 Feb 2018 00:56:48 -0800 Subject: [PATCH 196/456] add strobogrammatic_number --- .../StrobogrammaticNumber.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/strobogrammatic_number/StrobogrammaticNumber.java diff --git a/src/main/java/strobogrammatic_number/StrobogrammaticNumber.java b/src/main/java/strobogrammatic_number/StrobogrammaticNumber.java new file mode 100644 index 0000000..5cfb582 --- /dev/null +++ b/src/main/java/strobogrammatic_number/StrobogrammaticNumber.java @@ -0,0 +1,37 @@ +package strobogrammatic_number; + +/** + * Created by lxie on 2/12/18. + */ +public class StrobogrammaticNumber { + + public class Solution { + + boolean isStrobogrammatic(String num) { + char[] numi = num.toCharArray(); + int l = 0, r = numi.length - 1; + while (l <= r) { + if (numi[l] == numi[r]) { + if (numi[l] != '1' && numi[l] != '0' && numi[l] != '8'){ + return false; + } + } else { + // must be 6 o 9 if not equal + if ((numi[l] != '6' || numi[r] != '9') && (numi[l] != '9' || numi[r] != '6')) { + return false; + } + } + ++l; --r; + } + return true; + } + + + + } + + public static class UnitTest { + + } + +} From 4b4579b8c51f3f7d4f1de7605e4708e3fcb13fa0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 13 Feb 2018 10:14:16 -0800 Subject: [PATCH 197/456] add contains_duplicates_ii --- .../ContainsDuplicatesII.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/main/java/contains_duplicate_ii/ContainsDuplicatesII.java diff --git a/src/main/java/contains_duplicate_ii/ContainsDuplicatesII.java b/src/main/java/contains_duplicate_ii/ContainsDuplicatesII.java new file mode 100644 index 0000000..bcfc18d --- /dev/null +++ b/src/main/java/contains_duplicate_ii/ContainsDuplicatesII.java @@ -0,0 +1,25 @@ +package contains_duplicate_ii; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 2/13/18. + */ +public class ContainsDuplicatesII { + + public class Solution { + public boolean containsNearbyDuplicate(int[] nums, int k) { + Map m = new HashMap<>(); + for (int i = 0; i < nums.length; ++i) { + if (m.containsKey(nums[i]) && i - m.get(nums[i]) <= k) return true; + else m.put(nums[i], i); + } + return false; + } + } + + public static class UnitTest { + + } +} From 021537ed9cc7ec08286df9a3348a2995d38b7488 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 14 Feb 2018 12:22:21 -0800 Subject: [PATCH 198/456] add count_complete_tree_nodes --- .../ContainsDuplicatesIII.java | 50 +++++++++++++++++++ .../CountCompleteTreeNode.java | 35 +++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 src/main/java/contains_duplicates_iii/ContainsDuplicatesIII.java create mode 100644 src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java diff --git a/src/main/java/contains_duplicates_iii/ContainsDuplicatesIII.java b/src/main/java/contains_duplicates_iii/ContainsDuplicatesIII.java new file mode 100644 index 0000000..0a62bf8 --- /dev/null +++ b/src/main/java/contains_duplicates_iii/ContainsDuplicatesIII.java @@ -0,0 +1,50 @@ +package contains_duplicates_iii; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 2/13/18. + */ +public class ContainsDuplicatesIII { + + public static class Solution { + + public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { + Map m = new HashMap<>(); + int j = 0; + for (int i = 0; i < nums.length; ++i) { + if (i - j > k && m.get(nums[j]) == j) m.remove(nums[j++]); + int[] lower = new int[1]; + boolean a = lower_bound(m, (long) nums[i] - t, lower); + if (a && Math.abs((long) lower[0] - nums[i]) <= t) return true; + m.put(nums[i], i); + } + return false; + } + + + // TODO - need a better algorithm !!! + private boolean lower_bound(Map m, long v, int[] res) { + long min_diff = Long.MAX_VALUE; + for (int key : m.keySet()) { + if (key >= v && key - v < min_diff) + min_diff = key - v; + } + if (min_diff == Long.MAX_VALUE) + return false; + else { + res[0] = (int) (v + min_diff); + return true; + } + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + int[] a = {2147483647, -2147483647}; + boolean res = sol.containsNearbyAlmostDuplicate(a, 1, 2147483647); + System.out.println(res); + } +} diff --git a/src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java b/src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java new file mode 100644 index 0000000..31d9206 --- /dev/null +++ b/src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java @@ -0,0 +1,35 @@ +package count_complete_tree_nodes; + +import common.TreeNode; + +/** + * Created by lxie on 2/14/18. + */ +public class CountCompleteTreeNode { + + public class Solution { + + public int countNodes(TreeNode root) { + int hLeft = leftHeight(root); + int hRight = rightHeight(root); + if (hLeft == hRight) return (int) Math.pow(2, hLeft) - 1; + return countNodes(root.left) + countNodes(root.right) + 1; + } + int leftHeight(TreeNode root) { // height of left-most + if (root == null) return 0; + return 1 + leftHeight(root.left); + } + int rightHeight(TreeNode root) { // height of righ-most + if (root == null) return 0; + return 1 + rightHeight(root.right); + } + + } + + public static class UnitTest { + + + } + + +} From abf56c0a95a0a10c2aed4a817d423dcfc3c828ee Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 14 Feb 2018 16:27:44 -0800 Subject: [PATCH 199/456] add basic_calculator --- .../basic_calculator/BasicCalculator.java | 38 +++++++++++++++++++ .../CountCompleteTreeNode.java | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/main/java/basic_calculator/BasicCalculator.java diff --git a/src/main/java/basic_calculator/BasicCalculator.java b/src/main/java/basic_calculator/BasicCalculator.java new file mode 100644 index 0000000..69a9785 --- /dev/null +++ b/src/main/java/basic_calculator/BasicCalculator.java @@ -0,0 +1,38 @@ +package basic_calculator; + +import java.util.Stack; + +/** + * Created by lxie on 2/14/18. + */ +public class BasicCalculator { + + public class Solution { + + int calculate(String s) { + int res = 0; + Stack sign = new Stack<>(); + sign.push(1); sign.push(1); + char[] str = s.toCharArray(); + for (int i = 0; i < s.length(); ++i) { + char c = str[i]; + if (c >= '0') { + int num = 0; + while (i < s.length() && str[i] >= '0') { + num = 10 * num + str[i++] - '0'; + } + res += sign.peek() * num; + sign.pop(); + --i; + } + else if (c == ')') sign.pop(); + else if (c != ' ') sign.push(sign.peek() * (c == '-' ? -1 : 1)); + } + return res; + } + } + + public static class UnitTest { + + } +} diff --git a/src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java b/src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java index 31d9206..477a3c1 100644 --- a/src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java +++ b/src/main/java/count_complete_tree_nodes/CountCompleteTreeNode.java @@ -23,7 +23,7 @@ int rightHeight(TreeNode root) { // height of righ-most if (root == null) return 0; return 1 + rightHeight(root.right); } - + } public static class UnitTest { From fe1c0cbfd4439e1ef06879382dbc7429a4a384d0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 15 Feb 2018 11:06:45 -0800 Subject: [PATCH 200/456] add implement_stack_using_queues --- .../StackUsingQueues.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/implement_stack_using_queues/StackUsingQueues.java diff --git a/src/main/java/implement_stack_using_queues/StackUsingQueues.java b/src/main/java/implement_stack_using_queues/StackUsingQueues.java new file mode 100644 index 0000000..a314337 --- /dev/null +++ b/src/main/java/implement_stack_using_queues/StackUsingQueues.java @@ -0,0 +1,54 @@ +package implement_stack_using_queues; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by lxie on 2/15/18. + */ +public class StackUsingQueues { + + class MyStack { + + private Queue q = new LinkedList<>(); + + /** Initialize your data structure here. */ + public MyStack() { + + } + + /** Push element x onto stack. */ + public void push(int x) { + Queue tmp = new LinkedList<>(); + while (!q.isEmpty()) { + tmp.add(q.peek()); + q.remove(); + } + q.add(x); + while (!tmp.isEmpty()) { + q.add(tmp.peek()); + tmp.remove(); + } + + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + return q.remove(); + } + + /** Get the top element. */ + public int top() { + return q.peek(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return q.isEmpty(); + } + } + + public static class UnitTest { + + } +} From d2942804791b16f3cc9a1ae5329a661deecbd767 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 19 Feb 2018 00:40:31 -0800 Subject: [PATCH 201/456] add invert_binary_tree --- .../invert_binary_tree/InvertBinaryTree.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/invert_binary_tree/InvertBinaryTree.java diff --git a/src/main/java/invert_binary_tree/InvertBinaryTree.java b/src/main/java/invert_binary_tree/InvertBinaryTree.java new file mode 100644 index 0000000..2747f9d --- /dev/null +++ b/src/main/java/invert_binary_tree/InvertBinaryTree.java @@ -0,0 +1,44 @@ +package invert_binary_tree; + +import common.TreeNode; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by lxie on 2/18/18. + */ +public class InvertBinaryTree { + + public class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) return null; + TreeNode tmp = root.left; + root.left = invertTree(root.right); + root.right = invertTree(tmp); + return root; + } + + public TreeNode invertTree1(TreeNode root) { + if (root == null) return null; + Queue q = new LinkedList<>(); + q.add(root); + while (!q.isEmpty()) { + TreeNode node = q.peek(); + q.remove(); + TreeNode tmp = node.left; + node.left = node.right; + node.right = tmp; + if (node.left != null) q.add(node.left); + if (node.right != null) q.add(node.right); + } + return root; + } + + } + + public static class UnitTest { + + } + +} From e57990e45f34d9828ae91438f8e95305c165d434 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 21 Feb 2018 10:46:23 -0800 Subject: [PATCH 202/456] add basic_calculator_ii --- .../BasicCalculatorII.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/basic_calculator_ii/BasicCalculatorII.java diff --git a/src/main/java/basic_calculator_ii/BasicCalculatorII.java b/src/main/java/basic_calculator_ii/BasicCalculatorII.java new file mode 100644 index 0000000..e01603f --- /dev/null +++ b/src/main/java/basic_calculator_ii/BasicCalculatorII.java @@ -0,0 +1,45 @@ +package basic_calculator_ii; + +import java.util.Stack; + +/** + * Created by lxie on 2/21/18. + */ +public class BasicCalculatorII { + + public class Solution { + public int calculate(String s) { + int res = 0, d = 0; + char sign = '+'; + char[] str = s.toCharArray(); + Stack nums = new Stack<>(); + for (int i = 0; i < s.length(); ++i) { + if (str[i] >= '0') { + d = d * 10 + str[i] - '0'; + } + if ((str[i] < '0' && str[i] != ' ') || i == s.length() - 1) { + if (sign == '+') nums.push(d); + if (sign == '-') nums.push(-d); + if (sign == '*' || sign == '/') { + int tmp = sign == '*' ? nums.peek() * d : nums.peek() / d; + nums.pop(); + nums.push(tmp); + } + sign = str[i]; // operator before number + d = 0; + } + } + while (!nums.empty()) { + res += nums.peek(); + nums.pop(); + } + return res; + + } + } + + public static class UnitTest { + + } + +} From f4fecadba9266cb101767d817c0ac56168161d58 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 28 Feb 2018 02:16:04 -0800 Subject: [PATCH 203/456] add summary_ranges --- .../java/summary_ranges/SummaryRanges.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/summary_ranges/SummaryRanges.java diff --git a/src/main/java/summary_ranges/SummaryRanges.java b/src/main/java/summary_ranges/SummaryRanges.java new file mode 100644 index 0000000..cd0053f --- /dev/null +++ b/src/main/java/summary_ranges/SummaryRanges.java @@ -0,0 +1,30 @@ +package summary_ranges; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 2/28/18. + */ +public class SummaryRanges { + + public class Solution { + public List summaryRanges(int[] nums) { + List res = new ArrayList<>(); + int i = 0, n = nums.length; + while (i < n) { + int j = 1; + while (i + j < n && nums[i + j] - nums[i] == j) ++j; + res.add(j <= 1 ? Integer.toString(nums[i]) : Integer.toString(nums[i]) + + "->" + Integer.toString(nums[i + j - 1])); + i += j; + } + return res; + } + } + + public static class UnitTest { + + } + +} From 0025f5115cc0c1c053909b120a0951ed48635e25 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 28 Feb 2018 02:46:47 -0800 Subject: [PATCH 204/456] add majority_element_ii --- .../MajorityElementII.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/majority_element_ii/MajorityElementII.java diff --git a/src/main/java/majority_element_ii/MajorityElementII.java b/src/main/java/majority_element_ii/MajorityElementII.java new file mode 100644 index 0000000..44e1566 --- /dev/null +++ b/src/main/java/majority_element_ii/MajorityElementII.java @@ -0,0 +1,37 @@ +package majority_element_ii; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 2/28/18. + */ +public class MajorityElementII { + + public class Solution { + public List majorityElement(int[] nums) { + List res = new ArrayList<>(); + int m = 0, n = 0, cm = 0, cn = 0; + for (int a : nums) { // find two majority + if (a == m) ++cm; + else if (a ==n) ++cn; + else if (cm == 0) { m = a; cm = 1; } + else if (cn == 0) { n = a; cn = 1; } + else { --cm; --cn; } + } + cm = cn = 0; + for (int a : nums) { // verify if > n/3 + if (a == m) ++cm; + else if (a == n) ++cn; + } + if (cm > nums.length / 3) res.add(m); + if (cn > nums.length / 3) res.add(n); + return res; + + } + } + + public static class UnitTest { + + } +} From 13008f5398953ff79b2600bead449bfeacec3bc0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 5 Mar 2018 10:39:11 -0800 Subject: [PATCH 205/456] add kth_smallest_bst --- .../kth_smallest_in_bst/KthSmallestInBst.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/kth_smallest_in_bst/KthSmallestInBst.java diff --git a/src/main/java/kth_smallest_in_bst/KthSmallestInBst.java b/src/main/java/kth_smallest_in_bst/KthSmallestInBst.java new file mode 100644 index 0000000..d253939 --- /dev/null +++ b/src/main/java/kth_smallest_in_bst/KthSmallestInBst.java @@ -0,0 +1,49 @@ +package kth_smallest_in_bst; + +import common.TreeNode; + +import java.util.Stack; + +/** + * Created by lxie on 3/2/18. + */ +public class KthSmallestInBst { + + public class Solution { + public int kthSmallest(TreeNode root, int k) { + int[] c = {k}; + return kthSmallestDFS(root, c); + } + + private int kthSmallestDFS(TreeNode root, int[] c) { + if (root == null) return -1; + int val = kthSmallestDFS(root.left, c); + if (c[0] == 0) return val; + if (--c[0] == 0) return root.val; + return kthSmallestDFS(root.right, c); + } + + // non-recursive + public int kthSmallest2(TreeNode root, int k) { + int cnt = 0; + Stack s = new Stack<>(); + TreeNode p = root; + while (p != null || !s.empty()) { + while (p != null) { + s.push(p); + p = p.left; + } + p = s.peek(); s.pop(); + ++cnt; + if (cnt == k) return p.val; + p = p.right; + } + return 0; + } + } + + public static class UnitTest { + + } + +} From eb9c4dfbb86cc874601d6ab32fb7aac794810361 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 5 Mar 2018 10:50:48 -0800 Subject: [PATCH 206/456] add implement_queue_using_stack --- .../QueueUsingStacks.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/implement_queue_using_stacks/QueueUsingStacks.java diff --git a/src/main/java/implement_queue_using_stacks/QueueUsingStacks.java b/src/main/java/implement_queue_using_stacks/QueueUsingStacks.java new file mode 100644 index 0000000..38e523e --- /dev/null +++ b/src/main/java/implement_queue_using_stacks/QueueUsingStacks.java @@ -0,0 +1,54 @@ +package implement_queue_using_stacks; + +import java.util.Stack; + +/** + * Created by lxie on 3/5/18. + */ +public class QueueUsingStacks { + + class MyQueue { + + private Stack s = new Stack<>(); + + /** Initialize your data structure here. */ + public MyQueue() { + + } + + /** Push element x onto stack. */ + public void push(int x) { + Stack tmp = new Stack<>(); + while (!s.isEmpty()) { + tmp.push(s.peek()); + s.pop(); + } + s.push(x); + while (!tmp.isEmpty()) { + s.push(tmp.peek()); + tmp.pop(); + } + + } + + /** Removes the element on top of the stack and returns that element. */ + public int pop() { + return s.pop(); + } + + /** Get the top element. */ + public int peek() { + return s.peek(); + } + + /** Returns whether the stack is empty. */ + public boolean empty() { + return s.isEmpty(); + } + } + + public static class UnitTest { + + } + +} From 8f74e88d1b7d79684e2e093b71ae61d533c65423 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 6 Mar 2018 10:18:43 -0800 Subject: [PATCH 207/456] add search_a_2d_matrix_ii --- .../Search2DMatrixII.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/search_a_2d_matrix_ii/Search2DMatrixII.java diff --git a/src/main/java/search_a_2d_matrix_ii/Search2DMatrixII.java b/src/main/java/search_a_2d_matrix_ii/Search2DMatrixII.java new file mode 100644 index 0000000..d63e653 --- /dev/null +++ b/src/main/java/search_a_2d_matrix_ii/Search2DMatrixII.java @@ -0,0 +1,27 @@ +package search_a_2d_matrix_ii; + +/** + * Created by lxie on 3/6/18. + */ +public class Search2DMatrixII { + + public class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + if (matrix.length == 0 || matrix[0].length == 0) return false; + if (target < matrix[0][0] || target > matrix[matrix.length-1][matrix[0].length-1]) + return false; + int x = matrix.length - 1, y = 0; + while (true) { + if (matrix[x][y] > target) --x; + else if (matrix[x][y] < target) ++y; + else return true; + if (x < 0 || y >= matrix[0].length) break; + } + return false; + } + } + + public static class UnitTest { + + } +} From 6b879628054a617e144636193c360798a49efaf4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 6 Mar 2018 10:29:36 -0800 Subject: [PATCH 208/456] add valid_anagram --- src/main/java/valid_anagram/ValidAnagram.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/main/java/valid_anagram/ValidAnagram.java diff --git a/src/main/java/valid_anagram/ValidAnagram.java b/src/main/java/valid_anagram/ValidAnagram.java new file mode 100644 index 0000000..d7d83ff --- /dev/null +++ b/src/main/java/valid_anagram/ValidAnagram.java @@ -0,0 +1,24 @@ +package valid_anagram; + +/** + * Created by lxie on 3/6/18. + */ +public class ValidAnagram { + + public class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) return false; + int[] m = new int[26]; + for (int i = 0; i < s.length(); ++i) ++m[s.toCharArray()[i] - 'a']; + for (int i = 0; i < t.length(); ++i) { + if (--m[t.toCharArray()[i] - 'a'] < 0) return false; + } + return true; + } + } + + public static class UnitTest { + + } + +} From 0c59ffcb817fcc432713605110b4be386d4f4ef3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 7 Mar 2018 10:14:38 -0800 Subject: [PATCH 209/456] add shortest_word_distance --- .../ShortestWordDistance.java | 28 +++++++++++++++++++ src/main/java/valid_anagram/ValidAnagram.java | 7 +++-- 2 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 src/main/java/shortest_word_distance/ShortestWordDistance.java diff --git a/src/main/java/shortest_word_distance/ShortestWordDistance.java b/src/main/java/shortest_word_distance/ShortestWordDistance.java new file mode 100644 index 0000000..1a88265 --- /dev/null +++ b/src/main/java/shortest_word_distance/ShortestWordDistance.java @@ -0,0 +1,28 @@ +package shortest_word_distance; + +import java.util.List; + +import static java.lang.StrictMath.abs; + +/** + * Created by lxie on 3/7/18. + */ +public class ShortestWordDistance { + + public class Solution { + int shortestDistance(List words, String word1, String word2) { + int p1 = -1, p2 = -1, res = Integer.MAX_VALUE; + for (int i = 0; i < words.size(); ++i) { + if (words.toArray()[i] == word1) p1 = i; + if (words.toArray()[i] == word2) p2 = i; + if (p1 != -1 && p2 != -1) res = Math.min(res, abs(p1 - p2)); + } + return res; + } + } + + public static class UnitTest { + + } + +} diff --git a/src/main/java/valid_anagram/ValidAnagram.java b/src/main/java/valid_anagram/ValidAnagram.java index d7d83ff..606b299 100644 --- a/src/main/java/valid_anagram/ValidAnagram.java +++ b/src/main/java/valid_anagram/ValidAnagram.java @@ -7,10 +7,11 @@ public class ValidAnagram { public class Solution { public boolean isAnagram(String s, String t) { - if (s.length() != t.length()) return false; + int lens = s.length(), lent = t.length(); + if (lens != lent) return false; int[] m = new int[26]; - for (int i = 0; i < s.length(); ++i) ++m[s.toCharArray()[i] - 'a']; - for (int i = 0; i < t.length(); ++i) { + for (int i = 0; i < lens; ++i) ++m[s.toCharArray()[i] - 'a']; + for (int i = 0; i < lent; ++i) { if (--m[t.toCharArray()[i] - 'a'] < 0) return false; } return true; From 7f5b836c89d24fd78db3374f3bd3cd35c181cd3e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 7 Mar 2018 10:32:39 -0800 Subject: [PATCH 210/456] add shortest_word_distance_ii --- .../ShortestWordDistanceII.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/shortest_word_distance_ii/ShortestWordDistanceII.java diff --git a/src/main/java/shortest_word_distance_ii/ShortestWordDistanceII.java b/src/main/java/shortest_word_distance_ii/ShortestWordDistanceII.java new file mode 100644 index 0000000..c11a169 --- /dev/null +++ b/src/main/java/shortest_word_distance_ii/ShortestWordDistanceII.java @@ -0,0 +1,37 @@ +package shortest_word_distance_ii; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 3/7/18. + */ +public class ShortestWordDistanceII { + + private Map> m = new HashMap<>(); + + public ShortestWordDistanceII(List words) { + for (int i = 0; i < words.size(); ++i) { + String s = words.get(i); + if (m.containsKey(s)) m.get(s).add(i); + else + m.put(s, new ArrayList(i)); + } + } + + public int shortest(String word1, String word2) { + int i = 0, j = 0, res = Integer.MAX_VALUE; + int len1 = m.containsKey(word1) ? m.get(word1).size() : -1; + int len2 = m.containsKey(word2) ? m.get(word2).size() : -1; + if (len1 <= 0 || len2 <= 0) return -1; + + while (i < len1 && j < len2) { + res = Math.min(res, Math.abs(m.get(word1).get(i) - m.get(word2).get(j))); + if (m.get(word1).get(i) < m.get(word2).get(j)) ++i; + else ++j; + } + return res; + } +} From acfb3a118b350623f007e644bcc98db286dbf9f3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 8 Mar 2018 03:11:17 -0800 Subject: [PATCH 211/456] add shortest_word_distance_iii --- .../ShortestWordDistanceIII.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/shortest_word_distance_iii/ShortestWordDistanceIII.java diff --git a/src/main/java/shortest_word_distance_iii/ShortestWordDistanceIII.java b/src/main/java/shortest_word_distance_iii/ShortestWordDistanceIII.java new file mode 100644 index 0000000..d916220 --- /dev/null +++ b/src/main/java/shortest_word_distance_iii/ShortestWordDistanceIII.java @@ -0,0 +1,28 @@ +package shortest_word_distance_iii; + +import java.util.List; + +import static java.lang.StrictMath.abs; + +/** + * Created by lxie on 3/8/18. + */ +public class ShortestWordDistanceIII { + + public class Solution { + int shortestDistance(List words, String word1, String word2) { + int p1 = words.size(), p2 = -words.size(), res = Integer.MAX_VALUE; + for (int i = 0; i < words.size(); ++i) { + if (words.toArray()[i] == word1) p1 = word1 == word2 ? p2 : i; + if (words.toArray()[i] == word2) p2 = i; + if (p1 != -1 && p2 != -1) res = Math.min(res, abs(p1 - p2)); + } + return res; + } + } + + public static class UnitTest { + + } + +} From 146669b3b1eedd78ae9402ba186b90d5117a58a4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 15 Mar 2018 01:11:50 -0700 Subject: [PATCH 212/456] add strobogrammatic_number_ii --- .../StrobogrammaticNumberII.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/strobogrammatic_number_ii/StrobogrammaticNumberII.java diff --git a/src/main/java/strobogrammatic_number_ii/StrobogrammaticNumberII.java b/src/main/java/strobogrammatic_number_ii/StrobogrammaticNumberII.java new file mode 100644 index 0000000..bc01f92 --- /dev/null +++ b/src/main/java/strobogrammatic_number_ii/StrobogrammaticNumberII.java @@ -0,0 +1,41 @@ +package strobogrammatic_number_ii; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 3/15/18. + */ +public class StrobogrammaticNumberII { + + public static class Solution { + + public List findStrobogrammatic(int n) { + return find(n, n); + } + + private List find(int m, int n) { + if (m == 0) return new ArrayList(Arrays.asList("")); + if (m == 1) return new ArrayList(Arrays.asList("0", "1", "8")); + List t = find(m - 2, n); + List res = new ArrayList<>(); + for (String a : t) { + if (m != n) res.add("0" + a + "0"); // cannot add 0 when m = n + res.add("1" + a + "1"); + res.add("6" + a + "9"); + res.add("8" + a + "8"); + res.add("9" + a + "6"); + } + return res; + } + + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution s = new Solution(); + System.out.println(s.findStrobogrammatic(3)); + } + +} From 7b2fc6b56c9343d2e9a9bf8763ff9f7ff2bf20d8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 16 Mar 2018 16:55:30 -0700 Subject: [PATCH 213/456] add strobogrammatic_number_iii --- .../StrobogrammaticNumberIII.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/strobogrammatic_number_iii/StrobogrammaticNumberIII.java diff --git a/src/main/java/strobogrammatic_number_iii/StrobogrammaticNumberIII.java b/src/main/java/strobogrammatic_number_iii/StrobogrammaticNumberIII.java new file mode 100644 index 0000000..8ae997e --- /dev/null +++ b/src/main/java/strobogrammatic_number_iii/StrobogrammaticNumberIII.java @@ -0,0 +1,40 @@ +package strobogrammatic_number_iii; + +/** + * Created by lxie on 3/16/18. + */ +public class StrobogrammaticNumberIII { + + public static class Solution { + public int strobogrammaticInRange(String low, String high) { + int[] res = new int[1]; + find(low, high, "", res); + find(low, high, "0", res); + find(low, high, "1", res); + find(low, high, "8", res); + return res[0]; + } + + private void find(String low, String high, String w, int[] res) { + if (w.length() >= low.length() && w.length() <= high.length()) { + if ((w.length() == low.length() && w.compareTo(low) < 0) || + (w.length() == high.length() && w.compareTo(high) > 0)) { + return; + } + if (!(w.length() > 1 && w.toCharArray()[0] == '0')) ++res[0]; + } + if (w.length() + 2 > high.length()) return; + find(low, high, "0" + w + "0", res); + find(low, high, "1" + w + "1", res); + find(low, high, "6" + w + "9", res); + find(low, high, "8" + w + "8", res); + find(low, high, "9" + w + "6", res); + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution s = new Solution(); + System.out.println(s.strobogrammaticInRange("50", "100")); + } +} From ef50e0d63bed5344dd1b4d267ccc0dac9dd8c30a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 19 Mar 2018 01:15:01 -0700 Subject: [PATCH 214/456] add group_shifted_string --- .../GroupShiftedString.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/group_shifted_string/GroupShiftedString.java diff --git a/src/main/java/group_shifted_string/GroupShiftedString.java b/src/main/java/group_shifted_string/GroupShiftedString.java new file mode 100644 index 0000000..46e8554 --- /dev/null +++ b/src/main/java/group_shifted_string/GroupShiftedString.java @@ -0,0 +1,43 @@ +package group_shifted_string; + +import java.util.*; + +/** + * Created by lxie on 3/19/18. + */ +public class GroupShiftedString { + + public static class Solution { + + List> groupStrings(List strings) { + List> res = new ArrayList<>(); + Map> m = new HashMap<>(); + for (String a : strings) { + String t = ""; + for (char c : a.toCharArray()) { + t += Integer.toString((c + 26 - a.toCharArray()[0]) % 26) + ","; + } + if (!m.containsKey(t)) { + TreeSet tset = new TreeSet<>(); + tset.add(a); + m.put(t, tset); + } else { + m.get(t).add(a); + } + } + for (Map.Entry> entry : m.entrySet()) { + res.add(new ArrayList<>(entry.getValue())); + } + return res; + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution s = new Solution(); + List strings = new ArrayList(Arrays.asList( + "abc", "bcd", "acef", "xyz", "az", "ba", "a", "z")); + System.out.println(s.groupStrings(strings)); + } + +} From f460df574daa9d7038d47c7a4c112dafcee6fb61 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 24 May 2018 11:48:34 -0700 Subject: [PATCH 215/456] add count_univalue_subtrees --- .../CountUnivalueSubtrees.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/count_univalue_subtrees/CountUnivalueSubtrees.java diff --git a/src/main/java/count_univalue_subtrees/CountUnivalueSubtrees.java b/src/main/java/count_univalue_subtrees/CountUnivalueSubtrees.java new file mode 100644 index 0000000..0343aa3 --- /dev/null +++ b/src/main/java/count_univalue_subtrees/CountUnivalueSubtrees.java @@ -0,0 +1,43 @@ +package count_univalue_subtrees; + +import common.TreeNode; + +/** + * Created by lxie on 5/23/18. + */ +public class CountUnivalueSubtrees { + + public static class Solution { + + public int countUnivalSubtrees (TreeNode root) { + int[] res = new int[1]; + isUnival(root, -1, res); + return res[0]; + } + + private boolean isUnival(TreeNode root, int val, int[] res) { + if (root == null) return true; + if (!isUnival(root.left, root.val, res) | !isUnival(root.right, root.val, res)) { + return false; + } + ++res[0]; + return root.val == val; + } + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + TreeNode root = new TreeNode(5); + root.left = new TreeNode(1); root.right = new TreeNode(5); + root.left.left = new TreeNode(5); root.left.right = new TreeNode(5); + root.right.right = new TreeNode(5); + + int res = sol.countUnivalSubtrees(root); + + System.out.println("result is " + res); + } + + +} From 20c18834ff341b67d595d074a60688a53605baa5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 25 May 2018 12:59:26 -0700 Subject: [PATCH 216/456] add meeting_rooms --- src/main/java/meeting_rooms/MeetingRooms.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/meeting_rooms/MeetingRooms.java diff --git a/src/main/java/meeting_rooms/MeetingRooms.java b/src/main/java/meeting_rooms/MeetingRooms.java new file mode 100644 index 0000000..5c3fbd7 --- /dev/null +++ b/src/main/java/meeting_rooms/MeetingRooms.java @@ -0,0 +1,39 @@ +package meeting_rooms; + +import common.Interval; + +import java.util.Arrays; +import java.util.Comparator; + +/** + * Created by lxie on 5/25/18. + */ +public class MeetingRooms { + + public class Solution { + + public boolean canAttendMeetings(Interval[] intervals) { + if(intervals == null || intervals.length == 0) return true; + Arrays.sort(intervals, new Comparator(){ + @Override + public int compare(Interval i1, Interval i2){ + return i1.start - i2.start; + } + }); + for (int i = 1; i < intervals.length; ++i) { + if (intervals[i].start < intervals[i - 1].end) { + return false; + } + } + return true; + } + } + + public class UnitTest { + + + + } + + +} From 053258a80c3ed0acd96592a15dc60f0ab3c5cf9a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 26 May 2018 01:42:36 -0700 Subject: [PATCH 217/456] add meeting_rooms_ii --- .../java/meeting_rooms_ii/MeetingRoomsII.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/meeting_rooms_ii/MeetingRoomsII.java diff --git a/src/main/java/meeting_rooms_ii/MeetingRoomsII.java b/src/main/java/meeting_rooms_ii/MeetingRoomsII.java new file mode 100644 index 0000000..1f8412b --- /dev/null +++ b/src/main/java/meeting_rooms_ii/MeetingRoomsII.java @@ -0,0 +1,56 @@ +package meeting_rooms_ii; + +import common.Interval; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static java.lang.Integer.max; + +/** + * Created by lxie on 5/25/18. + */ +public class MeetingRoomsII { + + public static class Solution { + + public int minMeetingRooms(List intervals) { + Map m = new TreeMap<>(); + for (Interval a : intervals) { + if (m.containsKey(a.start)) { + m.put(a.start, m.get(a.start)+1); + } else { + m.put(a.start, 1); + } + + if (m.containsKey(a.end)) { + m.put(a.end, m.get(a.end)-1); + } else{ + m.put(a.end, -1); + } + } + int rooms = 0, res = 0; + for ( Map.Entry i : m.entrySet()) { + res = max(res, rooms += i.getValue()); + } + return res; + } + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + List intervals = new ArrayList<>(); + intervals.add(new Interval(0, 30)); + intervals.add(new Interval(5, 10)); + intervals.add(new Interval(15, 20)); + + int res = sol.minMeetingRooms(intervals); + System.out.println("result is " + res); + } + + +} From 5ba1bb3286d55456ca25a2235915bef4a9bd64f0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 27 May 2018 02:32:08 -0700 Subject: [PATCH 218/456] add factor_combinations --- .../FactorCombinations.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/factor_combinations/FactorCombinations.java diff --git a/src/main/java/factor_combinations/FactorCombinations.java b/src/main/java/factor_combinations/FactorCombinations.java new file mode 100644 index 0000000..7e9ec36 --- /dev/null +++ b/src/main/java/factor_combinations/FactorCombinations.java @@ -0,0 +1,40 @@ +package factor_combinations; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 5/27/18. + */ +public class FactorCombinations { + + public static class Solution { + + public List> getFactors(int n) { + List> res = new ArrayList<>(); + helper(n, 2, new ArrayList(), res); + return res; + } + + void helper(int n, int start, List out, List> res) { + if (n == 1) { + if (out.size() > 1) res.add(new ArrayList<>(out)); + } else { + for (int i = start; i <= n; ++i) { + if (n % i == 0) { + out.add(i); + helper(n / i, i, out, res); + out.remove(out.size()-1); + } + } + } + } + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + System.out.println("result is " + sol.getFactors(32)); + } + +} From 9f831dc12130666d4b84ae6eaeb01ec8ac3c493d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 28 May 2018 18:03:27 -0700 Subject: [PATCH 219/456] add verify_preorder_sequence_bst --- .../PreorderSeqBst.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java diff --git a/src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java b/src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java new file mode 100644 index 0000000..49ae65a --- /dev/null +++ b/src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java @@ -0,0 +1,38 @@ +package verify_preorder_sequence_bst; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Stack; + +/** + * Created by lxie on 5/28/18. + */ +public class PreorderSeqBst { + + public static class Solution { + + public boolean verifyPreorder(List preorder) { + int low = Integer.MIN_VALUE; + Stack s = new Stack<>(); + for (int a : preorder) { + if (a < low) return false; + while (!s.empty() && a > s.peek()) { + low = s.peek(); s.pop(); + } + s.push(a); + } + return true; + } + + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + boolean res = sol.verifyPreorder(new ArrayList(Arrays.asList(5, 2, 1, 3, 6, 8, 7))); + System.out.println("result is " + res); + } + + +} From 8895ddcd4184b5678c7fcf065f8285b00d179f3c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 3 Jun 2018 01:34:13 -0700 Subject: [PATCH 220/456] add paint_house --- src/main/java/paint_house/PaintHouse.java | 29 +++++++++++++++++++ .../PreorderSeqBst.java | 16 +++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/main/java/paint_house/PaintHouse.java diff --git a/src/main/java/paint_house/PaintHouse.java b/src/main/java/paint_house/PaintHouse.java new file mode 100644 index 0000000..d765a42 --- /dev/null +++ b/src/main/java/paint_house/PaintHouse.java @@ -0,0 +1,29 @@ +package paint_house; + +/** + * Created by lxie on 6/3/18. + */ +public class PaintHouse { + + public static class Solution { + + int minCost(int [][] costs) { + if (costs.length == 0 || costs[0].length == 0) return 0; + int[][] dp = costs; + for (int i = 1; i < dp.length; ++i) { + for (int j = 0; j < 3; ++j) { + dp[i][j] += Integer.min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]); + } + } + int n = dp.length; + return Integer.min(Integer.min(dp[n-1][0], dp[n-1][1]), dp[n-1][2]); + } + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int[][] costs= {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}; + int res = sol.minCost(costs); + System.out.println("result is "+res); + } +} diff --git a/src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java b/src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java index 49ae65a..42940b3 100644 --- a/src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java +++ b/src/main/java/verify_preorder_sequence_bst/PreorderSeqBst.java @@ -26,11 +26,25 @@ public boolean verifyPreorder(List preorder) { } + public boolean verifyPreorderRecursive(List preorder) { + return helper(preorder, 0, preorder.size() - 1, Integer.MIN_VALUE, Integer.MAX_VALUE); + } + + boolean helper(List preorder, int start, int end, int lower, int upper) { + if (start > end) return true; + int val = preorder.get(start), i = 0; + if (val <= lower || val >= upper) return false; + for (i = start + 1; i <= end; ++i) { + if (preorder.get(i) >= val) break; + } + return helper(preorder, start + 1, i - 1, lower, val) && helper(preorder, i, end, val, upper); + } + } public static void main(String[] args) { Solution sol = new Solution(); - boolean res = sol.verifyPreorder(new ArrayList(Arrays.asList(5, 2, 1, 3, 6, 8, 7))); + boolean res = sol.verifyPreorderRecursive(new ArrayList(Arrays.asList(5, 2, 1, 3, 6, 8, 7))); System.out.println("result is " + res); } From d317d762c30e0228ac1ad878e37d5102dd9f7124 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 3 Jun 2018 02:55:15 -0700 Subject: [PATCH 221/456] add binary_tree_paths --- .../binary_tree_paths/BinaryTreePaths.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/binary_tree_paths/BinaryTreePaths.java diff --git a/src/main/java/binary_tree_paths/BinaryTreePaths.java b/src/main/java/binary_tree_paths/BinaryTreePaths.java new file mode 100644 index 0000000..948570a --- /dev/null +++ b/src/main/java/binary_tree_paths/BinaryTreePaths.java @@ -0,0 +1,46 @@ +package binary_tree_paths; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 6/3/18. + */ +public class BinaryTreePaths { + + public static class Solution { + + public List binaryTreePaths(TreeNode root) { + List res = new ArrayList<>(); + if (root != null) dfs(root, "", res); + return res; + } + + public void dfs(TreeNode root, String out, List res) { + out += Integer.toString(root.val); + if (root.left == null && root.right == null) res.add(out); + else { + if (root.left != null) dfs(root.left, out + "->", res); + if (root.right != null) dfs(root.right, out + "->", res); + } // out is not string & + } + + + + + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); root.right = new TreeNode(3); + root.left.right = new TreeNode(5); + List res = sol.binaryTreePaths(root); + System.out.println("result is " + res); + } + +} From 7e4c822ac70ee46f1487ac89e1ccde7c42b850c9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 4 Jun 2018 10:24:57 -0700 Subject: [PATCH 222/456] add 3sum_smaller --- src/main/java/_3sum_smaller/_3SumSmaller.java | 42 +++++++++++++++++++ .../binary_tree_paths/BinaryTreePaths.java | 5 --- 2 files changed, 42 insertions(+), 5 deletions(-) create mode 100644 src/main/java/_3sum_smaller/_3SumSmaller.java diff --git a/src/main/java/_3sum_smaller/_3SumSmaller.java b/src/main/java/_3sum_smaller/_3SumSmaller.java new file mode 100644 index 0000000..4ac66f1 --- /dev/null +++ b/src/main/java/_3sum_smaller/_3SumSmaller.java @@ -0,0 +1,42 @@ +package _3sum_smaller; + +import java.util.Arrays; + +/** + * Created by lxie on 6/4/18. + */ +public class _3SumSmaller { + + public class Solution { + + int threeSumSmaller(int[] nums, int target) { + if (nums.length < 3) return 0; + int res = 0; + Arrays.sort(nums); + for (int i = 0; i < nums.length - 2; ++i) { + int left = i + 1, right = nums.length - 1; + while (left < right) { + if (nums[i] + nums[left] + nums[right] < target) { + res += right - left; + ++left; + } else { + --right; + } + } + } + return res; + } + }; + + + +} + + public class UnitTest { + + + + + } + +} diff --git a/src/main/java/binary_tree_paths/BinaryTreePaths.java b/src/main/java/binary_tree_paths/BinaryTreePaths.java index 948570a..279dae8 100644 --- a/src/main/java/binary_tree_paths/BinaryTreePaths.java +++ b/src/main/java/binary_tree_paths/BinaryTreePaths.java @@ -26,11 +26,6 @@ public void dfs(TreeNode root, String out, List res) { if (root.right != null) dfs(root.right, out + "->", res); } // out is not string & } - - - - - } public static void main(String[] args) { From 2d68d9f7fb5a830552f2b020e3d8ffe652d5156b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 4 Jun 2018 16:58:46 -0700 Subject: [PATCH 223/456] add single_number_iii --- src/main/java/_3sum_smaller/_3SumSmaller.java | 7 --- .../single_number_iii/SingleNumberIII.java | 43 +++++++++++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) create mode 100644 src/main/java/single_number_iii/SingleNumberIII.java diff --git a/src/main/java/_3sum_smaller/_3SumSmaller.java b/src/main/java/_3sum_smaller/_3SumSmaller.java index 4ac66f1..e8adc3b 100644 --- a/src/main/java/_3sum_smaller/_3SumSmaller.java +++ b/src/main/java/_3sum_smaller/_3SumSmaller.java @@ -28,15 +28,8 @@ int threeSumSmaller(int[] nums, int target) { } }; - - -} - public class UnitTest { - - - } } diff --git a/src/main/java/single_number_iii/SingleNumberIII.java b/src/main/java/single_number_iii/SingleNumberIII.java new file mode 100644 index 0000000..c32197e --- /dev/null +++ b/src/main/java/single_number_iii/SingleNumberIII.java @@ -0,0 +1,43 @@ +package single_number_iii; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 6/4/18. + */ +public class SingleNumberIII { + + public class Solution { + public List singleNumberIII(int[] A) { + int xor = 0; + for (int i = 0; i < A.length; i++) { + xor ^= A[i]; + } + + int lastBit = xor - (xor & (xor - 1)); + int group0 = 0, group1 = 0; + for (int i = 0; i < A.length; i++) { + if ((lastBit & A[i]) == 0) { + group0 ^= A[i]; + } else { + group1 ^= A[i]; + } + } + + List result = new ArrayList(); + result.add(group0); + result.add(group1); + return result; + } + } + + public class UnitTest { + + + + + + } + +} From d6cbab5ae3365397fcd52c6a2382ef435686a431 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 5 Jun 2018 11:32:52 -0700 Subject: [PATCH 224/456] add graph_valid_tree --- .../java/graph_valid_tree/GraphValidTree.java | 118 ++++++++++++++++++ .../single_number_iii/SingleNumberIII.java | 4 - 2 files changed, 118 insertions(+), 4 deletions(-) create mode 100644 src/main/java/graph_valid_tree/GraphValidTree.java diff --git a/src/main/java/graph_valid_tree/GraphValidTree.java b/src/main/java/graph_valid_tree/GraphValidTree.java new file mode 100644 index 0000000..5e7fb19 --- /dev/null +++ b/src/main/java/graph_valid_tree/GraphValidTree.java @@ -0,0 +1,118 @@ +package graph_valid_tree; + +import java.util.*; + +/** + * Created by lxie on 6/5/18. + */ +public class GraphValidTree { + + // Note - if edge number is n then either 1. all connected, or 2. no loop should work + // version 1: BFS + public class SolutionBFS { + + public boolean validTree(int n, int[][] edges) { + if (n == 0) { + return false; + } + + if (edges.length != n - 1) { + return false; + } + + Map> graph = initializeGraph(n, edges); + + // bfs + Queue queue = new LinkedList<>(); + Set hash = new HashSet<>(); + + queue.offer(0); + hash.add(0); + while (!queue.isEmpty()) { + int node = queue.poll(); + for (Integer neighbor : graph.get(node)) { + if (hash.contains(neighbor)) { + continue; + } + hash.add(neighbor); + queue.offer(neighbor); + } + } + + return (hash.size() == n); + } + + private Map> initializeGraph(int n, int[][] edges) { + Map> graph = new HashMap<>(); + for (int i = 0; i < n; i++) { + graph.put(i, new HashSet()); + } + + for (int i = 0; i < edges.length; i++) { + int u = edges[i][0]; + int v = edges[i][1]; + graph.get(u).add(v); + graph.get(v).add(u); + } + + return graph; + } + } + + + // version 2: Union Find + public class SolutionUnion { + class UnionFind{ + HashMap father = new HashMap(); + UnionFind(int n){ + for(int i = 0 ; i < n; i++) { + father.put(i, i); + } + } + int compressed_find(int x){ + int parent = father.get(x); + while(parent!=father.get(parent)) { + parent = father.get(parent); + } + int temp = -1; + int fa = father.get(x); + while(fa!=father.get(fa)) { + temp = father.get(fa); + father.put(fa, parent) ; + fa = temp; + } + return parent; + + } + + void union(int x, int y){ + int fa_x = compressed_find(x); + int fa_y = compressed_find(y); + if(fa_x != fa_y) + father.put(fa_x, fa_y); + } + } + /** + * @param n an integer + * @param edges a list of undirected edges + * @return true if it's a valid tree, or false + */ + public boolean validTree(int n, int[][] edges) { + // tree should have n nodes with n-1 edges + if (n - 1 != edges.length) { + return false; + } + + UnionFind uf = new UnionFind(n); + + for (int i = 0; i < edges.length; i++) { + if (uf.compressed_find(edges[i][0]) == uf.compressed_find(edges[i][1])) { + return false; + } + uf.union(edges[i][0], edges[i][1]); + } + return true; + } + } + +} diff --git a/src/main/java/single_number_iii/SingleNumberIII.java b/src/main/java/single_number_iii/SingleNumberIII.java index c32197e..21740fd 100644 --- a/src/main/java/single_number_iii/SingleNumberIII.java +++ b/src/main/java/single_number_iii/SingleNumberIII.java @@ -34,10 +34,6 @@ public List singleNumberIII(int[] A) { public class UnitTest { - - - - } } From a7a10f3cbe014b4a08c24e499230d304d3adbefa Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 6 Jun 2018 10:18:27 -0700 Subject: [PATCH 225/456] add ugly_number_ii --- .../java/ugly_number_ii/UglyNumberII.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/ugly_number_ii/UglyNumberII.java diff --git a/src/main/java/ugly_number_ii/UglyNumberII.java b/src/main/java/ugly_number_ii/UglyNumberII.java new file mode 100644 index 0000000..2e5b5c5 --- /dev/null +++ b/src/main/java/ugly_number_ii/UglyNumberII.java @@ -0,0 +1,32 @@ +package ugly_number_ii; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 6/6/18. + */ +public class UglyNumberII { + + public class Solution { + int nthUglyNumber(int n) { + List res = new ArrayList<>(); + res.add(1); + int i2 = 0, i3 = 0, i5 = 0; + while (res.size() < n) { + int m2 = res.get(i2) * 2, m3 = res.get(i3) * 3, m5 = res.get(i5) * 5; + int mn = Integer.min(m2, Integer.min(m3, m5)); + if (mn == m2) ++i2; + if (mn == m3) ++i3; + if (mn == m5) ++i5; + res.add(mn); + } + return res.get(res.size()-1); + } + } + + public class UnitTest { + + } + +} From 664210e258fd270f8554ed9a9b2cf4bd3b519168 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 6 Jun 2018 16:08:05 -0700 Subject: [PATCH 226/456] paint_house_ii --- src/main/java/_3sum_smaller/_3SumSmaller.java | 2 +- .../java/paint_house_ii/PaintHouseII.java | 41 +++++++++++++++++++ .../java/ugly_number_ii/UglyNumberII.java | 2 +- 3 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 src/main/java/paint_house_ii/PaintHouseII.java diff --git a/src/main/java/_3sum_smaller/_3SumSmaller.java b/src/main/java/_3sum_smaller/_3SumSmaller.java index e8adc3b..9db21ec 100644 --- a/src/main/java/_3sum_smaller/_3SumSmaller.java +++ b/src/main/java/_3sum_smaller/_3SumSmaller.java @@ -9,7 +9,7 @@ public class _3SumSmaller { public class Solution { - int threeSumSmaller(int[] nums, int target) { + public int threeSumSmaller(int[] nums, int target) { if (nums.length < 3) return 0; int res = 0; Arrays.sort(nums); diff --git a/src/main/java/paint_house_ii/PaintHouseII.java b/src/main/java/paint_house_ii/PaintHouseII.java new file mode 100644 index 0000000..dc6be8b --- /dev/null +++ b/src/main/java/paint_house_ii/PaintHouseII.java @@ -0,0 +1,41 @@ +package paint_house_ii; + +/** + * Created by lxie on 6/6/18. + */ +public class PaintHouseII { + + public class Solution { + + public int minCostII(int[][] costs) { + if (costs.length == 0 || costs[0].length == 0) return 0; + int[][] dp = costs; + int min1 = -1, min2 = -1; + for (int i = 0; i < dp.length; ++i) { + int last1 = min1, last2 = min2; + min1 = -1; min2 = -1; + for (int j = 0; j < dp[i].length; ++j) { + if (j != last1) { + dp[i][j] += last1 < 0 ? 0 : dp[i - 1][last1]; + } else { + dp[i][j] += last2 < 0 ? 0 : dp[i - 1][last2]; + } + if (min1 < 0 || dp[i][j] < dp[i][min1]) { + min2 = min1; min1 = j; + } else if (min2 < 0 || dp[i][j] < dp[i][min2]) { + min2 = j; + } + } + } + return dp[dp.length-1][min1]; + } + + + } + + public class UnitTest { + + + } + +} diff --git a/src/main/java/ugly_number_ii/UglyNumberII.java b/src/main/java/ugly_number_ii/UglyNumberII.java index 2e5b5c5..7c3bd59 100644 --- a/src/main/java/ugly_number_ii/UglyNumberII.java +++ b/src/main/java/ugly_number_ii/UglyNumberII.java @@ -9,7 +9,7 @@ public class UglyNumberII { public class Solution { - int nthUglyNumber(int n) { + public int nthUglyNumber(int n) { List res = new ArrayList<>(); res.add(1); int i2 = 0, i3 = 0, i5 = 0; From f96e599d31e6ff5e8eb1a8755299590edb1ebccc Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 11 Jun 2018 12:44:10 -0700 Subject: [PATCH 227/456] closest_bst_value --- .../closest_bst_value/ClosestBSTValue.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/closest_bst_value/ClosestBSTValue.java diff --git a/src/main/java/closest_bst_value/ClosestBSTValue.java b/src/main/java/closest_bst_value/ClosestBSTValue.java new file mode 100644 index 0000000..73bd730 --- /dev/null +++ b/src/main/java/closest_bst_value/ClosestBSTValue.java @@ -0,0 +1,36 @@ +package closest_bst_value; + +import common.TreeNode; + +/** + * Created by lxie on 6/11/18. + */ +public class ClosestBSTValue { + + public class Solution { + + public int closestValue(TreeNode root, double target) { + int res = root.val; + while (root != null) { + if (Math.abs(res - target) >= Math.abs(root.val - target)) { + res = root.val; + } + root = target < root.val ? root.left : root.right; + } + return res; + } + + int closestValueRecursive(TreeNode root, double target) { + int a = root.val; + TreeNode t = target < a ? root.left : root.right; + if (t == null) return a; + int b = closestValue(t, target); + return Math.abs(a - target) < Math.abs(b - target) ? a : b; + } + } + + public class UnitTest { + + } + +} From f9d5638ba7ecff841da42edd515cc3cdd2ab620b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 12 Jun 2018 15:05:49 -0700 Subject: [PATCH 228/456] encode_decode_strings --- .../EncodeDecodeStrings.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/encode_decode_strings/EncodeDecodeStrings.java diff --git a/src/main/java/encode_decode_strings/EncodeDecodeStrings.java b/src/main/java/encode_decode_strings/EncodeDecodeStrings.java new file mode 100644 index 0000000..ec97332 --- /dev/null +++ b/src/main/java/encode_decode_strings/EncodeDecodeStrings.java @@ -0,0 +1,50 @@ +package encode_decode_strings; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 6/12/18. + */ +public class EncodeDecodeStrings { + + public static class Solution { + + // Encodes a list of strings to a single string. + public String encode(List strs) { + String res = ""; + for (String a : strs) { + res += Integer.toString(a.length()) + "/" + a; + } + return res; + } + // Decodes a single string to a list of strings. + public List decode(String s) { + List res = new ArrayList<>(); + int i = 0; + while (i < s.length()) { + int found = s.indexOf("/", i); + int len = Integer.parseInt(s.substring(i, found)); + res.add(s.substring(found + 1, found + len + 1)); + i = found + len + 1; + } + return res; + } + + + + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + + String encoded = sol.encode(new ArrayList<>(Arrays.asList("a", "ab", "abc"))); + System.out.println("encode = " + encoded); + + List decoded = sol.decode(encoded); + System.out.println(decoded.toString()); + } + +} From b99c8d742371ba6fedb854cd3452dafe12c62805 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 13 Jun 2018 11:39:27 -0700 Subject: [PATCH 229/456] add closest_bst_value_ii --- .../ClosestBSTValueII.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/main/java/closest_bst_value_ii/ClosestBSTValueII.java diff --git a/src/main/java/closest_bst_value_ii/ClosestBSTValueII.java b/src/main/java/closest_bst_value_ii/ClosestBSTValueII.java new file mode 100644 index 0000000..7c34964 --- /dev/null +++ b/src/main/java/closest_bst_value_ii/ClosestBSTValueII.java @@ -0,0 +1,66 @@ +package closest_bst_value_ii; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 6/13/18. + */ +public class ClosestBSTValueII { + + public class Solution { + + public List closestKValues(TreeNode root, double target, int k) { + List values = new ArrayList<>(); + + traverse(root, values); + + int i = 0, n = values.size(); + for (; i < n; i++) { + if (values.get(i) >= target) { + break; + } + } + + if (i >= n) { + return values.subList(n - k, n); + } + + int left = i - 1, right = i; + List result = new ArrayList<>(); + for (i = 0; i < k; i++) { + if (left >= 0 && (right >= n || target - values.get(left) < values.get(right) - target)) { + result.add(values.get(left)); + left--; + } else { + result.add(values.get(right)); + right++; + } + } + + return result; + } + + private void traverse(TreeNode root, List values) { + if (root == null) { + return; + } + + traverse(root.left, values); + values.add(root.val); + traverse(root.right, values); + } + + + + + } + + public class UnitTest { + + + } + +} From ae401d08ff4dab8dadb9eb70861e21762e30382b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 13 Jun 2018 15:39:52 -0700 Subject: [PATCH 230/456] add inter_to_english_words --- .../NumberToWords.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/integer_to_english_words/NumberToWords.java diff --git a/src/main/java/integer_to_english_words/NumberToWords.java b/src/main/java/integer_to_english_words/NumberToWords.java new file mode 100644 index 0000000..731bc84 --- /dev/null +++ b/src/main/java/integer_to_english_words/NumberToWords.java @@ -0,0 +1,43 @@ +package integer_to_english_words; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 6/13/18. + */ +public class NumberToWords { + + public static class Solution { + + String numberToWords(int num) { + String res = convertHundred(num % 1000); + List v = new ArrayList<>(Arrays.asList("Thousand", "Million", "Billion")); + for (int i = 0; i < 3; ++i) { + num /= 1000; + res = num % 1000 != 0 ? convertHundred(num % 1000) + " " + v.get(i) + " " + res : res; + } + while (res.charAt(res.length()-1) == ' ') res.substring(0, res.length()-1); + return res.isEmpty() ? "Zero" : res; + } + String convertHundred(int num) { + List v1 = new ArrayList<>(Arrays.asList("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")); + List v2 = new ArrayList<>(Arrays.asList("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")); + String res; + int a = num / 100, b = num % 100, c = num % 10; + res = b < 20 ? v1.get(b) : v2.get(b / 10) + (c != 0 ? " " + v1.get(c) : ""); + if (a > 0) res = v1.get(a) + " Hundred" + (b != 0 ? " " + res : ""); + return res; + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + + System.out.println(sol.numberToWords(1234567)); + + } + +} From c961c5ce28308e11a694671f83855b4650064a3c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 14 Jun 2018 10:55:10 -0700 Subject: [PATCH 231/456] add h-index --- src/main/java/h_index/HIndex.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/java/h_index/HIndex.java diff --git a/src/main/java/h_index/HIndex.java b/src/main/java/h_index/HIndex.java new file mode 100644 index 0000000..c62abd5 --- /dev/null +++ b/src/main/java/h_index/HIndex.java @@ -0,0 +1,28 @@ +package h_index; + +import java.util.Collections; +import java.util.List; + +/** + * Created by lxie on 6/14/18. + */ +public class HIndex { + + public class Solution { + + int hIndex(List citations) { + Collections.sort(citations, Collections.reverseOrder()); + + for (int i = 0; i < citations.size(); ++i) { + if (i >= citations.get(i)) return i; + } + return citations.size(); + } + } + + public class UnitTest { + + } + + +} From 56850d2f8b96f4071cfbba155886c7aef463ab44 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 14 Jun 2018 11:50:43 -0700 Subject: [PATCH 232/456] add h-index ii --- src/main/java/h_index_ii/HIndexII.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/main/java/h_index_ii/HIndexII.java diff --git a/src/main/java/h_index_ii/HIndexII.java b/src/main/java/h_index_ii/HIndexII.java new file mode 100644 index 0000000..9f2ea80 --- /dev/null +++ b/src/main/java/h_index_ii/HIndexII.java @@ -0,0 +1,26 @@ +package h_index_ii; + +/** + * Created by lxie on 6/14/18. + */ +public class HIndexII { + + public class Solution { + + public int hIndex(int[] citations) { + int len = citations.length, left = 0, right = len - 1; + while (left <= right) { + int mid = (left + right)/2; + if (citations[mid] == len - mid) return len - mid; + else if (citations[mid] > len - mid) right = mid - 1; + else left = mid + 1; + } + return len - left; + } + } + + public class UnitTest { + + } + +} From cd331be04581f245e28e08b6ac721a5cfc3f511a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 14 Jun 2018 22:59:54 -0700 Subject: [PATCH 233/456] find_celerity --- .../java/find_celebrity/FindCelebrity.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/find_celebrity/FindCelebrity.java diff --git a/src/main/java/find_celebrity/FindCelebrity.java b/src/main/java/find_celebrity/FindCelebrity.java new file mode 100644 index 0000000..13dcbd8 --- /dev/null +++ b/src/main/java/find_celebrity/FindCelebrity.java @@ -0,0 +1,29 @@ +package find_celebrity; + +/** + * Created by lxie on 6/14/18. + */ +public class FindCelebrity { + + public class Solution { + + private boolean knows(int a, int b) { + return true; // it varies + } + + public int findCelebrity(int n) { + int res = 0; + for (int i = 0; i < n; ++i) { + if (knows(res, i)) res = i; // get a candidate + } + for (int i = 0; i < n; ++i) { + if (res != i && (knows(res, i) || !knows(i, res))) return -1; + } + return res; + } + } + + public class UnitTest { + + } +} From 7943ee3006e34e46aab01f9df764f6b0ebfbe2ca Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 15 Jun 2018 02:34:45 -0700 Subject: [PATCH 234/456] add zigzag_iterator --- .../java/find_celebrity/FindCelebrity.java | 3 +- .../java/zigzag_iterator/ZigzagIterator.java | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/main/java/zigzag_iterator/ZigzagIterator.java diff --git a/src/main/java/find_celebrity/FindCelebrity.java b/src/main/java/find_celebrity/FindCelebrity.java index 13dcbd8..4764f70 100644 --- a/src/main/java/find_celebrity/FindCelebrity.java +++ b/src/main/java/find_celebrity/FindCelebrity.java @@ -8,7 +8,8 @@ public class FindCelebrity { public class Solution { private boolean knows(int a, int b) { - return true; // it varies + // ... + return true; } public int findCelebrity(int n) { diff --git a/src/main/java/zigzag_iterator/ZigzagIterator.java b/src/main/java/zigzag_iterator/ZigzagIterator.java new file mode 100644 index 0000000..b58251f --- /dev/null +++ b/src/main/java/zigzag_iterator/ZigzagIterator.java @@ -0,0 +1,30 @@ +package zigzag_iterator; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 6/15/18. + */ +public class ZigzagIterator { + + private List v = new ArrayList<>(); + public int i = 0; + + public ZigzagIterator(List v1, List v2) { + int n1 = v1.size(), n2 = v2.size(), n = Math.max(n1, n2); + for (int i = 0; i < n; ++i) { + if (i < n1) v.add(v1.get(i)); + if (i < n2) v.add(v2.get(i)); + } + } + + public int next() { + return v.get(i++); + } + + public boolean hasNext() { + return i < v.size(); + } + +} From 782ceeea2900a93c4c3189c400c279829637e7a4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 15 Jun 2018 16:55:07 -0700 Subject: [PATCH 235/456] expr_add_ops --- src/main/java/expr_add_ops/ExprAddOps.java | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/java/expr_add_ops/ExprAddOps.java diff --git a/src/main/java/expr_add_ops/ExprAddOps.java b/src/main/java/expr_add_ops/ExprAddOps.java new file mode 100644 index 0000000..857477a --- /dev/null +++ b/src/main/java/expr_add_ops/ExprAddOps.java @@ -0,0 +1,48 @@ +package expr_add_ops; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 6/15/18. + */ +public class ExprAddOps { + + public static class Solution { + + public List addOperators(String num, int target) { + List res = new ArrayList<>(); + addOperatorsDFS(num, target, 0, 0, "", res); + return res; + } + + public void addOperatorsDFS(String num, int target, long diff, long curNum, String out, List res) { + if (num.length() == 0 && curNum == target) { + res.add(out); + } + for (int i = 1; i <= num.length(); ++i) { + String cur = num.substring(0, i); + if (cur.length() > 1 && cur.charAt(0) == '0') return; + String next = num.substring(i); + Long curLong = Long.parseLong(cur); + if (out.length() > 0) { + addOperatorsDFS(next, target, curLong, curNum + curLong, out + "+" + cur, res); + addOperatorsDFS(next, target, -curLong, curNum - curLong, out + "-" + cur, res); + addOperatorsDFS(next, target, diff * curLong, (curNum - diff) + diff * curLong, out + "*" + cur, res); + } else { + addOperatorsDFS(next, target, curLong, curLong, cur, res); // first split + } + } + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + + System.out.println(sol.addOperators("232", 8)); + + } + + +} From d1216bc4eee4d4d16d38670ac84a9d9fa889ba01 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 16 Jun 2018 01:15:41 -0700 Subject: [PATCH 236/456] peeking_iterator --- .../java/peeking_iterator/PeekIterator.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/peeking_iterator/PeekIterator.java diff --git a/src/main/java/peeking_iterator/PeekIterator.java b/src/main/java/peeking_iterator/PeekIterator.java new file mode 100644 index 0000000..48f68b0 --- /dev/null +++ b/src/main/java/peeking_iterator/PeekIterator.java @@ -0,0 +1,49 @@ +package peeking_iterator; + +import java.util.Iterator; + +/** + * Created by lxie on 6/15/18. + */ +//Java Iterator interface reference: +// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html +class PeekingIterator implements Iterator { + + private static int _value; + private static boolean _flag; + private final Iterator _iterator; + + + public PeekingIterator(Iterator iterator) { + // initialize any member here. + _iterator = iterator; + _flag = false; + } + + // Returns the next element in the iteration without advancing the iterator. + public Integer peek() { + if (!_flag) { + _value = _iterator.next(); + _flag = true; + } + return _value; + + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + @Override + public Integer next() { + if (!_flag) return _iterator.next(); + _flag = false; + return _value; + } + + @Override + public boolean hasNext() { + if (_flag) return true; + if (_iterator.hasNext()) return true; + return false; + + } +} From 796d294cce779cc6a23ad5bc99bccf1aa94552ce Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 16 Jun 2018 17:26:58 -0700 Subject: [PATCH 237/456] add inorder_successor --- .../inorder_successor/InorderSuccessor.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/inorder_successor/InorderSuccessor.java diff --git a/src/main/java/inorder_successor/InorderSuccessor.java b/src/main/java/inorder_successor/InorderSuccessor.java new file mode 100644 index 0000000..5076228 --- /dev/null +++ b/src/main/java/inorder_successor/InorderSuccessor.java @@ -0,0 +1,27 @@ +package inorder_successor; + +import common.TreeNode; + +/** + * Created by lxie on 6/16/18. + */ +public class InorderSuccessor { + + public class Solution { + + public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { + TreeNode res = null; + while (root != null) { + if (root.val > p.val) { + res = root; + root = root.left; + } else root = root.right; + } + return res; + } + } + + public class UnitTest { + + } +} From 48720e8f03e23bedb0dbdc632f8c746a1b58d781 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 16 Jun 2018 17:35:58 -0700 Subject: [PATCH 238/456] add walls_and_gates --- .../java/walls_and_gates/WallAndGates.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/walls_and_gates/WallAndGates.java diff --git a/src/main/java/walls_and_gates/WallAndGates.java b/src/main/java/walls_and_gates/WallAndGates.java new file mode 100644 index 0000000..8a2ed1f --- /dev/null +++ b/src/main/java/walls_and_gates/WallAndGates.java @@ -0,0 +1,39 @@ +package walls_and_gates; + +/** + * Created by lxie on 6/16/18. + */ +public class WallAndGates { + + public class Solution { + + public void wallsAndGates(int[][] rooms) { + for (int i = 0; i < rooms.length; ++i) { + for (int j = 0; j < rooms[i].length; ++j) { + if (rooms[i][j] == 0) { + dfs(rooms, i + 1, j, 1); + dfs(rooms, i - 1, j, 1); + dfs(rooms, i, j + 1, 1); + dfs(rooms, i, j - 1, 1); + } + } + } + } + + private void dfs(int[][] rooms, int i, int j, int val) { + if (i < 0 || i >= rooms.length || j < 0 || j >= rooms[i].length) return; + if (rooms[i][j] > val) { + rooms[i][j] = val; + dfs(rooms, i + 1, j, val + 1); + dfs(rooms, i - 1, j, val + 1); + dfs(rooms, i, j + 1, val + 1); + dfs(rooms, i, j - 1, val + 1); + } + } + + } + + public class UnitTest { + + } +} From b60cc838ebe0b60c4a09ac12ea8285f6c5976e56 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 17 Jun 2018 02:05:43 -0700 Subject: [PATCH 239/456] add valid_Word_abbrev --- .../unique_word_abbrev/UniqWordAbbrev.java | 47 +++++++++++++++++++ .../java/walls_and_gates/WallAndGates.java | 2 +- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/main/java/unique_word_abbrev/UniqWordAbbrev.java diff --git a/src/main/java/unique_word_abbrev/UniqWordAbbrev.java b/src/main/java/unique_word_abbrev/UniqWordAbbrev.java new file mode 100644 index 0000000..39bd11f --- /dev/null +++ b/src/main/java/unique_word_abbrev/UniqWordAbbrev.java @@ -0,0 +1,47 @@ +package unique_word_abbrev; + + +import java.util.*; + +/** + * Created by lxie on 6/17/18. + */ +public class UniqWordAbbrev { + + Map> m = new HashMap<>(); + + public void ValidWordAbbr(List dictionary) { + for (String a : dictionary) { + String k = a.charAt(0) + Integer.toString(a.length() - 2) + a.charAt(a.length()-1); + if (m.containsKey(k)) { + m.get(k).add(a); + } else { + m.put(k, new HashSet(Arrays.asList(a))); + } + } + } + + public boolean isUnique(String word) { + String k = word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length()-1); + if (m.containsKey(k)) { + return (m.get(k).contains(word) ? 1 : 0) == m.get(k).size(); + } else { + return true; + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + List dict = new ArrayList<>(Arrays.asList("deer", "door", "cake", "card")); + UniqWordAbbrev u = new UniqWordAbbrev(); + u.ValidWordAbbr(dict); + + System.out.println(u.isUnique("dear")); + System.out.println(u.isUnique("cart")); + System.out.println(u.isUnique("cane")); + System.out.println(u.isUnique("make")); + + } + + +} diff --git a/src/main/java/walls_and_gates/WallAndGates.java b/src/main/java/walls_and_gates/WallAndGates.java index 8a2ed1f..6c186a7 100644 --- a/src/main/java/walls_and_gates/WallAndGates.java +++ b/src/main/java/walls_and_gates/WallAndGates.java @@ -34,6 +34,6 @@ private void dfs(int[][] rooms, int i, int j, int val) { } public class UnitTest { - + } } From de94a6d99cfa31382980b6d773180b76cfc71676 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 18 Jun 2018 01:07:58 -0700 Subject: [PATCH 240/456] add game_of_life --- src/main/java/game_of_life/GameOfLife.java | 39 +++++++++++++++++++ .../unique_word_abbrev/UniqWordAbbrev.java | 2 - 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 src/main/java/game_of_life/GameOfLife.java diff --git a/src/main/java/game_of_life/GameOfLife.java b/src/main/java/game_of_life/GameOfLife.java new file mode 100644 index 0000000..7505c7e --- /dev/null +++ b/src/main/java/game_of_life/GameOfLife.java @@ -0,0 +1,39 @@ +package game_of_life; + +/** + * Created by lxie on 6/17/18. + */ +public class GameOfLife { + + public class Solution { + + public void gameOfLife(int[][] board) { + int m = board.length, n = (m != 0) ? board[0].length : 0; + int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0}; + int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int cnt = 0; + for (int k = 0; k < 8; ++k) { + int x = i + dx[k], y = j + dy[k]; + if (x >= 0 && x < m && y >= 0 && y < n && (board[x][y] == 1 || board[x][y] == 2)) { + ++cnt; + } + } + if (board[i][j] != 0 && (cnt < 2 || cnt > 3)) board[i][j] = 2; + else if (board[i][j] == 0 && cnt == 3) board[i][j] = 3; + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + board[i][j] %= 2; + } + } + } + + } + + public class UnitTest { + + } +} diff --git a/src/main/java/unique_word_abbrev/UniqWordAbbrev.java b/src/main/java/unique_word_abbrev/UniqWordAbbrev.java index 39bd11f..1febd7f 100644 --- a/src/main/java/unique_word_abbrev/UniqWordAbbrev.java +++ b/src/main/java/unique_word_abbrev/UniqWordAbbrev.java @@ -42,6 +42,4 @@ public static void main(String[] args) { System.out.println(u.isUnique("make")); } - - } From 5bca74b20939cf22eab2a31c6fcd321097b26f91 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 19 Jun 2018 03:18:33 -0700 Subject: [PATCH 241/456] add word_pattern --- src/main/java/word_pattern/WordPattern.java | 41 +++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/word_pattern/WordPattern.java diff --git a/src/main/java/word_pattern/WordPattern.java b/src/main/java/word_pattern/WordPattern.java new file mode 100644 index 0000000..25a6ed2 --- /dev/null +++ b/src/main/java/word_pattern/WordPattern.java @@ -0,0 +1,41 @@ +package word_pattern; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 6/18/18. + */ +public class WordPattern { + + public static class Solution { + + public boolean wordPattern(String pattern, String str) { + Map m1 = new HashMap<>(); + Map m2 = new HashMap<>(); + + String[] words = str.split(" "); + int i = 0; + if (pattern.length() != words.length) return false; + for (String word : words) { + if (!m1.containsKey(pattern.charAt(i)) && !m2.containsKey(word)) { + m1.put(pattern.charAt(i), i); + m2.put(word, i); + } else if (m1.containsKey(pattern.charAt(i)) && m2.containsKey(word)) { + if (m1.get(pattern.charAt(i)).intValue() != m2.get(word).intValue()) + return false; + } else { + return false; + } + ++i; + } + return i == pattern.length(); + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + System.out.println(sol.wordPattern("abba", "dog cat cat fish")); + } + } +} From d1e7411d1f072eaa84650c6de2361fabc5a0e9f6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 19 Jun 2018 16:06:48 -0700 Subject: [PATCH 242/456] add word_pattern_ii --- .../java/word_pattern_ii/WordPatternII.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/main/java/word_pattern_ii/WordPatternII.java diff --git a/src/main/java/word_pattern_ii/WordPatternII.java b/src/main/java/word_pattern_ii/WordPatternII.java new file mode 100644 index 0000000..ef37180 --- /dev/null +++ b/src/main/java/word_pattern_ii/WordPatternII.java @@ -0,0 +1,55 @@ +package word_pattern_ii; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 6/19/18. + */ +public class WordPatternII { + + public static class Solution{ + + public boolean wordPatternMatch(String pattern, String str) { + Map m = new HashMap<>(); + return helper(pattern, 0, str, 0, m); + } + + private boolean helper(String pattern, int p, String str, int r, Map m) { + if (p == pattern.length() && r == str.length()) return true; + if (p == pattern.length() || r == str.length()) return false; + char c = pattern.charAt(p); + for (int i = r; i < str.length(); ++i) { + String t = str.substring(r, i+1); + if (m.containsKey(c) && m.get(c).equals(t)) { + if (helper(pattern, p + 1, str, i + 1, m)) return true; + } else if (!m.containsKey(c)) { + boolean b = false; + for (Map.Entry it : m.entrySet()) { + if (it.getValue().equals(t)) b = true; + } + if (!b) { + m.put(c, t); + if (helper(pattern, p + 1, str, i + 1, m)) return true; + m.remove(c); // backtracking + } + } + } + return false; + } + } + + public static void main(String[] args) { + System.out.println("this is for test"); + Solution sol = new Solution(); + + //pattern = "abab", str = "redblueredblue" should return true. + //pattern = "aaaa", str = "asdasdasdasd" should return true. + //pattern = "aabb", str = "xyzabcxzyabc" should return false. + System.out.println(sol.wordPatternMatch("abab", "redblueredblue")); + System.out.println(sol.wordPatternMatch("aaaa", "asdasdasdasd")); + System.out.println(sol.wordPatternMatch("aabb", "xyzabcxzyabc")); + + } + +} From 0ea80aba5a62698cfb93d619c5be099f56b340d2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 20 Jun 2018 11:17:30 -0700 Subject: [PATCH 243/456] add flip_game_ii and find_median_in_stream --- .../find_median_in_stream/MedianInStream.java | 31 +++++++++++++++++++ src/main/java/flip_game_ii/FlipGameII.java | 24 ++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 src/main/java/find_median_in_stream/MedianInStream.java create mode 100644 src/main/java/flip_game_ii/FlipGameII.java diff --git a/src/main/java/find_median_in_stream/MedianInStream.java b/src/main/java/find_median_in_stream/MedianInStream.java new file mode 100644 index 0000000..be20da3 --- /dev/null +++ b/src/main/java/find_median_in_stream/MedianInStream.java @@ -0,0 +1,31 @@ +package find_median_in_stream; + +import java.util.Collections; +import java.util.PriorityQueue; + +/** + * Created by lxie on 6/20/18. + */ +public class MedianInStream { + + // by default min heap in java + private PriorityQueue small = new PriorityQueue(30, Collections.reverseOrder()); + private PriorityQueue large = new PriorityQueue(30); + + + public void addNum(int num) { + small.add(num); + large.add(small.peek()); + small.poll(); + if (small.size() < large.size()) { + small.add(large.peek()); + large.poll(); + } + } + + // Returns the median of current data stream + public double findMedian() { + return small.size() > large.size() ? (double) small.peek() : 0.5 *((int)small.peek() + (int)large.peek()); + } + +} diff --git a/src/main/java/flip_game_ii/FlipGameII.java b/src/main/java/flip_game_ii/FlipGameII.java new file mode 100644 index 0000000..17398f4 --- /dev/null +++ b/src/main/java/flip_game_ii/FlipGameII.java @@ -0,0 +1,24 @@ +package flip_game_ii; + +/** + * Created by lxie on 6/20/18. + */ +public class FlipGameII { + + public class Solution { + + public boolean canWin(String s) { + for (int i = 1; i < s.length(); ++i) { + if (s.charAt(i) == '+' && s.charAt(i-1) == '+' && + !canWin(s.substring(0, i) + "--" + s.substring(i + 1))) { + return true; + } + } + return false; + } + } + + public static void main(String[] args) { + + } +} From f288324c2a27ee3b4f4096a08f51f254595decd3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 20 Jun 2018 11:53:36 -0700 Subject: [PATCH 244/456] add best_meeting_point --- .../best_meeting_point/BestMeetingPoint.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/best_meeting_point/BestMeetingPoint.java diff --git a/src/main/java/best_meeting_point/BestMeetingPoint.java b/src/main/java/best_meeting_point/BestMeetingPoint.java new file mode 100644 index 0000000..92ad29a --- /dev/null +++ b/src/main/java/best_meeting_point/BestMeetingPoint.java @@ -0,0 +1,41 @@ +package best_meeting_point; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created by lxie on 6/20/18. + */ +public class BestMeetingPoint { + + public class Solution { + + public int minTotalDistance(int[][] grid) { + List rows = new ArrayList(); + List cols = new ArrayList(); + for (int i = 0; i < grid.length; ++i) { + for (int j = 0; j < grid[i].length; ++j) { + if (grid[i][j] == 1) { + rows.add(i); + cols.add(j); + } + } + } + return minTotalDistance(rows) + minTotalDistance(cols); + } + int minTotalDistance(List v) { + int res = 0; + Collections.sort(v); + int i = 0, j = v.size() - 1; + while (i < j) res += v.get(j--) - v.get(i++); + return res; + } + + } + + public class UnitTest { + + } + +} From a4eea3c8a31e9d5f0a9ad08dc827a401319f7fe6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 21 Jun 2018 00:20:21 -0700 Subject: [PATCH 245/456] add binary_tree_longest_consecutive_sequence --- .../LongestConsecutiveSequenceBTree.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/binary_tree_longest_consecutive_sequence/LongestConsecutiveSequenceBTree.java diff --git a/src/main/java/binary_tree_longest_consecutive_sequence/LongestConsecutiveSequenceBTree.java b/src/main/java/binary_tree_longest_consecutive_sequence/LongestConsecutiveSequenceBTree.java new file mode 100644 index 0000000..00a2d2d --- /dev/null +++ b/src/main/java/binary_tree_longest_consecutive_sequence/LongestConsecutiveSequenceBTree.java @@ -0,0 +1,44 @@ +package binary_tree_longest_consecutive_sequence; + +import common.TreeNode; + +import static java.lang.Math.max; + +/** + * Created by lxie on 6/21/18. + */ +public class LongestConsecutiveSequenceBTree { + + public static class Solution { + + public int longestConsecutive(TreeNode root) { + if (root == null) return 0; + int[] res = {0}; + dfs(root, root.val - 1, 0, res); + return res[0]; + } + + private void dfs(TreeNode root, int v, int out, int[] res) { + if (root == null) return; + if (root.val == v + 1) ++out; + else out = 1; + res[0] = max(res[0], out); + dfs(root.left, root.val, out, res); + dfs(root.right, root.val, out, res); + } + } + + public static void main(String[] args) { + Solution sol = new Solution(); + + TreeNode root = new TreeNode(1); + root.right = new TreeNode(3); + root.right.left = new TreeNode(2); + root.right.right = new TreeNode(4); + root.right.right.right = new TreeNode(5); + int res = sol.longestConsecutive(root); + System.out.println("result is " + res); + } + + +} From c5a8d6008e30dd9c407b68bf5082f0ff11caa9c7 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 21 Jun 2018 16:56:06 -0700 Subject: [PATCH 246/456] add bulls_and_cows --- src/main/java/bulls_and_cows/BullAndCows.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/bulls_and_cows/BullAndCows.java diff --git a/src/main/java/bulls_and_cows/BullAndCows.java b/src/main/java/bulls_and_cows/BullAndCows.java new file mode 100644 index 0000000..622337f --- /dev/null +++ b/src/main/java/bulls_and_cows/BullAndCows.java @@ -0,0 +1,29 @@ +package bulls_and_cows; + +/** + * Created by lxie on 6/21/18. + */ +public class BullAndCows { + + public class Solution { + + public String getHint(String secret, String guess) { + int bulls = 0, cows = 0; + int[] m = new int[256]; + for (int i = 0; i < secret.length(); ++i) { + if (secret.charAt(i) == guess.charAt(i)) ++bulls; + else { + if (m[secret.charAt(i)]++ < 0) ++cows; + if (m[guess.charAt(i)]-- > 0) ++ cows; + } + } + return Integer.toString(bulls)+ "A" + Integer.toString(cows) + "B"; + } + } + + public class UnitTest { + + + } + +} From cfff4feeb005f68a5ec208de3beb592ad0d7d3a0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 22 Jun 2018 03:09:02 -0700 Subject: [PATCH 247/456] add longest_increasing_subsequence --- .../LongestIncSubsequence.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/main/java/longest_increasing_subsequence/LongestIncSubsequence.java diff --git a/src/main/java/longest_increasing_subsequence/LongestIncSubsequence.java b/src/main/java/longest_increasing_subsequence/LongestIncSubsequence.java new file mode 100644 index 0000000..66279f1 --- /dev/null +++ b/src/main/java/longest_increasing_subsequence/LongestIncSubsequence.java @@ -0,0 +1,55 @@ +package longest_increasing_subsequence; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 6/22/18. + */ +public class LongestIncSubsequence { + + public class Solution { + + // O(n^2) + public int lengthOfLIS(int[] nums) { + int[] dp = new int[nums.length]; + for (int i=0; i nums[j]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + res = Math.max(res, dp[i]); + } + return res; + } + + // O(nlogn) + public int lengthOfLIS1(int[] nums) { + if (nums.length == 0) return 0; + List ends = new ArrayList<>(); + ends.add(nums[0]); + for (int a : nums) { + if (a < ends.get(0)) ends.set(0, a); + else if (a > ends.get(ends.size()-1)) ends.add(a); + else { + int left = 0, right = ends.size(); + while (left < right) { + int mid = left + (right - left) / 2; + if (ends.get(mid) < a) left = mid + 1; + else right = mid; + } + ends.set(right, a); // find first >= a and replace it + } + } + return ends.size(); + } + + } + + public class UnitTest { + + } +} From 1d7b0f81895d6ac9332734f994d7f98ca61b4211 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 23 Jun 2018 23:06:49 -0700 Subject: [PATCH 248/456] add remove_invalid_parentheses --- .../RemoveInvalidParentheses.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/remove_invalid_parentheses/RemoveInvalidParentheses.java diff --git a/src/main/java/remove_invalid_parentheses/RemoveInvalidParentheses.java b/src/main/java/remove_invalid_parentheses/RemoveInvalidParentheses.java new file mode 100644 index 0000000..018cb18 --- /dev/null +++ b/src/main/java/remove_invalid_parentheses/RemoveInvalidParentheses.java @@ -0,0 +1,53 @@ +package remove_invalid_parentheses; + +import java.util.*; + +/** + * Created by lxie on 6/23/18. + */ +public class RemoveInvalidParentheses { + + public class Solution { + + public List removeInvalidParentheses(String s) { + List res = new ArrayList<>(); + Set visited = new HashSet<>(); + Queue q = new LinkedList<>(); + q.add(s); + boolean found = false; + while (!q.isEmpty()) { + String t = q.peek(); q.poll(); + if (isValid(t)) { + res.add(t); + found = true; + } + if (found) continue; + for (int i = 0; i < t.length(); ++i) { + if (t.charAt(i) != '(' && t.charAt(i) != ')') continue; + String str = t.substring(0, i) + t.substring(i + 1); + if (!visited.contains(str)) { + q.add(str); + visited.add(str); + } + } + } + return res; + } + + boolean isValid(String t) { + int cnt = 0; + for (int i = 0; i < t.length(); ++i) { + if (t.charAt(i) == '(') ++cnt; + else if (t.charAt(i) == ')' && --cnt < 0) return false; + } + return cnt == 0; + } + + } + + public class UnitTest { + + } + + +} From 5c3bf5cfb79339fd6873a37357d8c1b070dc11cb Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 26 Jun 2018 10:41:27 -0700 Subject: [PATCH 249/456] add smallest_rectangle_enclosing_black_pixels --- .../MinArea.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/smallest_rectangle_enclosing_black_pixels/MinArea.java diff --git a/src/main/java/smallest_rectangle_enclosing_black_pixels/MinArea.java b/src/main/java/smallest_rectangle_enclosing_black_pixels/MinArea.java new file mode 100644 index 0000000..4552ad4 --- /dev/null +++ b/src/main/java/smallest_rectangle_enclosing_black_pixels/MinArea.java @@ -0,0 +1,41 @@ +package smallest_rectangle_enclosing_black_pixels; + +/** + * Created by lxie on 6/26/18. + */ +public class MinArea { + + public class Solution { + + public int minArea(char[][] image, int x, int y) { + int[] left = {y}; int[] right = {y}; + int[] up = {x}; int[] down = {x}; + dfs(image, x, y, left, right, up, down); + return (right[0] - left[0] + 1) * (down[0] - up[0] + 1); + } + + private void dfs(char[][] image, int x, int y, int[] left, + int[] right, int[] up, int[] down) { + if (x < 0 || x >= image.length || y < 0 || y >= image[0].length || + image[x][y] != '1') return; + left[0] = Math.min(left[0], y); + right[0] = Math.max(right[0], y); + up[0] = Math.min(up[0], x); + down[0] = Math.max(down[0], x); + image[x][y] = '2'; + dfs(image, x + 1, y, left, right, up, down); + dfs(image, x - 1, y, left, right, up, down); + dfs(image, x, y + 1, left, right, up, down); + dfs(image, x, y - 1, left, right, up, down); + } + + + } + + public class UnitTest { + + + } + + +} From d5f77c77629888913cba46d828116db9ae79574e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 28 Jun 2018 10:37:12 -0700 Subject: [PATCH 250/456] add range_sum_query_2d --- .../java/range_sum_query_2d/NumMatrix.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/main/java/range_sum_query_2d/NumMatrix.java diff --git a/src/main/java/range_sum_query_2d/NumMatrix.java b/src/main/java/range_sum_query_2d/NumMatrix.java new file mode 100644 index 0000000..7e2bc1d --- /dev/null +++ b/src/main/java/range_sum_query_2d/NumMatrix.java @@ -0,0 +1,23 @@ +package range_sum_query_2d; + +/** + * Created by lxie on 6/28/18. + */ +public class NumMatrix { + + private int[][] dp = null; + + public NumMatrix(int[][] matrix) { + if (matrix.length == 0 || matrix[0].length == 0) return; + dp = new int[matrix.length+1][matrix[0].length+1]; + for (int i = 1; i <= matrix.length; ++i) { + for (int j = 1; j <= matrix[0].length; ++j) { + dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1] + matrix[i - 1][j - 1]; + } + } + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + return dp[row2 + 1][col2 + 1] - dp[row1][col2 + 1] - dp[row2 + 1][col1] + dp[row1][col1]; + } +} From 98a1f6bcad17461e2b55612f7b0ea7b1aa7da69c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 30 Jun 2018 16:01:17 -0700 Subject: [PATCH 251/456] add additive_number --- .../java/additive_number/AdditiveNumber.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/additive_number/AdditiveNumber.java diff --git a/src/main/java/additive_number/AdditiveNumber.java b/src/main/java/additive_number/AdditiveNumber.java new file mode 100644 index 0000000..ba3f8c8 --- /dev/null +++ b/src/main/java/additive_number/AdditiveNumber.java @@ -0,0 +1,47 @@ +package additive_number; + +/** + * Created by lxie on 6/30/18. + */ +public class AdditiveNumber { + + public static class Solution { + + public boolean isAdditiveNumber(String num) { + for (int i = 1; i < num.length(); ++i) { + for (int j = i + 1; j < num.length(); ++j) { + String s1 = num.substring(0, i); + String s2 = num.substring(i, j); + long d1 = Long.parseLong(s1), d2 = Long.parseLong(s2); + if ((s1.length() > 1 && s1.charAt(0) == '0') || + (s2.length() > 1 && s2.charAt(0) == '0')) continue; + long next = d1 + d2; + String nexts = Long.toString(next); + String now = s1 + s2 + nexts; + while (now.length() < num.length()) { + d1 = d2; + d2 = next; + next = d1 + d2; + nexts = Long.toString(next); + now += nexts; + } + if (now.compareTo(num) == 0) return true; + } + } + return false; + } + + } + + public static void main(String[] args) { + + Solution sol = new Solution(); + boolean res = sol.isAdditiveNumber("112358"); + + System.out.println("result is " + res); + + + + } + +} From 42ee22af4324af33a975eea607ca0e0249046525 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 2 Jul 2018 15:54:24 -0700 Subject: [PATCH 252/456] add super_ugly_number --- .../super_ugly_number/SuperUglyNumber.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/super_ugly_number/SuperUglyNumber.java diff --git a/src/main/java/super_ugly_number/SuperUglyNumber.java b/src/main/java/super_ugly_number/SuperUglyNumber.java new file mode 100644 index 0000000..3af10e8 --- /dev/null +++ b/src/main/java/super_ugly_number/SuperUglyNumber.java @@ -0,0 +1,34 @@ +package super_ugly_number; + +/** + * Created by lxie on 7/2/18. + */ +public class SuperUglyNumber { + + public class Solution { + + public int nthSuperUglyNumber(int n, int[] primes) { + int[] dp = new int[n]; for (int i=0; i Date: Mon, 2 Jul 2018 16:58:35 -0700 Subject: [PATCH 253/456] add smaller_numbers_after_self --- .../SmallerAfterSelf.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/smaller_numbers_after_self/SmallerAfterSelf.java diff --git a/src/main/java/smaller_numbers_after_self/SmallerAfterSelf.java b/src/main/java/smaller_numbers_after_self/SmallerAfterSelf.java new file mode 100644 index 0000000..143c9cf --- /dev/null +++ b/src/main/java/smaller_numbers_after_self/SmallerAfterSelf.java @@ -0,0 +1,35 @@ +package smaller_numbers_after_self; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 7/2/18. + */ +public class SmallerAfterSelf { + + public class Solution { + + public List countSmaller(int[] nums) { + List t = new ArrayList<>(); + Integer[] res = new Integer[nums.length]; + for (int i = nums.length - 1; i >= 0; --i) { + int left = 0, right = t.size(); + while (left < right) { + int mid = left + (right - left) / 2; + if (t.get(mid) >= nums[i]) right = mid; + else left = mid + 1; + } + res[i] = right; // for each i get count + t.add(right, nums[i]); + } + return Arrays.asList(res); + } + } + + public class UnitTest4 { + + } + +} From 0fcbf61d0a65c4a9f2be26c0836d44a305ed51d9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 3 Jul 2018 10:11:36 -0700 Subject: [PATCH 254/456] add max_product_of_word_lengths --- .../MaxProdWordLenghs.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/max_product_of_word_lengths/MaxProdWordLenghs.java diff --git a/src/main/java/max_product_of_word_lengths/MaxProdWordLenghs.java b/src/main/java/max_product_of_word_lengths/MaxProdWordLenghs.java new file mode 100644 index 0000000..1a94a75 --- /dev/null +++ b/src/main/java/max_product_of_word_lengths/MaxProdWordLenghs.java @@ -0,0 +1,44 @@ +package max_product_of_word_lengths; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 7/3/18. + */ +public class MaxProdWordLenghs { + + public class Solution { + + public int maxProduct(String[] words) { + int res = 0; + Map m = new HashMap<>(); + for (String word : words) { + int mask = 0; + for (char c : word.toCharArray()) { + mask |= 1 << (c - 'a'); + } + if (!m.containsKey(mask)) { + m.put(mask, word.length()); + } else { + m.put(mask, Math.max(m.get(mask), word.length())); + } + + for (Map.Entry a : m.entrySet()) { + if ((mask & a.getKey()) == 0) { + res = Math.max(res, (int)word.length() * a.getValue()); + } + } + } + return res; + } + } + + public class UnitTest { + + + + } + + +} From 218406658a6b76f739b5547d29be24b902667f49 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 3 Jul 2018 17:09:30 -0700 Subject: [PATCH 255/456] add generalized_abbreviation --- .../GeneralizedAbbreviation.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/generalized_abbreviation/GeneralizedAbbreviation.java diff --git a/src/main/java/generalized_abbreviation/GeneralizedAbbreviation.java b/src/main/java/generalized_abbreviation/GeneralizedAbbreviation.java new file mode 100644 index 0000000..d3540c2 --- /dev/null +++ b/src/main/java/generalized_abbreviation/GeneralizedAbbreviation.java @@ -0,0 +1,40 @@ +package generalized_abbreviation; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 7/3/18. + */ +public class GeneralizedAbbreviation { + + public static class Solution { + + public List generateAbbreviations(String word) { + List res = new ArrayList<>(); + for (int i = 0; i < Math.pow(2, word.length()); ++i) { + String out = ""; + int cnt = 0; + for (int j = 0; j < word.length(); ++j) { + if (((i >> j) & 1) == 1) ++cnt; + else { + if (cnt != 0) { + out += Integer.toString(cnt); + cnt = 0; + } + out += word.charAt(j); + } + } + if (cnt > 0) out += Integer.toString(cnt); + res.add(out); + } + return res; + } + + } + + public static void main (String[] args) { + Solution sol = new Solution(); + System.out.println("result is " + sol.generateAbbreviations("word")); + } +} From d5ab92de3938c4ba04dd69a7fd86073cec49803a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 4 Jul 2018 00:49:21 -0700 Subject: [PATCH 256/456] logger_rate_limiter --- src/main/java/logger_rate_limiter/Logger.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/main/java/logger_rate_limiter/Logger.java diff --git a/src/main/java/logger_rate_limiter/Logger.java b/src/main/java/logger_rate_limiter/Logger.java new file mode 100644 index 0000000..f07d5bd --- /dev/null +++ b/src/main/java/logger_rate_limiter/Logger.java @@ -0,0 +1,26 @@ +package logger_rate_limiter; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 7/4/18. + */ +public class Logger { + + public Logger() {}; + + private Map m = new HashMap<>(); + + boolean shouldPrintMessage(int timestamp, String message) { + if (!m.containsKey(message)) { + m.put(message, timestamp); + return true; + } + if (timestamp - m.get(message) >= 10) { + m.put(message, timestamp); + return true; + } + return false; + } +} From 3fb6540e13fba2cdd9928b459850732619db0066 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 4 Jul 2018 23:15:09 -0700 Subject: [PATCH 257/456] find_anagram_mappings --- .../FindAnagramMappings.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/find_anagram_mappings/FindAnagramMappings.java diff --git a/src/main/java/find_anagram_mappings/FindAnagramMappings.java b/src/main/java/find_anagram_mappings/FindAnagramMappings.java new file mode 100644 index 0000000..431a9ec --- /dev/null +++ b/src/main/java/find_anagram_mappings/FindAnagramMappings.java @@ -0,0 +1,35 @@ +package find_anagram_mappings; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 7/4/18. + */ +public class FindAnagramMappings { + + public static class Solution { + + public List anagramMappings(int[] A, int[] B) { + List res = new ArrayList<>(); + Map m = new HashMap<>(); + for (int i = 0; i < B.length; ++i) { + m.put(B[i], i); + } + for (int num : A) res.add(m.get(num)); + return res; + } + + + } + + public static void main (String[] args) { + Solution sol = new Solution(); + int[] a = {12,28, 46, 32, 50}; + int[] b = {50, 12, 32,46,28}; + System.out.println("result is " + sol.anagramMappings(a, b)); + } + +} From b2518cda9b5e5c78ca4da23cb1d681da28be39bb Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 6 Jul 2018 00:53:07 -0700 Subject: [PATCH 258/456] island_perimeter --- .../island_perimeter/IslandPerimeter.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/island_perimeter/IslandPerimeter.java diff --git a/src/main/java/island_perimeter/IslandPerimeter.java b/src/main/java/island_perimeter/IslandPerimeter.java new file mode 100644 index 0000000..a5fd931 --- /dev/null +++ b/src/main/java/island_perimeter/IslandPerimeter.java @@ -0,0 +1,31 @@ +package island_perimeter; + +/** + * Created by lxie on 7/6/18. + */ +public class IslandPerimeter { + + public class Solution { + + public int islandPerimeter(int[][] grid) { + if (grid.length == 0 || grid[0].length == 0) return 0; + int m = grid.length, n = grid[0].length, res = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) continue; + if (j == 0 || grid[i][j - 1] == 0) ++res; + if (i == 0 || grid[i - 1][j] == 0) ++res; + if (j == n - 1 || grid[i][j + 1] == 0) ++res; + if (i == m - 1 || grid[i + 1][j] == 0) ++res; + } + } + return res; + } + } + + public class UnitTest { + + + } + +} From e113b77b301c07bb0a2cd23faaa144ca815f7467 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 10 Jul 2018 15:48:00 -0700 Subject: [PATCH 259/456] find_disppeared_in_array --- .../FindAnagramMappings.java | 9 ++-- .../FindDisappearedInArray.java | 41 +++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) create mode 100644 src/main/java/find_disappeared_in_array/FindDisappearedInArray.java diff --git a/src/main/java/find_anagram_mappings/FindAnagramMappings.java b/src/main/java/find_anagram_mappings/FindAnagramMappings.java index 431a9ec..7b749a8 100644 --- a/src/main/java/find_anagram_mappings/FindAnagramMappings.java +++ b/src/main/java/find_anagram_mappings/FindAnagramMappings.java @@ -21,15 +21,12 @@ public List anagramMappings(int[] A, int[] B) { for (int num : A) res.add(m.get(num)); return res; } - - } - public static void main (String[] args) { + public static void main(String[] args) { Solution sol = new Solution(); - int[] a = {12,28, 46, 32, 50}; - int[] b = {50, 12, 32,46,28}; + int[] a = {12, 28, 46, 32, 50}; + int[] b = {50, 12, 32, 46, 28}; System.out.println("result is " + sol.anagramMappings(a, b)); } - } diff --git a/src/main/java/find_disappeared_in_array/FindDisappearedInArray.java b/src/main/java/find_disappeared_in_array/FindDisappearedInArray.java new file mode 100644 index 0000000..7e5a548 --- /dev/null +++ b/src/main/java/find_disappeared_in_array/FindDisappearedInArray.java @@ -0,0 +1,41 @@ +package find_disappeared_in_array; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 7/10/18. + */ +public class FindDisappearedInArray { + + public class Solution { + + public List findDisappearedNumbers(int[] nums) { + List res = new ArrayList<>(); + for (int i = 0; i < nums.length; ++i) { + if (nums[i] != nums[nums[i] - 1]) { + // swap in right order + int temp = nums[nums[i] - 1]; + nums[nums[i] - 1] = nums[i]; + nums[i] = temp; + + --i; + } + } + for (int i = 0; i < nums.length; ++i) { + if (nums[i] != i + 1) { + res.add(i + 1); + } + } + return res; + } + + } + + public class UnitTest { + + + + } + +} From 1482850cb54688ee0a653ad963d376f2835c7f75 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 11 Jul 2018 11:48:44 -0700 Subject: [PATCH 260/456] add rotated_digits --- .../java/rotated_digits/RotatedDigits.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/rotated_digits/RotatedDigits.java diff --git a/src/main/java/rotated_digits/RotatedDigits.java b/src/main/java/rotated_digits/RotatedDigits.java new file mode 100644 index 0000000..487e92b --- /dev/null +++ b/src/main/java/rotated_digits/RotatedDigits.java @@ -0,0 +1,35 @@ +package rotated_digits; + +/** + * Created by lxie on 7/10/18. + */ +public class RotatedDigits { + + public class Solution { + + public int rotatedDigits(int N) { + int res = 0; + for (int i = 1; i <= N; ++i) { + if (check(i)) ++res; + } + return res; + } + + private boolean check(int k) { + String str = Integer.toString(k); + boolean flag = false; + for (char c : str.toCharArray()) { + if (c == '3' || c == '4' || c == '7') return false; + if (c == '2' || c == '5' || c == '6' || c == '9') flag = true;; + } + return flag; + } + + } + + public class UnitTest { + + + + } +} From c011b2100aa6f6ef96d685a8cebd27cf3d049bf5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 11 Jul 2018 14:38:19 -0700 Subject: [PATCH 261/456] add min_distance_between_bst_nodes --- .../MinDistanceBSTNodes.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/min_distance_between_bst_nodes/MinDistanceBSTNodes.java diff --git a/src/main/java/min_distance_between_bst_nodes/MinDistanceBSTNodes.java b/src/main/java/min_distance_between_bst_nodes/MinDistanceBSTNodes.java new file mode 100644 index 0000000..186be2d --- /dev/null +++ b/src/main/java/min_distance_between_bst_nodes/MinDistanceBSTNodes.java @@ -0,0 +1,32 @@ +package min_distance_between_bst_nodes; + +import common.TreeNode; + +/** + * Created by lxie on 7/11/18. + */ +public class MinDistanceBSTNodes { + + public class Solution { + + public int minDiffInBST(TreeNode root) { + int[] res = {Integer.MAX_VALUE}; + int[] pre = {-1}; + helper(root, pre, res); + return res[0]; + } + + private void helper(TreeNode node, int[] pre, int[] res) { + if (node == null) return; + helper(node.left, pre, res); + if (pre[0] != -1) res[0] = Math.min(res[0], node.val - pre[0]); + pre[0] = node.val; + helper(node.right, pre, res); + } + } + + public class UnitTest { + + } + +} From f8008a883819ad1cab7db77bb211d0b47673a2e3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 12 Jul 2018 00:47:37 -0700 Subject: [PATCH 262/456] add number_of_boomerangs --- .../NumberOfBoomerangs.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/number_of_boomerangs/NumberOfBoomerangs.java diff --git a/src/main/java/number_of_boomerangs/NumberOfBoomerangs.java b/src/main/java/number_of_boomerangs/NumberOfBoomerangs.java new file mode 100644 index 0000000..5b3e900 --- /dev/null +++ b/src/main/java/number_of_boomerangs/NumberOfBoomerangs.java @@ -0,0 +1,39 @@ +package number_of_boomerangs; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 7/12/18. + */ +public class NumberOfBoomerangs { + + public class Solution { + public int numberOfBoomerangs(int[][] points) { + int res = 0; + for (int i = 0; i < points.length; ++i) { + Map m = new HashMap<>(); + for (int j = 0; j < points.length; ++j) { + int a = points[i][0] - points[j][0]; + int b = points[i][1] - points[j][1]; + if (!m.containsKey(a * a + b * b)) { + m.put(a * a + b * b, 1); + } else { + m.put(a * a + b * b, m.get(a * a + b * b)+1); + } + } + for (Map.Entry entry : m.entrySet()) { + res += entry.getValue() * (entry.getValue() - 1); + } + } + return res; + } + + + } + + public class UnitTest { + + + } +} From 0e97b1691ef198ed98abec35067f7efa23c0f580 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 12 Jul 2018 02:46:49 -0700 Subject: [PATCH 263/456] add relative_ranks --- .../java/relative_ranks/RelativeRanks.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/relative_ranks/RelativeRanks.java diff --git a/src/main/java/relative_ranks/RelativeRanks.java b/src/main/java/relative_ranks/RelativeRanks.java new file mode 100644 index 0000000..e20acef --- /dev/null +++ b/src/main/java/relative_ranks/RelativeRanks.java @@ -0,0 +1,45 @@ +package relative_ranks; + +import javafx.util.Pair; + +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * Created by lxie on 7/12/18. + */ +public class RelativeRanks { + + public class Solution { + + public String[] findRelativeRanks(int[] nums) { + int n = nums.length, cnt = 1; + String[] res = new String[n]; + PriorityQueue> q = + new PriorityQueue>(10, + new Comparator>() { + @Override + public int compare(Pair p1, Pair p2) { + return p2.getKey() - p1.getKey(); + } + }); + for (int i = 0; i < n; ++i) { + q.add(new Pair(nums[i], i)); + } + for (int i = 0; i < n; ++i) { + int idx = q.peek().getValue(); q.poll(); + if (cnt == 1) res[idx] = "Gold Medal"; + else if (cnt == 2) res[idx] = "Silver Medal"; + else if (cnt == 3) res[idx] = "Bronze Medal"; + else res[idx] = Integer.toString(cnt); + ++cnt; + } + return res; + } + + } + + public class UnitTest { + + } +} From e25fe76d38f7dcbf0863f9088ba86230b8fa482c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 13 Jul 2018 12:03:10 -0700 Subject: [PATCH 264/456] add longest_palindrome. --- .../longest_palindrome/LongestPalindrome.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/longest_palindrome/LongestPalindrome.java diff --git a/src/main/java/longest_palindrome/LongestPalindrome.java b/src/main/java/longest_palindrome/LongestPalindrome.java new file mode 100644 index 0000000..b5f3cb9 --- /dev/null +++ b/src/main/java/longest_palindrome/LongestPalindrome.java @@ -0,0 +1,38 @@ +package longest_palindrome; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 7/13/18. + */ +public class LongestPalindrome { + + public class Solution { + int longestPalindrome(String s) { + int res = 0; + boolean mid = false; + Map m = new HashMap<>(); + for (char c : s.toCharArray()) { + if (!m.containsKey(c)) { + m.put(c, 1); + } else { + m.put(c, m.get(c) + 1); + } + }; + + for (Map.Entry it: m.entrySet()) { + res += it.getValue(); + if (it.getValue() % 2 == 1) { + res -= 1; + mid = true; + } + } + return mid ? res + 1 : res; + } + } + + public class UnitTest { + + } +} From 5f42ad029dca97337b5e8190b798d0ad79e19795 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 13 Jul 2018 17:13:16 -0700 Subject: [PATCH 265/456] add diameter_of_binary_tree --- .../DiameterBinaryTree.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/diameter_of_binary_tree/DiameterBinaryTree.java diff --git a/src/main/java/diameter_of_binary_tree/DiameterBinaryTree.java b/src/main/java/diameter_of_binary_tree/DiameterBinaryTree.java new file mode 100644 index 0000000..abbdfb7 --- /dev/null +++ b/src/main/java/diameter_of_binary_tree/DiameterBinaryTree.java @@ -0,0 +1,37 @@ +package diameter_of_binary_tree; + +import common.TreeNode; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 7/13/18. + */ +public class DiameterBinaryTree { + + public class Solution { + private Map m = new HashMap<>(); + + public int diameterOfBinaryTree(TreeNode root) { + int[] res = {0}; + maxDepth(root, res); + return res[0]; + } + int maxDepth(TreeNode node, int[] res) { + if (node == null) return 0; + if (m.containsKey(node)) return m.get(node); + int left = maxDepth(node.left, res); + int right = maxDepth(node.right, res); + res[0] = Math.max(res[0], left + right); + int ret = Math.max(left, right) + 1; + m.put(node, ret); + return ret; + } + } + + public class UnitTest { + + + } +} From 0f165ab362d866aa67c28bb04c7d7e370626b005 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 14 Jul 2018 02:29:59 -0700 Subject: [PATCH 266/456] add binary_watch --- src/main/java/binary_watch/BinaryWatch.java | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/binary_watch/BinaryWatch.java diff --git a/src/main/java/binary_watch/BinaryWatch.java b/src/main/java/binary_watch/BinaryWatch.java new file mode 100644 index 0000000..475275c --- /dev/null +++ b/src/main/java/binary_watch/BinaryWatch.java @@ -0,0 +1,52 @@ +package binary_watch; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 7/14/18. + */ +public class BinaryWatch { + + public class Solution { + + public List readBinaryWatch(int num) { + List res = new ArrayList<>(); + int[] hour = {8, 4, 2, 1}; int[] minute = {32, 16, 8, 4, 2, 1}; + for (int i = 0; i <= num; ++i) { + List hours = generate(hour, i); + List minutes = generate(minute, num - i); + for (int h : hours) { + if (h > 11) continue; + for (int m : minutes) { + if (m > 59) continue; + res.add(Integer.toString(h) + (m < 10 ? ":0" : ":") + Integer.toString(m)); + } + } + } + return res; + } + + private List generate(int[] nums, int cnt) { + List res = new ArrayList<>(); + helper(nums, cnt, 0, 0, res); + return res; + } + + private void helper(int[] nums, int cnt, int pos, int out, List res) { + if (cnt == 0) { + res.add(out); + return; + } + for (int i = pos; i < nums.length; ++i) { + helper(nums, cnt - 1, i + 1, out + nums[i], res); + } + } + + } + + public class UnitTest { + + + } +} From ace7edbed0900375c4f91c94d11af446687fc58a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 17 Jul 2018 09:43:01 -0700 Subject: [PATCH 267/456] add sentence_similarity --- .../SentenceSimilarity.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/sentence_similarity/SentenceSimilarity.java diff --git a/src/main/java/sentence_similarity/SentenceSimilarity.java b/src/main/java/sentence_similarity/SentenceSimilarity.java new file mode 100644 index 0000000..8c14814 --- /dev/null +++ b/src/main/java/sentence_similarity/SentenceSimilarity.java @@ -0,0 +1,45 @@ +package sentence_similarity; + +import javafx.util.Pair; + +import java.util.*; + +/** + * Created by lxie on 7/17/18. + */ +public class SentenceSimilarity { + + public boolean areSentencesSimilar(String[] words1, String[] words2, List> pairs) { + if (words1.length != words2.length) return false; + Map> m = new HashMap<>(); + + for (Pair pair : pairs) { + //m[pair.first].insert(pair.second); + if (!m.containsKey(pair.getKey())) { + m.put(pair.getKey(), new HashSet<>(Arrays.asList(pair.getValue()))); + } else { + m.get(pair.getKey()).add(pair.getValue()); + } + } + for (int i = 0; i < words1.length; ++i) { + if (words1[i] == words2[i]) continue; + if((m.containsKey(words1[i]) && m.get(words1[i]).contains(words2[i])) || + (m.containsKey(words2[i]) && m.get(words2[i]).contains(words1[i]))) continue; + return false; + } + return true; + } + + public static void main(String[] args) { + SentenceSimilarity ss = new SentenceSimilarity(); + String[] words1 = {"great", "acting", "skills"}; + String[] words2 = {"fine","drama", "talent"}; + List> pairs = new ArrayList<>(); + pairs.add(new Pair<>("great", "fine")); + pairs.add(new Pair<>("acting", "drama")); + pairs.add(new Pair<>("skills", "talent")); + + System.out.println(ss.areSentencesSimilar(words1, words2, pairs)); + + } +} From 22269bd272e63abd4ee8ff6b4251e2c3d9017dfc Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 17 Jul 2018 10:33:24 -0700 Subject: [PATCH 268/456] add bold_words_in_string --- .../BoldWordsInString.java | 37 +++++++++++++++++++ .../SentenceSimilarity.java | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/main/java/bold_words_in_string/BoldWordsInString.java diff --git a/src/main/java/bold_words_in_string/BoldWordsInString.java b/src/main/java/bold_words_in_string/BoldWordsInString.java new file mode 100644 index 0000000..dad075e --- /dev/null +++ b/src/main/java/bold_words_in_string/BoldWordsInString.java @@ -0,0 +1,37 @@ +package bold_words_in_string; + +import java.util.HashSet; +import java.util.Set; + +/** + * Created by lxie on 7/17/18. + */ +public class BoldWordsInString { + + public String boldWords(String[] words, String S) { + int n = S.length(); + String res = ""; + Set bold = new HashSet<>(); + for (String word : words) { + int len = word.length(); + for (int i = 0; i <= n - len; ++i) { + if (S.charAt(i) == word.charAt(0) && S.substring(i, i+len).compareTo(word) == 0) { + for (int j = i; j < i + len; ++j) bold.add(j); + } + } + } + for (int i = 0; i < n; ++i) { + if (bold.contains(i) && !bold.contains(i - 1)) res += ""; + res += S.charAt(i); + if (bold.contains(i) && !bold.contains(i + 1)) res += ""; + } + return res; + } + + public static void main(String[] args) { + BoldWordsInString bs = new BoldWordsInString(); + String[] words = {"ab", "bc"}; + System.out.println(bs.boldWords(words, "aabcd")); + + } +} diff --git a/src/main/java/sentence_similarity/SentenceSimilarity.java b/src/main/java/sentence_similarity/SentenceSimilarity.java index 8c14814..87083fa 100644 --- a/src/main/java/sentence_similarity/SentenceSimilarity.java +++ b/src/main/java/sentence_similarity/SentenceSimilarity.java @@ -33,7 +33,7 @@ public boolean areSentencesSimilar(String[] words1, String[] words2, List> pairs = new ArrayList<>(); pairs.add(new Pair<>("great", "fine")); pairs.add(new Pair<>("acting", "drama")); From 7a5789b7d4413de54721ee9b59b3963799802671 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 18 Jul 2018 10:22:25 -0700 Subject: [PATCH 269/456] add compressed_string_iterator --- .../CompressedStringIterator.java | 39 +++++++++++++++ .../java/find_mode_bst/FindModeInBst.java | 50 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 src/main/java/compressed_string_iterator/CompressedStringIterator.java create mode 100644 src/main/java/find_mode_bst/FindModeInBst.java diff --git a/src/main/java/compressed_string_iterator/CompressedStringIterator.java b/src/main/java/compressed_string_iterator/CompressedStringIterator.java new file mode 100644 index 0000000..84a1ff1 --- /dev/null +++ b/src/main/java/compressed_string_iterator/CompressedStringIterator.java @@ -0,0 +1,39 @@ +package compressed_string_iterator; + +/** + * Created by lxie on 7/18/18. + */ +public class CompressedStringIterator { + + private static String s; + private int n = 0, i = 0, cnt = 0; + private char c; + + public CompressedStringIterator(String compressedString) { + s = compressedString; + n = s.length(); + c = ' '; + } + + public char next() { + if (hasNext()) { + --cnt; + return c; + } + return ' '; + } + + public boolean hasNext() { + if (cnt > 0) return true; + if (i >= n) return false; + c = s.charAt(i++); + while (i < n && s.charAt(i) >= '0' && s.charAt(i) <= '9') { + cnt = cnt * 10 + s.charAt(i++) - '0'; + } + return true; + } +} + + + + diff --git a/src/main/java/find_mode_bst/FindModeInBst.java b/src/main/java/find_mode_bst/FindModeInBst.java new file mode 100644 index 0000000..9b7948f --- /dev/null +++ b/src/main/java/find_mode_bst/FindModeInBst.java @@ -0,0 +1,50 @@ +package find_mode_bst; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 7/18/18. + */ +public class FindModeInBst { + + public class Solution { + + public List findMode(TreeNode root) { + List res = new ArrayList<>(); + int[] mx = {0}; + Map m = new HashMap<>(); + inorder(root, m, mx); + for (Map.Entry a : m.entrySet()) { + if (a.getValue().equals(mx)) { + res.add(a.getKey()); + } + } + return res; + } + + private void inorder(TreeNode node, Map m, int[] mx) { + if (node == null) return; + inorder(node.left, m, mx); + if (!m.containsKey(node.val)) { + m.put(node.val, 1); + } else { + m.put(node.val, m.get(node.val)+1); + } + mx[0] = Math.max(mx[0], m.get(node.val)); + inorder(node.right, m, mx); + } + + + } + + public class UnitTest { + + + } + +} From b5bfbe3a0f4e2c4ab4b8a949fee99f06e5ca5c51 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 18 Jul 2018 16:49:20 -0700 Subject: [PATCH 270/456] add longest_univalue_path --- .../LongestUnivaluePath.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/longest_univalue_path/LongestUnivaluePath.java diff --git a/src/main/java/longest_univalue_path/LongestUnivaluePath.java b/src/main/java/longest_univalue_path/LongestUnivaluePath.java new file mode 100644 index 0000000..dad30e0 --- /dev/null +++ b/src/main/java/longest_univalue_path/LongestUnivaluePath.java @@ -0,0 +1,29 @@ +package longest_univalue_path; + +import common.TreeNode; + +/** + * Created by lxie on 7/18/18. + */ +public class LongestUnivaluePath { + + public class Solution { + + public int longestUnivaluePath(TreeNode root) { + if (root == null) return 0; + int sub = Math.max(longestUnivaluePath(root.left), longestUnivaluePath(root.right)); + return Math.max(sub, helper(root.left, root.val) + helper(root.right, root.val)); + } + + private int helper(TreeNode node, int parent) { + if (node == null || node.val != parent) return 0; + return 1 + Math.max(helper(node.left, node.val), helper(node.right, node.val)); + } + } + + public class UnitTest { + + + + } +} From 30821584a7fff83c191799aee9e0446a098de3e2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 21 Jul 2018 01:53:38 -0700 Subject: [PATCH 271/456] add encode_decode_tinyurl --- .../EncodeDecodeTinyUrl.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java diff --git a/src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java b/src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java new file mode 100644 index 0000000..636980d --- /dev/null +++ b/src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java @@ -0,0 +1,47 @@ +package encode_decode_strings; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +/** + * Created by lxie on 7/21/18. + */ +public class EncodeDecodeTinyUrl { + + private Map short2long = new HashMap<>(); + private Map long2short = new HashMap<>(); + private String dict = ""; + + public EncodeDecodeTinyUrl(String longUrl) { + dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + } + + // Encodes a URL to a shortened URL. + public String encode(String longUrl) { + if (long2short.containsKey(longUrl)) { + return "http://tinyurl.com/" + long2short.get(longUrl); + } + int idx = 0; + String randStr = ""; + for (int i = 0; i < 6; ++i) { + Random rand = new Random(); + randStr += dict.charAt(rand.nextInt() % 62); + } + while (short2long.containsKey(randStr)) { + Random rand = new Random(); + randStr.toCharArray()[idx] = dict.charAt(rand.nextInt() % 62); + idx = (idx + 1) % 5; + } + short2long.put(randStr, longUrl); + long2short.put(longUrl, randStr); + return "http://tinyurl.com/" + randStr; + } + + // Decodes a shortened URL to its original URL. + public String decode(String shortUrl) { + String randStr = shortUrl.substring(shortUrl.lastIndexOf("/") + 1); + return short2long.containsKey(randStr) ? short2long.get(randStr) : shortUrl; + } + +} From 7ddec215dbca26f4b0cba8469c32ac4628fec2b3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 21 Jul 2018 01:58:27 -0700 Subject: [PATCH 272/456] dir change --- .../EncodeDecodeTinyUrl.java | 47 ------------------- 1 file changed, 47 deletions(-) delete mode 100644 src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java diff --git a/src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java b/src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java deleted file mode 100644 index 636980d..0000000 --- a/src/main/java/encode_decode_strings/EncodeDecodeTinyUrl.java +++ /dev/null @@ -1,47 +0,0 @@ -package encode_decode_strings; - -import java.util.HashMap; -import java.util.Map; -import java.util.Random; - -/** - * Created by lxie on 7/21/18. - */ -public class EncodeDecodeTinyUrl { - - private Map short2long = new HashMap<>(); - private Map long2short = new HashMap<>(); - private String dict = ""; - - public EncodeDecodeTinyUrl(String longUrl) { - dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - } - - // Encodes a URL to a shortened URL. - public String encode(String longUrl) { - if (long2short.containsKey(longUrl)) { - return "http://tinyurl.com/" + long2short.get(longUrl); - } - int idx = 0; - String randStr = ""; - for (int i = 0; i < 6; ++i) { - Random rand = new Random(); - randStr += dict.charAt(rand.nextInt() % 62); - } - while (short2long.containsKey(randStr)) { - Random rand = new Random(); - randStr.toCharArray()[idx] = dict.charAt(rand.nextInt() % 62); - idx = (idx + 1) % 5; - } - short2long.put(randStr, longUrl); - long2short.put(longUrl, randStr); - return "http://tinyurl.com/" + randStr; - } - - // Decodes a shortened URL to its original URL. - public String decode(String shortUrl) { - String randStr = shortUrl.substring(shortUrl.lastIndexOf("/") + 1); - return short2long.containsKey(randStr) ? short2long.get(randStr) : shortUrl; - } - -} From 61c0d8368b75c918213477180790264100f8a4a5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 21 Jul 2018 02:01:14 -0700 Subject: [PATCH 273/456] change location --- .../EncodeDecodeTinyUrl.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java diff --git a/src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java b/src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java new file mode 100644 index 0000000..636980d --- /dev/null +++ b/src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java @@ -0,0 +1,47 @@ +package encode_decode_strings; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +/** + * Created by lxie on 7/21/18. + */ +public class EncodeDecodeTinyUrl { + + private Map short2long = new HashMap<>(); + private Map long2short = new HashMap<>(); + private String dict = ""; + + public EncodeDecodeTinyUrl(String longUrl) { + dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + } + + // Encodes a URL to a shortened URL. + public String encode(String longUrl) { + if (long2short.containsKey(longUrl)) { + return "http://tinyurl.com/" + long2short.get(longUrl); + } + int idx = 0; + String randStr = ""; + for (int i = 0; i < 6; ++i) { + Random rand = new Random(); + randStr += dict.charAt(rand.nextInt() % 62); + } + while (short2long.containsKey(randStr)) { + Random rand = new Random(); + randStr.toCharArray()[idx] = dict.charAt(rand.nextInt() % 62); + idx = (idx + 1) % 5; + } + short2long.put(randStr, longUrl); + long2short.put(longUrl, randStr); + return "http://tinyurl.com/" + randStr; + } + + // Decodes a shortened URL to its original URL. + public String decode(String shortUrl) { + String randStr = shortUrl.substring(shortUrl.lastIndexOf("/") + 1); + return short2long.containsKey(randStr) ? short2long.get(randStr) : shortUrl; + } + +} From 243484f2c637baa5e9d9a684125d1efd9a274254 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 21 Jul 2018 02:03:07 -0700 Subject: [PATCH 274/456] change package name for encode_decode_tinyurl --- src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java b/src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java index 636980d..6209c21 100644 --- a/src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java +++ b/src/main/java/encode_decode_tinyurl/EncodeDecodeTinyUrl.java @@ -1,4 +1,4 @@ -package encode_decode_strings; +package encode_decode_tinyurl; import java.util.HashMap; import java.util.Map; From b8a745b9ee9adac82db54b56d418eada5054d7c2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 24 Jul 2018 07:15:08 -0700 Subject: [PATCH 275/456] add design_hit_counter --- .../java/design_hit_counter/HitCounter.java | 30 ++++++++++++++++ .../java/range_addition/RangeAddition.java | 36 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 src/main/java/design_hit_counter/HitCounter.java create mode 100644 src/main/java/range_addition/RangeAddition.java diff --git a/src/main/java/design_hit_counter/HitCounter.java b/src/main/java/design_hit_counter/HitCounter.java new file mode 100644 index 0000000..79f168c --- /dev/null +++ b/src/main/java/design_hit_counter/HitCounter.java @@ -0,0 +1,30 @@ +package design_hit_counter; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by lxie on 7/24/18. + */ +public class HitCounter { + + private Queue q = new LinkedList<>(); + + public HitCounter() {}; + + /** Record a hit. + @param timestamp - The current timestamp (in seconds granularity). */ + public void hit(int timestamp) { + q.add(timestamp); + } + + /** Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). */ + public int getHits(int timestamp) { + while (q.isEmpty() && timestamp - q.peek() >= 300) { + q.poll(); + } + return q.size(); + } + +} diff --git a/src/main/java/range_addition/RangeAddition.java b/src/main/java/range_addition/RangeAddition.java new file mode 100644 index 0000000..4623239 --- /dev/null +++ b/src/main/java/range_addition/RangeAddition.java @@ -0,0 +1,36 @@ +package range_addition; + +/** + * Created by lxie on 7/23/18. + */ +public class RangeAddition { + + public class Solution { + + public int[] getModifiedArray(int length, int[][] updates) { + // Write your code here + int add[] = new int[length + 1]; + int res[] = new int[length]; + for(int i = 0; i < updates.length; i++){ + int first = updates[i][0]; + int second = updates[i][1]; + int third = updates[i][2]; + + add[first] += third; + add[second + 1] -= third; + } + res[0] = add[0]; + for(int i = 1; i < res.length; i++){ + res[i] = add[i] + res[i - 1]; + } + + return res; + } + + } + + public class UnitTest { + + } + +} From ef8a152b77f3f715ba5b75ce5ecfc3ee402f4753 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 24 Jul 2018 07:57:06 -0700 Subject: [PATCH 276/456] add daily_temperature --- .../daily_temperature/DailyTemperature.java | 31 +++++++++++++++++++ .../java/design_hit_counter/HitCounter.java | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/main/java/daily_temperature/DailyTemperature.java diff --git a/src/main/java/daily_temperature/DailyTemperature.java b/src/main/java/daily_temperature/DailyTemperature.java new file mode 100644 index 0000000..1c18a20 --- /dev/null +++ b/src/main/java/daily_temperature/DailyTemperature.java @@ -0,0 +1,31 @@ +package daily_temperature; + +import java.util.Stack; + +/** + * Created by lxie on 7/24/18. + */ +public class DailyTemperature { + + public class Solution { + + public int[] dailyTemperatures(int[] temperatures) { + int n = temperatures.length; + int[] res = new int[n]; + Stack st = new Stack<>(); + for (int i = 0; i < temperatures.length; ++i) { + while (!st.empty() && temperatures[i] > temperatures[st.peek()]) { + int t = st.peek(); st.pop(); + res[t] = i - t; + } + st.push(i); + } + return res; + } + + } + + public class UnitTest { + + } +} diff --git a/src/main/java/design_hit_counter/HitCounter.java b/src/main/java/design_hit_counter/HitCounter.java index 79f168c..45e299a 100644 --- a/src/main/java/design_hit_counter/HitCounter.java +++ b/src/main/java/design_hit_counter/HitCounter.java @@ -26,5 +26,5 @@ public int getHits(int timestamp) { } return q.size(); } - + } From 89cc9ad2b1fb60123f28c3098ce159c598aaa369 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 24 Jul 2018 10:23:20 -0700 Subject: [PATCH 277/456] add beautiful_arrangement --- .../BeautifulArrangement.java | 36 +++++++++++++++++++ .../daily_temperature/DailyTemperature.java | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/main/java/beautiful_arrangement/BeautifulArrangement.java diff --git a/src/main/java/beautiful_arrangement/BeautifulArrangement.java b/src/main/java/beautiful_arrangement/BeautifulArrangement.java new file mode 100644 index 0000000..68c4598 --- /dev/null +++ b/src/main/java/beautiful_arrangement/BeautifulArrangement.java @@ -0,0 +1,36 @@ +package beautiful_arrangement; + +/** + * Created by lxie on 7/24/18. + */ +public class BeautifulArrangement { + + public class Solution { + + public int countArrangement(int N) { + int[] res = {0}; + int[] visited = new int[N + 1]; + helper(N, visited, 1, res); + return res; + } + void helper(int N, int[] visited, int pos, int[] res) { + if (pos > N) { + ++res[0]; + return; + } + for (int i = 1; i <= N; ++i) { + if (visited[i] == 0 && (i % pos == 0 || pos % i == 0)) { + visited[i] = 1; + helper(N, visited, pos + 1, res); + visited[i] = 0; + } + } + } + } + + public class UnitTest { + + } + + +} diff --git a/src/main/java/daily_temperature/DailyTemperature.java b/src/main/java/daily_temperature/DailyTemperature.java index 1c18a20..5894281 100644 --- a/src/main/java/daily_temperature/DailyTemperature.java +++ b/src/main/java/daily_temperature/DailyTemperature.java @@ -26,6 +26,6 @@ public int[] dailyTemperatures(int[] temperatures) { } public class UnitTest { - + } } From bd1558ca4295b831c7625621e28ff37de51b765a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 26 Jul 2018 00:31:07 -0700 Subject: [PATCH 278/456] add sort_chars_by_frequency --- .../BeautifulArrangement.java | 2 +- .../SortCharsByFrequency.java | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java diff --git a/src/main/java/beautiful_arrangement/BeautifulArrangement.java b/src/main/java/beautiful_arrangement/BeautifulArrangement.java index 68c4598..fff8537 100644 --- a/src/main/java/beautiful_arrangement/BeautifulArrangement.java +++ b/src/main/java/beautiful_arrangement/BeautifulArrangement.java @@ -11,7 +11,7 @@ public int countArrangement(int N) { int[] res = {0}; int[] visited = new int[N + 1]; helper(N, visited, 1, res); - return res; + return res[0]; } void helper(int N, int[] visited, int pos, int[] res) { if (pos > N) { diff --git a/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java new file mode 100644 index 0000000..1ae94be --- /dev/null +++ b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java @@ -0,0 +1,44 @@ +package sort_chars_by_frequency; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 7/25/18. + */ +public class SortCharsByFrequency { + + public String frequencySort(String s) { + String res = ""; + String[] v = new String[s.length()+1]; + for (int i=0; i m = new HashMap<>(); + for (char c : s.toCharArray()) { + if (!m.containsKey(c)) { + m.put(c, 1); + } else { + m.put(c, m.get(c)+1); + } + } + for (Map.Entry a : m.entrySet()) { + for(int i=0; i 0; --i) { + if (!v[i].isEmpty()) { + res += v[i]; + } + } + return res; + } + + public static void main(String[] args) { + + SortCharsByFrequency scbf = new SortCharsByFrequency(); + System.out.println(scbf.frequencySort("Aabb")); + } + + + +} From 4d687e583d5f8bf374157576128042278665913e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 29 Jul 2018 16:30:34 -0700 Subject: [PATCH 279/456] add sort_list --- .../SortCharsByFrequency.java | 2 + src/main/java/sort_list/SortList.java | 64 +++++++------------ 2 files changed, 26 insertions(+), 40 deletions(-) diff --git a/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java index 1ae94be..5674b6b 100644 --- a/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java +++ b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java @@ -6,6 +6,8 @@ /** * Created by lxie on 7/25/18. */ + +/* time limit exceeds */ public class SortCharsByFrequency { public String frequencySort(String s) { diff --git a/src/main/java/sort_list/SortList.java b/src/main/java/sort_list/SortList.java index 254e561..ee14c68 100644 --- a/src/main/java/sort_list/SortList.java +++ b/src/main/java/sort_list/SortList.java @@ -6,51 +6,35 @@ public class SortList { public class Solution { - private ListNode merge(ListNode h1, ListNode h2) { - ListNode dummy = new ListNode(0); - ListNode prefix = dummy; - while (h1 != null || h2 != null) { - if (h2 == null || (h1 != null && h1.val < h2.val)) { - prefix.next = h1; - prefix = h1; - h1 = h1.next; - } else { - prefix.next = h2; - prefix = h2; - h2 = h2.next; - } + public ListNode sortList(ListNode head) { + if (head == null || head.next == null) return head; + ListNode slow = head, fast = head, pre = head; + while (fast != null && fast.next != null) { + pre = slow; + slow = slow.next; + fast = fast.next.next; } - return dummy.next; + pre.next = null; + return merge(sortList(head), sortList(slow)); } - private ListNode sortList(ListNode head, int start, int end, - ListNode[] tail) { - if (start == end) { - tail[0] = head; - return null; - } - if (end - start == 1) { - tail[0] = head.next; - head.next = null; - return head; - } - int mid = start + (end - start) / 2; - ListNode left = sortList(head, start, mid, tail); - ListNode right = sortList(tail[0], mid, end, tail); - return merge(left, right); - } - private int len(ListNode head) { - int len = 0; - while (head != null) { - len++; - head = head.next; + private ListNode merge(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(-1); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val < l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; } - return len; - } - - public ListNode sortList(ListNode head) { - return sortList(head, 0, len(head), new ListNode[1]); + if (l1 != null) cur.next = l1; + if (l2 != null) cur.next = l2; + return dummy.next; } } From 060fd1b33369ba3032e9681bff90718892f6f255 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 30 Jul 2018 23:24:42 -0700 Subject: [PATCH 280/456] modify word_break_ii --- src/main/java/word_break_ii/WordBreakII.java | 68 ++++++++++++-------- 1 file changed, 40 insertions(+), 28 deletions(-) diff --git a/src/main/java/word_break_ii/WordBreakII.java b/src/main/java/word_break_ii/WordBreakII.java index 691398c..a389bd8 100644 --- a/src/main/java/word_break_ii/WordBreakII.java +++ b/src/main/java/word_break_ii/WordBreakII.java @@ -1,43 +1,55 @@ package word_break_ii; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.util.*; public class WordBreakII { - public class Solution { - private ArrayList searchWordBreak(String s, Set dict, - Map> solutions) { - ArrayList solution = solutions.get(s); - if (solution != null) { - return solution; + public static class Solution { + public ArrayList wordBreak(String s, Set dict) { + Map> memo = new HashMap>(); + return wordBreakHelper(s, dict, memo); + } + + public ArrayList wordBreakHelper(String s, + Set dict, + Map> memo){ + if (memo.containsKey(s)) { + return memo.get(s); } - solution = new ArrayList(); - for (int i = 1; i < s.length(); i++) { - String prefix = s.substring(0, i); - if (dict.contains(prefix)) { - for (String subfix : searchWordBreak(s.substring(i), dict, - solutions)) { - solution.add(prefix + " " + subfix); - } - } + + ArrayList results = new ArrayList(); + + if (s.length() == 0) { + return results; } + if (dict.contains(s)) { - solution.add(s); + results.add(s); } - solutions.put(s, solution); - return solution; - } - public ArrayList wordBreak(String s, Set dict) { - return searchWordBreak(s, dict, - new HashMap>()); + for (int len = 1; len < s.length(); ++len){ + String word = s.substring(0, len); + if (!dict.contains(word)) { + continue; + } + + String suffix = s.substring(len); + ArrayList segmentations = wordBreakHelper(suffix, dict, memo); + + for (String segmentation: segmentations){ + results.add(word + " " + segmentation); + } + } + + memo.put(s, results); + return results; } } - public static class UnitTest { - + public static void main(String[] args) { + Set dict = new HashSet<>(Arrays.asList("cat", "cats", "and", "sand", "dog")); + Solution sol = new Solution(); + System.out.println(sol.wordBreak("catsanddog", dict)); + } } From 643fce2c5d84387667734170e36387ff8cfce0fd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 31 Jul 2018 18:49:23 -0700 Subject: [PATCH 281/456] modify single_number_ii --- .../java/single_number_ii/SingleNumberII.java | 24 +++++++------------ src/main/java/word_break_ii/WordBreakII.java | 2 +- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/main/java/single_number_ii/SingleNumberII.java b/src/main/java/single_number_ii/SingleNumberII.java index 99e6a2b..0d16ece 100644 --- a/src/main/java/single_number_ii/SingleNumberII.java +++ b/src/main/java/single_number_ii/SingleNumberII.java @@ -3,22 +3,16 @@ public class SingleNumberII { public class Solution { - public int singleNumber(int[] A) { - int[] bits = new int[32]; - for (int a : A) { - for (int i = 0; i < 32; i++) { - if ((a & (1 << i)) != 0) { - bits[i]++; - } - } + public int singleNumber(int[] nums) { + int one = 0, two = 0, three = 0; + for (int i = 0; i < nums.length; ++i) { + two |= one & nums[i]; + one ^= nums[i]; + three = one & two; + one &= ~three; + two &= ~three; } - int ans = 0; - for (int i = 0; i < 32; i++) { - if (bits[i] % 3 == 1) { - ans |= (1 << i); - } - } - return ans; + return one; } } diff --git a/src/main/java/word_break_ii/WordBreakII.java b/src/main/java/word_break_ii/WordBreakII.java index a389bd8..5f23e3c 100644 --- a/src/main/java/word_break_ii/WordBreakII.java +++ b/src/main/java/word_break_ii/WordBreakII.java @@ -50,6 +50,6 @@ public static void main(String[] args) { Set dict = new HashSet<>(Arrays.asList("cat", "cats", "and", "sand", "dog")); Solution sol = new Solution(); System.out.println(sol.wordBreak("catsanddog", dict)); - + } } From 5faeab985f3eea240dedde9fc89dc3000cfaac84 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 1 Aug 2018 10:16:16 -0700 Subject: [PATCH 282/456] modify palindrome_partitioning --- .../PalindromePartitioning.java | 63 +++++++++---------- 1 file changed, 29 insertions(+), 34 deletions(-) diff --git a/src/main/java/palindrome_partitioning/PalindromePartitioning.java b/src/main/java/palindrome_partitioning/PalindromePartitioning.java index d4a65a0..1633000 100644 --- a/src/main/java/palindrome_partitioning/PalindromePartitioning.java +++ b/src/main/java/palindrome_partitioning/PalindromePartitioning.java @@ -1,51 +1,46 @@ package palindrome_partitioning; import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; +import java.util.List; public class PalindromePartitioning { - public class Solution { - private boolean isPalindromic(String s) { - for (int i = 0; i < s.length() / 2; i++) { - if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { - return false; - } - } - return true; - } + public static class Solution { - private Map>> cache = new HashMap>>(); + public List> partition(String s) { + List> res = new ArrayList<>(); + List out = new ArrayList<>(); + partitionDFS(s, 0, out, res); + return res; + } - public ArrayList> partition(String s) { - ArrayList> ans = cache.get(s); - if (ans != null) { - return ans; + public void partitionDFS(String s, int start, List out, List> res) { + if (start == s.length()) { + res.add(new ArrayList<>(out)); + return; } - ans = new ArrayList>(); - for (int i = 1; i < s.length(); i++) { - String prefix = s.substring(0, i); - if (isPalindromic(prefix)) { - for (ArrayList subans : partition(s.substring(i))) { - ArrayList temp = new ArrayList(); - temp.add(prefix); - temp.addAll(subans); - ans.add(temp); - } + for (int i = start; i < s.length(); ++i) { + if (isPalindrome(s, start, i)) { + out.add(s.substring(start, i+1)); + partitionDFS(s, i + 1, out, res); + out.remove(out.size()-1); } } - if (isPalindromic(s)) { - ArrayList temp = new ArrayList(); - temp.add(s); - ans.add(temp); + } + + private boolean isPalindrome(String s, int start, int end) { + while (start < end) { + if (s.charAt(start) != s.charAt(end)) return false; + ++start; + --end; } - cache.put(s, ans); - return ans; + return true; } - } - public static class UnitTest { + } + public static void main(String[] args) { + Solution sol = new Solution(); + System.out.println(sol.partition("aab")); } } From 922606eee07fc193cb99492beb32cc7e33573db8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 3 Aug 2018 07:26:11 -0700 Subject: [PATCH 283/456] modify binary_tree_maximum_path_sum. --- .../BinaryTreeMaximumPathSum.java | 39 ++++++------------- 1 file changed, 12 insertions(+), 27 deletions(-) diff --git a/src/main/java/binary_tree_maximum_path_sum/BinaryTreeMaximumPathSum.java b/src/main/java/binary_tree_maximum_path_sum/BinaryTreeMaximumPathSum.java index fdd0fc9..a63cb96 100644 --- a/src/main/java/binary_tree_maximum_path_sum/BinaryTreeMaximumPathSum.java +++ b/src/main/java/binary_tree_maximum_path_sum/BinaryTreeMaximumPathSum.java @@ -5,36 +5,21 @@ public class BinaryTreeMaximumPathSum { public class Solution { - private int maxPathSum(TreeNode root, int[] partSum) { - int leftSum = 0; - int leftPartSum = 0; - int rightSum = 0; - int rightPartSum = 0; - if (root.left != null) { - leftSum = maxPathSum(root.left, partSum); - leftPartSum = partSum[0] > 0 ? partSum[0] : 0; - } - if (root.right != null) { - rightSum = maxPathSum(root.right, partSum); - rightPartSum = partSum[0] > 0 ? partSum[0] : 0; - } - int maxSum = leftPartSum + rightPartSum + root.val; - if (root.left != null) { - maxSum = Math.max(maxSum, leftSum); - } - if (root.right != null) { - maxSum = Math.max(maxSum, rightSum); - } - partSum[0] = Math.max(leftPartSum, rightPartSum) + root.val; - return maxSum; - } public int maxPathSum(TreeNode root) { - if (root == null) { - return 0; - } - return maxPathSum(root, new int[1]); + int[] res = {Integer.MIN_VALUE}; + helper(root, res); + return res[0]; + } + + private int helper(TreeNode node, int[] res) { + if (node == null) return 0; + int left = Math.max(helper(node.left, res), 0); + int right = Math.max(helper(node.right, res), 0); + res[0] = Math.max(res[0], left + right + node.val); + return Math.max(left, right) + node.val; } + } public static class UnitTest { From 1de7edb3fea1630db40e72b8445a7741b7af84ac Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 4 Aug 2018 00:26:22 -0700 Subject: [PATCH 284/456] modify populating_next_right --- ...pulatingNextRightPointersinEachNodeII.java | 43 ++++++++----------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java b/src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java index d9b44be..9c9987f 100644 --- a/src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java +++ b/src/main/java/populating_next_right_pointers_in_each_node_ii/PopulatingNextRightPointersinEachNodeII.java @@ -4,36 +4,27 @@ public class PopulatingNextRightPointersinEachNodeII { - public class Solution { + public class Solution { // const space public void connect(TreeLinkNode root) { - TreeLinkNode leftMost = root; - while (leftMost != null) { - TreeLinkNode p = leftMost; - TreeLinkNode pre = null; - leftMost = null; - while (p != null) { - if (p.left != null) { - if (leftMost == null) { - leftMost = p.left; - } - if (pre != null) { - pre.next = p.left; - } - pre = p.left; - } - if (p.right != null) { - if (leftMost == null) { - leftMost = p.right; - } - if (pre != null) { - pre.next = p.right; - } - pre = p.right; - } - p = p.next; + TreeLinkNode dummy = new TreeLinkNode(0), t = dummy; + while (root != null) { + if (root.left != null) { + t.next = root.left; + t = t.next; + } + if (root.right != null) { + t.next = root.right; + t = t.next; + } + root = root.next; + if (root == null) { + t = dummy; + root = dummy.next; + dummy.next = null; } } } + } public static class UnitTest { From 976f8fd29f97be2785c0a0ade88db4b3e6fac197 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 4 Aug 2018 08:00:24 -0700 Subject: [PATCH 285/456] add path_sum_ii --- src/main/java/path_sum_ii/PathSumII.java | 43 ++++++++++-------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/src/main/java/path_sum_ii/PathSumII.java b/src/main/java/path_sum_ii/PathSumII.java index 43af93b..a58c93c 100644 --- a/src/main/java/path_sum_ii/PathSumII.java +++ b/src/main/java/path_sum_ii/PathSumII.java @@ -1,39 +1,32 @@ package path_sum_ii; -import java.util.ArrayList; - import common.TreeNode; +import java.util.ArrayList; +import java.util.List; + public class PathSumII { public class Solution { - public ArrayList> pathSum(TreeNode root, int sum) { - ArrayList> ans = new ArrayList>(); - if (root != null) { - pathSum(root, sum, new ArrayList(), ans); - } - return ans; + + public List> pathSum(TreeNode root, int sum) { + List> res = new ArrayList<>(); + List out = new ArrayList<>(); + helper(root, sum, out, res); + return res; } - private void pathSum(TreeNode root, int sum, ArrayList nodes, - ArrayList> ans) { - if (root.left == null && root.right == null) { - if (root.val == sum) { - ArrayList temp = new ArrayList(nodes); - temp.add(root.val); - ans.add(temp); - } - return; - } - nodes.add(root.val); - if (root.left != null) { - pathSum(root.left, sum - root.val, nodes, ans); + private void helper(TreeNode node, int sum, List out, List> res) { + if (node == null) return; + out.add(node.val); + if (sum == node.val && node.left == null && node.right == null) { + res.add(new ArrayList<>(out)); // do not use the same reference } - if (root.right != null) { - pathSum(root.right, sum - root.val, nodes, ans); - } - nodes.remove(nodes.size() - 1); + helper(node.left, sum - node.val, out, res); + helper(node.right, sum - node.val, out, res); + out.remove(out.size()-1); // back-track to remove current } + } public static class UnitTest { From d4b87acbf943b9613d2a3f1e72d4be40bef97e72 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 4 Aug 2018 10:30:59 -0700 Subject: [PATCH 286/456] modify convert_sorted_list_to_bst --- .../ConvertSortedListtoBinarySearchTree.java | 36 +++++++++---------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java b/src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java index 7a45fd6..a4a56a4 100644 --- a/src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java +++ b/src/main/java/convert_sorted_list_to_binary_search_tree/ConvertSortedListtoBinarySearchTree.java @@ -6,29 +6,25 @@ public class ConvertSortedListtoBinarySearchTree { public class Solution { - private TreeNode sortedListToBST(ListNode head, ListNode[] tail, - int begin, int end) { - if (begin > end) { - tail[0] = head; - return null; - } - TreeNode p = new TreeNode(0); - int mid = begin + (end - begin) / 2; - p.left = sortedListToBST(head, tail, begin, mid - 1); - p.val = tail[0].val; - p.right = sortedListToBST(tail[0].next, tail, mid + 1, end); - return p; - } - public TreeNode sortedListToBST(ListNode head) { - ListNode p = head; - int len = 0; - while (p != null) { - len++; - p = p.next; + if (head == null) return null; + if (head.next == null) return new TreeNode(head.val); + ListNode slow = head; + ListNode fast = head; + ListNode last = slow; + while (fast.next != null && fast.next.next != null) { + last = slow; + slow = slow.next; + fast = fast.next.next; } - return sortedListToBST(head, new ListNode[1], 0, len - 1); + fast = slow.next; + last.next = null; + TreeNode cur = new TreeNode(slow.val); + if (head != slow) cur.left = sortedListToBST(head); + cur.right = sortedListToBST(fast); + return cur; } + } public static class UnitTest { From c03b680f67173d940c50185aed74c41a2d290546 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 5 Aug 2018 15:46:35 -0700 Subject: [PATCH 287/456] modify contruct_binary_trees --- ...yTreefromInorderandPostorderTraversal.java | 36 ++++++++----------- ...ryTreefromPreorderandInorderTraversal.java | 36 ++++++++----------- 2 files changed, 30 insertions(+), 42 deletions(-) diff --git a/src/main/java/construct_binary_tree_from_inorder_and_postorder_traversal/ConstructBinaryTreefromInorderandPostorderTraversal.java b/src/main/java/construct_binary_tree_from_inorder_and_postorder_traversal/ConstructBinaryTreefromInorderandPostorderTraversal.java index 60b9cbb..760c5b3 100644 --- a/src/main/java/construct_binary_tree_from_inorder_and_postorder_traversal/ConstructBinaryTreefromInorderandPostorderTraversal.java +++ b/src/main/java/construct_binary_tree_from_inorder_and_postorder_traversal/ConstructBinaryTreefromInorderandPostorderTraversal.java @@ -1,35 +1,29 @@ package construct_binary_tree_from_inorder_and_postorder_traversal; -import java.util.HashMap; -import java.util.Map; - import common.TreeNode; +import java.util.List; + public class ConstructBinaryTreefromInorderandPostorderTraversal { public class Solution { - private TreeNode buildTree(Map inorder, int b1, - int[] postorder, int b2, int len) { - if (len == 0) { - return null; - } - TreeNode node = new TreeNode(postorder[b2 + len - 1]); - int i = inorder.get(node.val); - node.left = buildTree(inorder, b1, postorder, b2, i - b1); - node.right = buildTree(inorder, i + 1, postorder, b2 + i - b1, len - - i + b1 - 1); - return node; + public TreeNode buildTree(List inorder, List postorder) { + return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); } - public TreeNode buildTree(int[] inorder, int[] postorder) { - assert inorder != null && postorder != null - && inorder.length == postorder.length; - Map inorderNodes = new HashMap(); - for (int i = 0; i < inorder.length; i++) { - inorderNodes.put(inorder[i], i); + private TreeNode buildTree(List inorder, int iLeft, int iRight, + List postorder, int pLeft, int pRight) { + if (iLeft > iRight || pLeft > pRight) return null; + TreeNode cur = new TreeNode(postorder.get(pRight)); + int i = 0; + for (i = iLeft; i < inorder.size(); ++i) { + if (inorder.get(i) == cur.val) break; } - return buildTree(inorderNodes, 0, postorder, 0, inorder.length); + cur.left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1); + cur.right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1); + return cur; } + } public static class UnitTest { diff --git a/src/main/java/construct_binary_tree_from_preorder_and_inorder_traversal/ConstructBinaryTreefromPreorderandInorderTraversal.java b/src/main/java/construct_binary_tree_from_preorder_and_inorder_traversal/ConstructBinaryTreefromPreorderandInorderTraversal.java index d1efd84..a1e53b3 100644 --- a/src/main/java/construct_binary_tree_from_preorder_and_inorder_traversal/ConstructBinaryTreefromPreorderandInorderTraversal.java +++ b/src/main/java/construct_binary_tree_from_preorder_and_inorder_traversal/ConstructBinaryTreefromPreorderandInorderTraversal.java @@ -1,34 +1,28 @@ package construct_binary_tree_from_preorder_and_inorder_traversal; -import java.util.HashMap; -import java.util.Map; - import common.TreeNode; +import java.util.List; + public class ConstructBinaryTreefromPreorderandInorderTraversal { public class Solution { - private TreeNode buildTree(int[] preorder, int b1, - Map inorderNodes, int b2, int len) { - if (len == 0) { - return null; - } - TreeNode node = new TreeNode(preorder[b1]); - int i = inorderNodes.get(node.val); - node.left = buildTree(preorder, b1 + 1, inorderNodes, b2, i - b2); - node.right = buildTree(preorder, b1 + 1 + i - b2, inorderNodes, - i + 1, len - i + b2 - 1); - return node; + TreeNode buildTree(List preorder, List inorder) { + return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); } - - public TreeNode buildTree(int[] preorder, int[] inorder) { - assert (preorder != null && inorder != null && preorder.length == inorder.length); - Map inorderNodes = new HashMap(); - for (int i = 0; i < inorder.length; i++) { - inorderNodes.put(inorder[i], i); + TreeNode buildTree(List preorder, int pLeft, int pRight, + List inorder, int iLeft, int iRight) { + if (pLeft > pRight || iLeft > iRight) return null; + int i = 0; + for (i = iLeft; i <= iRight; ++i) { + if (preorder.get(pLeft) == inorder.get(i)) break; } - return buildTree(preorder, 0, inorderNodes, 0, inorder.length); + TreeNode cur = new TreeNode(preorder.get(pLeft)); + cur.left = buildTree(preorder, pLeft + 1, pLeft + i - iLeft, inorder, iLeft, i - 1); + cur.right = buildTree(preorder, pLeft + i - iLeft + 1, pRight, inorder, i + 1, iRight); + return cur; } + } public static class UnitTest { From cd0e72c396779f720e29d8dfed0b32a8f4d80a17 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 5 Aug 2018 17:45:31 -0700 Subject: [PATCH 288/456] modify recover_bst --- .../RecoverBinarySearchTree.java | 66 +++++++++---------- 1 file changed, 30 insertions(+), 36 deletions(-) diff --git a/src/main/java/recover_binary_search_tree/RecoverBinarySearchTree.java b/src/main/java/recover_binary_search_tree/RecoverBinarySearchTree.java index d0cb0f8..4ee1f74 100644 --- a/src/main/java/recover_binary_search_tree/RecoverBinarySearchTree.java +++ b/src/main/java/recover_binary_search_tree/RecoverBinarySearchTree.java @@ -4,50 +4,44 @@ public class RecoverBinarySearchTree { - public class Solution { + public class Solution { // O(1) space public void recoverTree(TreeNode root) { - TreeNode first = null; - TreeNode second = null; - TreeNode p = root; - TreeNode pre = null; - while (p != null) { - if (p.left == null) { - if (pre != null && pre.val > p.val) { - if (first == null) { - first = pre; - second = p; - } else { - second = p; - } + TreeNode first = null, second = null, parent = null; + TreeNode cur, pre; + cur = root; + while (cur != null) { + if (cur.left == null) { + if (parent != null && parent.val > cur.val) { + if (first == null) first = parent; + second = cur; } - pre = p; - p = p.right; + parent = cur; + cur = cur.right; } else { - TreeNode temp = p.left; - while (temp.right != null && temp.right != p) { - temp = temp.right; - } - if (temp.right == null) { - temp.right = p; - p = p.left; + pre = cur.left; + while (pre.right != null && pre.right != cur) pre = pre.right; + if (pre.right == null) { + pre.right = cur; + cur = cur.left; } else { - if (pre != null && pre.val > p.val) { - if (first == null) { - first = pre; - second = p; - } else { - second = p; - } + pre.right = null; + if (parent.val > cur.val) { + if (first == null) first = parent; + second = cur; } - temp.right = null; - pre = p; - p = p.right; + parent = cur; + cur = cur.right; } } } - int temp = first.val; - first.val = second.val; - second.val = temp; + if (first != null && second != null) swap(first, second); + } + + + private void swap(TreeNode first, TreeNode second) { + int temp = second.val; + second.val = first.val; + first.val = temp; } } From 17836762c0c3527a911190087aa2df7b268ff317 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 5 Aug 2018 22:35:15 -0700 Subject: [PATCH 289/456] modify validate_bst --- .../ValidateBinarySearchTree.java | 30 +++++-------------- 1 file changed, 7 insertions(+), 23 deletions(-) diff --git a/src/main/java/validate_binary_search_tree/ValidateBinarySearchTree.java b/src/main/java/validate_binary_search_tree/ValidateBinarySearchTree.java index a041703..f95e977 100644 --- a/src/main/java/validate_binary_search_tree/ValidateBinarySearchTree.java +++ b/src/main/java/validate_binary_search_tree/ValidateBinarySearchTree.java @@ -5,31 +5,15 @@ public class ValidateBinarySearchTree { public class Solution { - private boolean isValidBST(TreeNode root, int[] minMax) { - int min = root.val; - int max = root.val; - if (root.left != null) { - if (!isValidBST(root.left, minMax) || root.val <= minMax[1]) { - return false; - } - min = minMax[0]; - } - if (root.right != null) { - if (!isValidBST(root.right, minMax) || root.val >= minMax[0]) { - return false; - } - max = minMax[1]; - } - minMax[0] = min; - minMax[1] = max; - return true; - } public boolean isValidBST(TreeNode root) { - if (root == null) { - return true; - } - return isValidBST(root, new int[2]); + return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + private boolean isValidBST(TreeNode root, long mn, long mx) { + if (root == null) return true; + if (root.val <= mn || root.val >= mx) return false; + return isValidBST(root.left, mn, root.val) && isValidBST(root.right, root.val, mx); } } From 79e3912777ab6768aa5adca2b3e3992a338577a8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 5 Aug 2018 23:31:27 -0700 Subject: [PATCH 290/456] interleaving_string --- .../InterleavingString.java | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/main/java/interleaving_string/InterleavingString.java b/src/main/java/interleaving_string/InterleavingString.java index 141648b..8b8d0fb 100644 --- a/src/main/java/interleaving_string/InterleavingString.java +++ b/src/main/java/interleaving_string/InterleavingString.java @@ -4,21 +4,26 @@ public class InterleavingString { public class Solution { public boolean isInterleave(String s1, String s2, String s3) { - if (s1.length() + s2.length() != s3.length()) { - return false; + if (s1.length() + s2.length() != s3.length()) return false; + int n1 = s1.length(); + int n2 = s2.length(); + boolean[][] dp = new boolean[n1+1][n2+1]; + dp[0][0] = true; + for (int i = 1; i <= n1; ++i) { + dp[i][0] = dp[i - 1][0] && (s1.charAt(i - 1) == s3.charAt(i - 1)); } - boolean[] dp = new boolean[s2.length() + 1]; - for (int i = 0; i <= s1.length(); i++) { - for (int j = 0; j <= s2.length(); j++) { - dp[j] = (i == 0 && j == 0) - || (i != 0 && dp[j] && s1.charAt(i - 1) == s3 - .charAt(i + j - 1)) - || (j != 0 && dp[j - 1] && s2.charAt(j - 1) == s3 - .charAt(i + j - 1)); + for (int i = 1; i <= n2; ++i) { + dp[0][i] = dp[0][i - 1] && (s2.charAt(i - 1) == s3.charAt(i - 1)); + } + for (int i = 1; i <= n1; ++i) { + for (int j = 1; j <= n2; ++j) { + dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i - 1 + j)) || + (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1 + i)); } } - return dp[s2.length()]; + return dp[n1][n2]; } + } public static class UnitTest { From ccb1d477dcbe1efe2bf50ee0faaceb4215dd4b44 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 6 Aug 2018 20:41:53 -0700 Subject: [PATCH 291/456] modify binary_tree_inorder_traversal --- .../BinaryTreeInorderTraversal.java | 32 ++++++++----------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/src/main/java/binary_tree_inorder_traversal/BinaryTreeInorderTraversal.java b/src/main/java/binary_tree_inorder_traversal/BinaryTreeInorderTraversal.java index 50e50ed..5c7cd24 100644 --- a/src/main/java/binary_tree_inorder_traversal/BinaryTreeInorderTraversal.java +++ b/src/main/java/binary_tree_inorder_traversal/BinaryTreeInorderTraversal.java @@ -1,35 +1,29 @@ package binary_tree_inorder_traversal; -import java.util.ArrayList; - import common.TreeNode; +import java.util.ArrayList; +import java.util.Stack; + public class BinaryTreeInorderTraversal { public class Solution { public ArrayList inorderTraversal(TreeNode root) { ArrayList ans = new ArrayList(); + Stack s = new Stack<>(); TreeNode p = root; - while (p != null) { - if (p.left == null) { - ans.add(p.val); - p = p.right; - } else { - TreeNode temp = p.left; - while (temp.right != null && temp.right != p) { - temp = temp.right; - } - if (temp.right == null) { - temp.right = p; - p = p.left; - } else { - ans.add(p.val); - temp.right = null; - p = p.right; - } + while (p != null || !s.empty()) { + while (p != null) { + s.push(p); + p = p.left; } + p = s.peek(); + s.pop(); + ans.add(p.val); + p = p.right; } return ans; + } } From 6cbb8b2d4396b0809b9253597c2c1bd7807c31a1 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 7 Aug 2018 00:31:33 -0700 Subject: [PATCH 292/456] modify restore_ip_address --- .../RestoreIPAddresses.java | 52 ++++++------------- 1 file changed, 15 insertions(+), 37 deletions(-) diff --git a/src/main/java/restore_ip_addresses/RestoreIPAddresses.java b/src/main/java/restore_ip_addresses/RestoreIPAddresses.java index 42b033b..6c6e8e3 100644 --- a/src/main/java/restore_ip_addresses/RestoreIPAddresses.java +++ b/src/main/java/restore_ip_addresses/RestoreIPAddresses.java @@ -1,53 +1,31 @@ package restore_ip_addresses; import java.util.ArrayList; +import java.util.List; public class RestoreIPAddresses { public class Solution { - private String toAddr(ArrayList solution) { - String addr = ""; - addr += solution.get(0); - addr += "."; - addr += solution.get(1); - addr += "."; - addr += solution.get(2); - addr += "."; - addr += solution.get(3); - return addr; + + public List restoreIpAddresses(String s) { + List res = new ArrayList<>(); + helper(s, 0, "", res); + return res; } - private void search(String s, int begin, ArrayList solution, - ArrayList solutions) { - if (begin == s.length() && solution.size() == 4) { - solutions.add(toAddr(solution)); - return; - } - if (s.length() - begin > (4 - solution.size()) * 3) { - return; - } - if (s.length() - begin < 4 - solution.size()) { - return; - } - int num = 0; - for (int i = begin; i < Math.min(begin + 3, s.length()); i++) { - num = num * 10 + s.charAt(i) - '0'; - if (num < 256) { - solution.add(num); - search(s, i + 1, solution, solutions); - solution.remove(solution.size() - 1); - } - if (num == 0) { - break; + private void helper(String s, int n, String out, List res) { + if (n == 4) { + if (s.isEmpty()) res.add(out); + } else { + for (int k = 1; k < 4; ++k) { + if (s.length() < k) break; + int val = Integer.parseInt(s.substring(0, k)); + if (val > 255 || k != Integer.toString(val).length()) continue; + helper(s.substring(k), n + 1, out + s.substring(0, k) + (n == 3 ? "" : "."), res); } } } - public ArrayList restoreIpAddresses(String s) { - ArrayList solutions = new ArrayList(); - search(s, 0, new ArrayList(), solutions); - return solutions; - } } public static class UnitTest { From cd779f2f7dc013873db891203cb17ec6a92d0c51 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 7 Aug 2018 22:01:08 -0700 Subject: [PATCH 293/456] modify subsets --- src/main/java/subsets/Subsets.java | 31 +++++++++++----------- src/main/java/subsets_ii/SubsetsII.java | 35 ++++++++++++------------- 2 files changed, 32 insertions(+), 34 deletions(-) diff --git a/src/main/java/subsets/Subsets.java b/src/main/java/subsets/Subsets.java index 9318484..e35a04e 100644 --- a/src/main/java/subsets/Subsets.java +++ b/src/main/java/subsets/Subsets.java @@ -2,27 +2,26 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.List; public class Subsets { public class Solution { - public ArrayList> subsets(int[] S) { - Arrays.sort(S); - ArrayList> subsets = new ArrayList>(); - for (int i = 0; i < 1 << S.length; i++) { - ArrayList subset = new ArrayList(); - int n = i; - int idx = 0; - while (n > 0) { - if ((n & 1) == 1) { - subset.add(S[idx]); - } - n >>= 1; - idx++; - } - subsets.add(subset); + public List> subsets(int[] nums) { + List> res = new ArrayList<>(); + List out = new ArrayList<>(); + Arrays.sort(nums); + getSubsets(nums, 0, out, res); + return res; + } + + private void getSubsets(int[] nums, int pos, List out, List> res) { + res.add(new ArrayList<>(out)); + for (int i = pos; i < nums.length; ++i) { + out.add(nums[i]); + getSubsets(nums, i + 1, out, res); + out.remove(out.size()-1); } - return subsets; } } diff --git a/src/main/java/subsets_ii/SubsetsII.java b/src/main/java/subsets_ii/SubsetsII.java index bc8e6d6..da542c5 100644 --- a/src/main/java/subsets_ii/SubsetsII.java +++ b/src/main/java/subsets_ii/SubsetsII.java @@ -2,29 +2,28 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.List; public class SubsetsII { public class Solution { - public ArrayList> subsetsWithDup(int[] num) { - Arrays.sort(num); - ArrayList> subsets = new ArrayList>(); - subsets.add(new ArrayList()); - int last = 1; - for (int i = 0; i < num.length; i++) { - int start = 0; - if (i != 0 && num[i] == num[i - 1]) { - start = last; - } - last = subsets.size(); - for (int j = start; j < last; j++) { - ArrayList subset = new ArrayList( - subsets.get(j)); - subset.add(num[i]); - subsets.add(subset); - } + + public List> subsetsWithDup(int[] nums) { + List> res = new ArrayList<>(); + List out = new ArrayList<>(); + Arrays.sort(nums); + getSubsets(nums, 0, out, res); + return res; + } + + private void getSubsets(int[] nums, int pos, List out, List> res) { + res.add(new ArrayList<>(out)); + for (int i = pos; i < nums.length; ++i) { + out.add(nums[i]); + getSubsets(nums, i + 1, out, res); + out.remove(out.size()-1); + while (i + 1 < nums.length && nums[i] == nums[i+1]) ++i; } - return subsets; } } From e8c185085847acf1da88ab54c37b768a50bfec7a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 8 Aug 2018 07:07:21 -0700 Subject: [PATCH 294/456] modify scrambling_string --- src/main/java/scramble_string/ScrambleString.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/scramble_string/ScrambleString.java b/src/main/java/scramble_string/ScrambleString.java index 8a33d8a..36a0e51 100644 --- a/src/main/java/scramble_string/ScrambleString.java +++ b/src/main/java/scramble_string/ScrambleString.java @@ -4,6 +4,7 @@ public class ScrambleString { public class Solution { public boolean isScramble(String s1, String s2) { + if (s1.length() != s2.length()) return false; if (s1.equals(s2)) { return true; } From e844b67a15a1711a9372b276c758b5e0ac43e10d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 8 Aug 2018 07:21:06 -0700 Subject: [PATCH 295/456] modify partition_list --- .../java/partition_list/PartitionList.java | 49 ++++++------------- 1 file changed, 16 insertions(+), 33 deletions(-) diff --git a/src/main/java/partition_list/PartitionList.java b/src/main/java/partition_list/PartitionList.java index ad7ab3d..6804117 100644 --- a/src/main/java/partition_list/PartitionList.java +++ b/src/main/java/partition_list/PartitionList.java @@ -5,42 +5,25 @@ public class PartitionList { public class Solution { - public ListNode partition(ListNode head, int x) { - ListNode lessHead = null; - ListNode lessTail = null; - ListNode greaterHead = null; - ListNode greaterTail = null; - ListNode p = head; - while (p != null) { - if (p.val < x) { - if (lessHead == null) { - lessHead = p; - } else { - lessTail.next = p; - } - lessTail = p; + ListNode partition(ListNode head, int x) { + if (head == null) return head; + ListNode dummy = new ListNode(-1); + ListNode newDummy = new ListNode(-1); + + dummy.next = head; + ListNode cur = dummy, p = newDummy; + while (cur.next != null) { + if (cur.next.val < x) { + p.next = cur.next; + p = p.next; + cur.next = cur.next.next; + p.next = null; } else { - if (greaterHead == null) { - greaterHead = p; - } else { - greaterTail.next = p; - } - greaterTail = p; - } - p = p.next; - } - if (lessHead == null) { - if (greaterTail != null) { - greaterTail.next = null; - } - return greaterHead; - } else { - lessTail.next = greaterHead; - if (greaterTail != null) { - greaterTail.next = null; + cur = cur.next; } - return lessHead; } + p.next = dummy.next; + return newDummy.next; } } From e8f8998beb2dc95230895f05a6d7aeb4a3256558 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 8 Aug 2018 16:23:03 -0700 Subject: [PATCH 296/456] modify maximal rectangle --- .../maximal_rectangle/MaximalRectangle.java | 64 +++++++++---------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/src/main/java/maximal_rectangle/MaximalRectangle.java b/src/main/java/maximal_rectangle/MaximalRectangle.java index 6b39bcd..062fcc4 100644 --- a/src/main/java/maximal_rectangle/MaximalRectangle.java +++ b/src/main/java/maximal_rectangle/MaximalRectangle.java @@ -1,49 +1,49 @@ package maximal_rectangle; -import java.util.ArrayDeque; +import java.util.Stack; public class MaximalRectangle { - public class Solution { - private int largestRectangleArea(int[] height) { - ArrayDeque p = new ArrayDeque(); - int i = 0; - int maxArea = 0; - while (i < height.length) { - if (p.isEmpty() || height[p.peekLast()] <= height[i]) { - p.offerLast(i++); - } else { - int pos = p.removeLast(); - maxArea = Math.max(maxArea, height[pos] - * (p.isEmpty() ? i : (i - p.peekLast() - 1))); + public static class Solution { + public int maximalRectangle(char[][] matrix) { + int res = 0; + int[] height = new int[matrix[0].length + 1]; + for (int i = 0; i < matrix.length; ++i) { + for (int j = 0; j < matrix[i].length; ++j) { + height[j] = matrix[i][j] == '0' ? 0 : (1 + height[j]); } + res = Math.max(res, largestRectangleArea(height)); // LC 84 } - return maxArea; + return res; } - public int maximalRectangle(char[][] matrix) { - if (matrix.length == 0 || matrix[0].length == 0) { - return 0; - } - int m = matrix.length; - int n = matrix[0].length; - int[] height = new int[n + 1]; - int maxArea = 0; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (matrix[i][j] == '1') { - height[j]++; - } else { - height[j] = 0; - } + // LC 84 + private int largestRectangleArea(int[] height) { + int res = 0; + Stack s = new Stack(); + height[height.length-1] = 0; + for (int i = 0; i < height.length; ++i) { + if (s.empty() || height[s.peek()] <= height[i]) s.push(i); + else { + int tmp = s.peek(); + s.pop(); + res = Math.max(res, height[tmp] * (s.empty() ? i : (i - s.peek() - 1))); + --i; } - maxArea = Math.max(maxArea, largestRectangleArea(height)); } - return maxArea; + return res; } } - public static class UnitTest { + public static void main(String[] args) { + Solution sol = new Solution(); + char[][] matrix = { + {'1', '0', '1', '0', '0'}, + {'1', '0', '1', '1', '1'}, + {'1', '1', '1', '1', '1'}, + {'1', '0', '0', '1', '0'} + }; + System.out.println(sol.maximalRectangle(matrix)); } } From 4d46dc30df9f0098ea62b365c6a598799d32b6cb Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 8 Aug 2018 19:26:17 -0700 Subject: [PATCH 297/456] modify largest_rectangle_area --- .../LargestRectangleinHistogram.java | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java b/src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java index 8fd774e..538c532 100644 --- a/src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java +++ b/src/main/java/largest_rectangle_in_histogram/LargestRectangleinHistogram.java @@ -1,32 +1,28 @@ package largest_rectangle_in_histogram; -import java.util.ArrayDeque; -import java.util.Deque; +import java.util.Arrays; +import java.util.List; +import java.util.Stack; +import java.util.stream.Collectors; public class LargestRectangleinHistogram { public class Solution { public int largestRectangleArea(int[] height) { - int maxArea = 0; - Deque p = new ArrayDeque(); - int i = 0; - while (i < height.length) { - if (p.isEmpty() || height[p.peekLast()] <= height[i]) { - p.offerLast(i++); + int res = 0; + List heights = Arrays.stream(height).boxed().collect(Collectors.toList());; + heights.add(0); + Stack st = new Stack<>(); + for (int i = 0; i < heights.size(); ++i) { + if (st.empty() || heights.get(st.peek()) < heights.get(i)) { + st.push(i); } else { - int pos = p.removeLast(); - maxArea = Math.max(maxArea, - (p.isEmpty() ? i : i - p.peekLast() - 1) - * height[pos]); + int cur = st.peek(); st.pop(); + res = Math.max(res, heights.get(cur) * (st.empty() ? i : (i - st.peek() - 1))); + --i; } } - while (!p.isEmpty()) { - int pos = p.removeLast(); - maxArea = Math.max(maxArea, (p.isEmpty() ? i : i - p.peekLast() - - 1) - * height[pos]); - } - return maxArea; + return res; } } From 3e9178a42b042cdd5cb472e563a2c69d77362a71 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 8 Aug 2018 20:53:28 -0700 Subject: [PATCH 298/456] modify remove_duplicates_sorted_list_ii --- .../RemoveDuplicatesfromSortedListII.java | 45 +++++-------------- 1 file changed, 12 insertions(+), 33 deletions(-) diff --git a/src/main/java/remove_duplicates_from_sorted_list_ii/RemoveDuplicatesfromSortedListII.java b/src/main/java/remove_duplicates_from_sorted_list_ii/RemoveDuplicatesfromSortedListII.java index e524ac4..e3050ef 100644 --- a/src/main/java/remove_duplicates_from_sorted_list_ii/RemoveDuplicatesfromSortedListII.java +++ b/src/main/java/remove_duplicates_from_sorted_list_ii/RemoveDuplicatesfromSortedListII.java @@ -6,41 +6,20 @@ public class RemoveDuplicatesfromSortedListII { public class Solution { public ListNode deleteDuplicates(ListNode head) { - if (head == null) { - return null; - } - ListNode pre = null; - int count = 1; - ListNode p = head; - while (p.next != null) { - if (p.next.val == p.val) { - count++; - } else if (count == 1) { - if (pre == null) { - head = p; - } - pre = p; - } else { - if (pre != null) { - pre.next = p.next; - } - count = 1; - } - p = p.next; - } - if (count == 1) { - if (pre == null) { - return p; - } else { - return head; - } - } - if (pre == null) { - return null; + if (head == null || head.next == null) return head; + + ListNode start = new ListNode(0); + start.next = head; + ListNode pre = start; + while (pre.next != null) { + ListNode cur = pre.next; + while (cur.next != null && cur.next.val == cur.val) cur = cur.next; + if (cur != pre.next) pre.next = cur.next; // need to delete nodes + else pre = pre.next; } - pre.next = null; - return head; + return start.next; } + } public static class UnitTest { From 51aebdbacef0817c0639a64e60ef22e5784b1f0c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 9 Aug 2018 14:27:51 -0700 Subject: [PATCH 299/456] modify combinations --- src/main/java/combinations/Combinations.java | 31 ++++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/src/main/java/combinations/Combinations.java b/src/main/java/combinations/Combinations.java index 4839652..c264f62 100644 --- a/src/main/java/combinations/Combinations.java +++ b/src/main/java/combinations/Combinations.java @@ -1,31 +1,30 @@ package combinations; -import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.List; public class Combinations { public class Solution { - private void search(int start, int end, int k, - ArrayDeque queue, ArrayList> ans) { - if (k == 0) { - ans.add(new ArrayList(queue)); - return; - } + public List> combine(int n, int k) { + List > res = new ArrayList<>(); + List out = new ArrayList<>(); + combineDFS(n, k, 1, out, res); + return res; + } - for (int i = start; i <= end - k + 1; i++) { - queue.offerLast(i); - search(i + 1, end, k - 1, queue, ans); - queue.removeLast(); + private void combineDFS(int n, int k, int level, List out, List > res) { + if (out.size() == k) res.add(new ArrayList<>(out)); + else { + for (int i = level; i <= n; ++i) { + out.add(i); + combineDFS(n, k, i + 1, out, res); + out.remove(out.size()-1); + } } } - public ArrayList> combine(int n, int k) { - ArrayList> ans = new ArrayList>(); - search(1, n, k, new ArrayDeque(), ans); - return ans; - } } public static class UnitTest { From 5d92c416da895e8d0a4d87dab1376fc693bf2c3d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 9 Aug 2018 18:40:13 -0700 Subject: [PATCH 300/456] modify minimum window substring --- .../MinimumWindowSubstring.java | 70 +++++++------------ 1 file changed, 24 insertions(+), 46 deletions(-) diff --git a/src/main/java/minimum_window_substring/MinimumWindowSubstring.java b/src/main/java/minimum_window_substring/MinimumWindowSubstring.java index 0711b9b..6de9004 100644 --- a/src/main/java/minimum_window_substring/MinimumWindowSubstring.java +++ b/src/main/java/minimum_window_substring/MinimumWindowSubstring.java @@ -4,57 +4,35 @@ public class MinimumWindowSubstring { public class Solution { public String minWindow(String S, String T) { - int[] tCount = new int[256]; - for (int i = 0; i < T.length(); i++) { - tCount[T.charAt(i)]++; - } - int[] sCount = new int[256]; - int i = 0; - for (; i < S.length(); i++) { - sCount[S.charAt(i)]++; - boolean find = true; - for (int j = 0; j < 256; j++) { - if (sCount[j] < tCount[j]) { - find = false; - break; - } - } - if (find) { - break; - } - } - if (i == S.length()) { - return ""; - } - int windowStart = 0; - int windowEnd = i; - int minWindowStart = windowStart; - int minWindowEnd = windowEnd; - while (windowStart < S.length()) { - char c = S.charAt(windowStart); - sCount[c]--; - windowStart++; - if (sCount[c] < tCount[c]) { - windowEnd++; - while (windowEnd < S.length()) { - char endC = S.charAt(windowEnd); - sCount[endC]++; - if (c == endC) { - break; - } - windowEnd++; + int[] need = new int[256]; + for(int i = 0; i < T.length(); i++) + need[T.charAt(i)]++; + int[] found = new int[256]; + + int count = 0; + int minLen = S.length()+1; + int minBegin = 0; + for(int begin = 0, end = 0; end < S.length(); ++end){ + char ch = S.charAt(end); + if(need[ch] == 0) continue; + if(++found[ch] <= need[ch]) count++; + if(count == T.length()){ + while(need[S.charAt(begin)] == 0 || + found[S.charAt(begin)] > need[S.charAt(begin)]){ + if(found[S.charAt(begin)] > need[S.charAt(begin)]) + found[S.charAt(begin)]--; + begin++; } - if (windowEnd == S.length()) { - break; + int leng = end - begin + 1; + if(leng < minLen){ + minLen = leng; + minBegin = begin; } } - if (windowEnd - windowStart < minWindowEnd - minWindowStart) { - minWindowStart = windowStart; - minWindowEnd = windowEnd; - } } - return S.substring(minWindowStart, minWindowEnd + 1); + return minLen > S.length()?"":S.substring(minBegin,minBegin+minLen); } + } public static class UnitTest { From 1311ce3bb9d5adfd0810d09b69b19dcb2d6853c5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 9 Aug 2018 22:28:21 -0700 Subject: [PATCH 301/456] modify edit_distance --- src/main/java/edit_distance/EditDistance.java | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/src/main/java/edit_distance/EditDistance.java b/src/main/java/edit_distance/EditDistance.java index c860709..e060e1c 100644 --- a/src/main/java/edit_distance/EditDistance.java +++ b/src/main/java/edit_distance/EditDistance.java @@ -4,23 +4,20 @@ public class EditDistance { public class Solution { public int minDistance(String word1, String word2) { - assert word1 != null && word2 != null; - int[][] dp = new int[word1.length() + 1][word2.length() + 1]; - for (int i = 0; i <= word2.length(); i++) { - dp[0][i] = i; - } - for (int i = 1; i <= word1.length(); i++) { - dp[i][0] = i; - for (int j = 1; j <= word2.length(); j++) { - dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1; - if (word1.charAt(i - 1) == word2.charAt(j - 1)) { - dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]); + int n1 = word1.length(), n2 = word2.length(); + int[][] dp = new int[n1 + 1][n2 + 1]; + for (int i = 0; i <= n1; ++i) dp[i][0] = i; + for (int i = 0; i <= n2; ++i) dp[0][i] = i; + for (int i = 1; i <= n1; ++i) { + for (int j = 1; j <= n2; ++j) { + if (word1.charAt(i-1) == word2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; } else { - dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + 1); + dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; } } } - return dp[word1.length()][word2.length()]; + return dp[n1][n2]; } } From 2ca56cf93faff40e4cef6a682e4cf7251c7288c2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 10 Aug 2018 07:29:39 -0700 Subject: [PATCH 302/456] modify simplify_path --- src/main/java/simplify_path/SimplifyPath.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/simplify_path/SimplifyPath.java b/src/main/java/simplify_path/SimplifyPath.java index 814f675..886c522 100644 --- a/src/main/java/simplify_path/SimplifyPath.java +++ b/src/main/java/simplify_path/SimplifyPath.java @@ -8,16 +8,16 @@ public class Solution { public String simplifyPath(String path) { String[] splits = path.split("/"); ArrayDeque stack = new ArrayDeque(); - for (String split : splits) { - if (!split.isEmpty()) { - if (split.equals("..")) { + for (String s : splits) { + if (!s.isEmpty()) { + if (s.equals("..")) { if (!stack.isEmpty()) { stack.removeLast(); } - } else if (split.equals(".")) { + } else if (s.equals(".")) { continue; } else { - stack.offerLast(split); + stack.offerLast(s); } } } From 216d941a9fcfc73ce0c5115e2e0e9e4135ec1866 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 10 Aug 2018 08:03:36 -0700 Subject: [PATCH 303/456] modify multiple files. --- .../java/climbing_stairs/ClimbingStairs.java | 14 +++++++------- src/main/java/sqrt_x/SqrtX.java | 16 +++++++++++----- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/main/java/climbing_stairs/ClimbingStairs.java b/src/main/java/climbing_stairs/ClimbingStairs.java index cd60f35..d32efe1 100644 --- a/src/main/java/climbing_stairs/ClimbingStairs.java +++ b/src/main/java/climbing_stairs/ClimbingStairs.java @@ -4,15 +4,15 @@ public class ClimbingStairs { public class Solution { public int climbStairs(int n) { - int f1 = 1; - int f2 = 1; - for (int i = 2; i <= n; i++) { - int temp = f1 + f2; - f1 = f2; - f2 = temp; + if (n <= 1) return 1; + int[] dp = new int[n]; + dp[0] = 1; dp[1] = 2; + for (int i = 2; i < n; ++i) { + dp[i] = dp[i - 1] + dp[i - 2]; } - return f2; + return dp[n-1]; } + } public static class UnitTest { diff --git a/src/main/java/sqrt_x/SqrtX.java b/src/main/java/sqrt_x/SqrtX.java index 340fdda..74ebfd9 100644 --- a/src/main/java/sqrt_x/SqrtX.java +++ b/src/main/java/sqrt_x/SqrtX.java @@ -3,13 +3,19 @@ public class SqrtX { public class Solution { - public int sqrt(int a) { - double x = 1.0; - while (Math.abs(x * x - a) > 10E-6) { - x = (x + a / x) / 2; + + public int SqrtX(int x) { + long left = 0, right = (x / 2) + 1; + while (left <= right) { + long mid = (left + right) / 2; + long sq = mid * mid; + if (sq == x) return (int) mid; + else if (sq < x) left = mid + 1; + else right = mid - 1; } - return (int) x; + return (int) right; } + } public static class UnitTest { From 550ab4e8a55e8848a50bd1b077e6fea2b19f0ea3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 10 Aug 2018 20:12:35 -0700 Subject: [PATCH 304/456] modify min_path_sum --- .../java/minimum_path_sum/MinimumPathSum.java | 17 +++++++++-------- src/main/java/sqrt_x/SqrtX.java | 2 +- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main/java/minimum_path_sum/MinimumPathSum.java b/src/main/java/minimum_path_sum/MinimumPathSum.java index f82d1b0..e8a61dc 100644 --- a/src/main/java/minimum_path_sum/MinimumPathSum.java +++ b/src/main/java/minimum_path_sum/MinimumPathSum.java @@ -4,16 +4,17 @@ public class MinimumPathSum { public class Solution { public int minPathSum(int[][] grid) { - assert grid != null && grid.length != 0 && grid[0].length != 0; - int[] dp = new int[grid[0].length]; - for (int i = 0; i < grid.length; i++) { - dp[0] = i == 0 ? grid[0][0] : dp[0] + grid[i][0]; - for (int j = 1; j < grid[0].length; j++) { - dp[j] = i == 0 ? dp[j - 1] : Math.min(dp[j], dp[j - 1]); - dp[j] += grid[i][j]; + int m = grid.length, n = grid[0].length; + int[][] dp = new int[m][n]; + dp[0][0] = grid[0][0]; + for (int i = 1; i < m; ++i) dp[i][0] = grid[i][0] + dp[i - 1][0]; + for (int i = 1; i < n; ++i) dp[0][i] = grid[0][i] + dp[0][i - 1]; + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]); } } - return dp[grid[0].length - 1]; + return dp[m - 1][n - 1]; } } diff --git a/src/main/java/sqrt_x/SqrtX.java b/src/main/java/sqrt_x/SqrtX.java index 74ebfd9..82accb1 100644 --- a/src/main/java/sqrt_x/SqrtX.java +++ b/src/main/java/sqrt_x/SqrtX.java @@ -5,7 +5,7 @@ public class SqrtX { public class Solution { public int SqrtX(int x) { - long left = 0, right = (x / 2) + 1; + long left = 0, right = (x / 2) + 1; while (left <= right) { long mid = (left + right) / 2; long sq = mid * mid; From 28310976ca1dc1a63fc6cd7b9fced86bb2296a46 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 10 Aug 2018 22:39:08 -0700 Subject: [PATCH 305/456] modify unique_paths_with_obstacle --- src/main/java/unique_paths_ii/UniquePathsII.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/unique_paths_ii/UniquePathsII.java b/src/main/java/unique_paths_ii/UniquePathsII.java index af0f200..8bde61d 100644 --- a/src/main/java/unique_paths_ii/UniquePathsII.java +++ b/src/main/java/unique_paths_ii/UniquePathsII.java @@ -4,18 +4,20 @@ public class UniquePathsII { public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { - int m = obstacleGrid.length; - int n = obstacleGrid[0].length; + if (obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; + int m = obstacleGrid.length, n = obstacleGrid[0].length; + if (obstacleGrid[0][0] == 1) return 0; int[] dp = new int[n]; - dp[0] = obstacleGrid[0][0] == 1 ? 0 : 1; - for (int i = 0; i < m; i++) { - dp[0] = obstacleGrid[i][0] == 1 ? 0 : dp[0]; - for (int j = 1; j < n; j++) { - dp[j] = obstacleGrid[i][j] == 1 ? 0 : dp[j - 1] + dp[j]; + dp[0] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (obstacleGrid[i][j] == 1) dp[j] = 0; + else if (j > 0) dp[j] += dp[j - 1]; //rolling array } } return dp[n - 1]; } + } public static class UnitTest { From 791455d0844f9fc06aeb4968f8e4adfab4b9cc33 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 11 Aug 2018 00:33:03 -0700 Subject: [PATCH 306/456] modify rotate_list --- src/main/java/rotate_list/RotateList.java | 54 +++++++++-------------- 1 file changed, 22 insertions(+), 32 deletions(-) diff --git a/src/main/java/rotate_list/RotateList.java b/src/main/java/rotate_list/RotateList.java index 13d433a..095b3c7 100644 --- a/src/main/java/rotate_list/RotateList.java +++ b/src/main/java/rotate_list/RotateList.java @@ -5,43 +5,33 @@ public class RotateList { public class Solution { - public ListNode rotateRight(ListNode head, int n) { - if (head == null) { - return head; + public ListNode rotateRight(ListNode head, int k) { + if (head == null) return null; + int n = 0; + ListNode cur = head; + while (cur != null) { + ++n; + cur = cur.next; } - int k = n; - int listSize = 0; - ListNode end = head; - while (k > 0) { - end = end.next; - k--; - listSize++; - if (end == null) { - k = n % listSize; - end = head; - while (k > 0) { - end = end.next; - k--; - } - break; - } + k %= n; + ListNode fast = head, slow = head; + for (int i = 0; i < k; ++i) { + if (fast != null) fast = fast.next; } - if (head == end) { - return head; + if (fast == null) return head; + while (fast.next != null) { + fast = fast.next; + slow = slow.next; } - ListNode start = head; - while (end.next != null) { - end = end.next; - start = start.next; - } - end.next = head; - head = start.next; - start.next = null; - return head; + fast.next = head; + fast = slow.next; + slow.next = null; + return fast; } - } - public static class UnitTest { + public class UnitTest { + + } } } From 3173192c4b9b579330529f57c6075250a9e1e72f Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 11 Aug 2018 23:40:04 -0700 Subject: [PATCH 307/456] modify n-queens --- .../java/merge_intervals/MergeIntervals.java | 27 +++----- src/main/java/n_queens/NQueens.java | 69 ++++++++----------- 2 files changed, 41 insertions(+), 55 deletions(-) diff --git a/src/main/java/merge_intervals/MergeIntervals.java b/src/main/java/merge_intervals/MergeIntervals.java index a6f8a36..0ef9549 100644 --- a/src/main/java/merge_intervals/MergeIntervals.java +++ b/src/main/java/merge_intervals/MergeIntervals.java @@ -1,15 +1,17 @@ package merge_intervals; +import common.Interval; + import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; -import common.Interval; - public class MergeIntervals { public class Solution { public ArrayList merge(ArrayList intervals) { + ArrayList ans = new ArrayList(); + if (intervals.isEmpty()) return ans; Collections.sort(intervals, new Comparator() { @Override @@ -22,24 +24,17 @@ public int compare(Interval i1, Interval i2) { }); - ArrayList ans = new ArrayList(); - Interval newInterval = null; - for (Interval i : intervals) { - if (newInterval == null) { - newInterval = new Interval(i.start, i.end); + ans.add(intervals.get(0)); + for (int i = 1; i < intervals.size(); ++i) { + if (ans.get(ans.size()-1).end >= intervals.get(i).start) { + ans.get(ans.size()-1).end = Math.max(ans.get(ans.size()-1).end, + intervals.get(i).end); } else { - if (newInterval.end < i.start) { - ans.add(newInterval); - newInterval = new Interval(i.start, i.end); - } else { - newInterval.end = Math.max(newInterval.end, i.end); - } + ans.add(new Interval(intervals.get(i).start, intervals.get(i).end)); } } - if (newInterval != null) { - ans.add(newInterval); - } return ans; + } } diff --git a/src/main/java/n_queens/NQueens.java b/src/main/java/n_queens/NQueens.java index cf99703..572a9d2 100644 --- a/src/main/java/n_queens/NQueens.java +++ b/src/main/java/n_queens/NQueens.java @@ -1,60 +1,51 @@ package n_queens; -import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; public class NQueens { public class Solution { - private boolean isValid(int row, int column, ArrayDeque columns) { - int r = 0; - for (int c : columns) { - if (c == column || Math.abs(c - column) == Math.abs(r - row)) { - return false; - } - r++; - } - return true; + public List> solveNQueens(int n) { + List > res = new ArrayList<>(); + int[] pos = new int[n]; + for(int i = 0; i < n; ++i) pos[i] = -1; + solveNQueensDFS(pos, 0, res); + return res; } - private String[] toSolution(ArrayDeque columns) { - int n = columns.size(); - String[] s = new String[n]; - int row = 0; - for (int column : columns) { - String line = ""; - for (int i = 0; i < n; i++) { - if (i != column) { - line += '.'; - } else { - line += 'Q'; + private void solveNQueensDFS(int[] pos, int row, List > res) { + int n = pos.length; + if (row == n) { + List out = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + char[] s = new char[n]; + Arrays.fill(s, '.'); + s[pos[i]] = 'Q'; + out.add(new String(s)); + } + res.add(new ArrayList<>(out)); + } else { + for (int col = 0; col < n; ++col) { + if (isValid(pos, row ,col)) { + pos[row] = col; + solveNQueensDFS(pos, row + 1, res); + pos[row] = -1; // back-tracking } } - s[row++] = line; } - return s; } - private void search(int row, int n, ArrayDeque columns, - ArrayList ans) { - if (row == n) { - ans.add(toSolution(columns)); - return; - } - for (int i = 0; i < n; i++) { - if (isValid(row, i, columns)) { - columns.offerLast(i); - search(row + 1, n, columns, ans); - columns.removeLast(); + private boolean isValid(int[] pos, int row, int col) { + for (int i = 0; i < row; ++i) { + if (col == pos[i] || Math.abs(row - i) == Math.abs(col - pos[i])) { + return false; } } + return true; } - public ArrayList solveNQueens(int n) { - ArrayList ans = new ArrayList(); - search(0, n, new ArrayDeque(), ans); - return ans; - } } public static class UnitTest { From 3c0c83949145496942f30c312096545fb3f5e918 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 11 Aug 2018 23:49:56 -0700 Subject: [PATCH 308/456] pow(x,n) --- src/main/java/pow_x_n/Powxn.java | 33 +++++++++++--------------------- 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/src/main/java/pow_x_n/Powxn.java b/src/main/java/pow_x_n/Powxn.java index 9392856..5a48815 100644 --- a/src/main/java/pow_x_n/Powxn.java +++ b/src/main/java/pow_x_n/Powxn.java @@ -3,29 +3,18 @@ public class Powxn { public class Solution { - public double pow(double x, int n) { - boolean overflow = false; - if (n == Integer.MIN_VALUE) { - overflow = true; - n++; - } - boolean negative = n < 0; - n = Math.abs(n); - double re = 1; - double times = x; - while (n != 0) { - if ((n & 1) == 1) { - re *= times; - } - times *= times; - n >>= 1; - } - if (negative) { - return overflow ? 1 / (re * x) : 1 / re; - } else { - return re; - } + public double myPow(double x, int n) { + if (n < 0) return 1 / power(x, -n); + return power(x, n); } + + private double power(double x, int n) { + if (n == 0) return 1; + double half = power(x, n / 2); + if (n % 2 == 0) return half * half; + return x * half * half; + } + } public static class UnitTest { From ea89af46faec8e21c78deac8c32e4e63eee17fe6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 12 Aug 2018 14:38:37 -0700 Subject: [PATCH 309/456] modify trapping rain water --- .../TrappingRainWater.java | 39 +++++++------------ 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/src/main/java/trapping_rain_water/TrappingRainWater.java b/src/main/java/trapping_rain_water/TrappingRainWater.java index 922c95e..3ca7e78 100644 --- a/src/main/java/trapping_rain_water/TrappingRainWater.java +++ b/src/main/java/trapping_rain_water/TrappingRainWater.java @@ -3,34 +3,21 @@ public class TrappingRainWater { public class Solution { - public int trap(int[] A) { - if (A.length == 0) { - return 0; + public int trap(int[] height) { + int res = 0, mx = 0, n = height.length; + int[] dp = new int[n]; + for (int i = 0; i < n; ++i) { + dp[i] = mx; + mx = Math.max(mx, height[i]); } - int maxIndex = 0; - for (int i = 1; i < A.length; i++) { - if (A[i] > A[maxIndex]) { - maxIndex = i; - } + mx = 0; + for (int i = n - 1; i >= 0; --i) { + dp[i] = Math.min(dp[i], mx); + mx = Math.max(mx, height[i]); + if (dp[i] > height[i]) res += dp[i] - height[i]; } - int height = A[0]; - int water = 0; - for (int i = 1; i < maxIndex; i++) { - if (A[i] > height) { - height = A[i]; - } else { - water += height - A[i]; - } - } - height = A[A.length - 1]; - for (int i = A.length - 2; i > maxIndex; i--) { - if (A[i] > height) { - height = A[i]; - } else { - water += height - A[i]; - } - } - return water; + return res; + } } From bf734eda940e1dbaca61aee87e72ba2522a266be Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 12 Aug 2018 15:11:55 -0700 Subject: [PATCH 310/456] modify multiply_string --- .../multiply_strings/MultiplyStrings.java | 89 ++++--------------- 1 file changed, 16 insertions(+), 73 deletions(-) diff --git a/src/main/java/multiply_strings/MultiplyStrings.java b/src/main/java/multiply_strings/MultiplyStrings.java index 07bab2a..b4c9c50 100644 --- a/src/main/java/multiply_strings/MultiplyStrings.java +++ b/src/main/java/multiply_strings/MultiplyStrings.java @@ -1,87 +1,30 @@ package multiply_strings; -import java.util.ArrayList; -import java.util.List; +import java.util.Arrays; public class MultiplyStrings { public class Solution { - private List multiply(List l1, List l2) { - List result = new ArrayList(); - for (int offset = 0; offset < l2.size(); offset++) { - if (l2.get(offset) != 0) { - List temp = multiplyDigit(l1, l2.get(offset)); - result = add(temp, result, offset); - } - } - return result; - } - - private List add(List l1, List l2, int offset) { - List result = new ArrayList(); - int index = 0; - while (index < offset) { - if (index < l2.size()) { - result.add(l2.get(index)); - } else { - result.add(0); - } - index++; - } - int carry = 0; - for (int i : l1) { - int value = i + carry + (index < l2.size() ? l2.get(index) : 0); - result.add(value % 10); - carry = value / 10; - index++; - } - if (carry != 0) { - result.add(carry); - } - return result; - } - - private List toList(String s) { - List result = new ArrayList(); - for (int i = s.length() - 1; i >= 0; i--) { - result.add(s.charAt(i) - '0'); - } - return result; - } - - private String toString(List l) { - StringBuilder builder = new StringBuilder(); - int i = l.size() - 1; - for (; i >= 0; i--) { - if (l.get(i) != 0) { - break; + public String multiply(String num1, String num2) { + if (num1.charAt(0) == '0' || num2.charAt(0) == '0') return "0"; + int n1 = num1.length(), n2 = num2.length(), n = (n1 + n2); + int[] r = new int[n]; + char[] s = new char[n]; + Arrays.fill(s, '0'); + + for (int i = 0; i < n1; ++i) { + for (int j = 0; j < n2; ++j) { + r[i + j + 1] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); } } - for (; i >= 0; i--) { - builder.append(l.get(i)); - } - if (builder.length() == 0) { - return "0"; - } - return builder.toString(); - } - private List multiplyDigit(List l, int digit) { - List result = new ArrayList(); - int carry = 0; - for (int i : l) { - result.add((i * digit + carry) % 10); - carry = (i * digit + carry) / 10; - } - if (carry != 0) { - result.add(carry); + for (int i = n - 1; i > 0; --i) { + if (r[i] > 9) r[i - 1] += r[i] / 10; + s[i] += r[i] % 10; } - return result; - } - - public String multiply(String num1, String num2) { - return toString(multiply(toList(num1), toList(num2))); + s[0] += r[0]; + return s[0] == '0' ? new String(s).substring(1) : new String(s); } } From 524cbc00322f4bdbfec252aa80ae14df5dc728d5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 12 Aug 2018 15:30:03 -0700 Subject: [PATCH 311/456] modify permutation_ii --- .../java/permutations_ii/PermutationsII.java | 60 ++++++------------- 1 file changed, 18 insertions(+), 42 deletions(-) diff --git a/src/main/java/permutations_ii/PermutationsII.java b/src/main/java/permutations_ii/PermutationsII.java index 2ddcff0..0bf67da 100644 --- a/src/main/java/permutations_ii/PermutationsII.java +++ b/src/main/java/permutations_ii/PermutationsII.java @@ -1,58 +1,34 @@ package permutations_ii; -import java.util.ArrayList; -import java.util.Arrays; +import java.util.*; +import java.util.stream.Collectors; public class PermutationsII { public class Solution { - private void swap(int[] num, int i, int j) { - int temp = num[i]; - num[i] = num[j]; - num[j] = temp; + public List> permuteUnique(int[] nums) { + Set> res = new HashSet<>(); + permute(nums, 0, res); + return new ArrayList<>(res); } - private void reverse(int[] num, int begin, int end) { - end--; - while (begin < end) { - swap(num, begin++, end--); + private void permute(int[] nums, int start, Set> res) { + if (start >= nums.length) + res.add(Arrays.stream(nums).boxed().collect(Collectors.toList())); + for (int i = start; i < nums.length; ++i) { + if (i != start && nums[i] == nums[start]) continue; + swap(nums, i, start); + permute(nums, start + 1, res); + swap(nums, i, start); } } - private boolean nextPermutation(int[] num) { - if (num.length <= 1) { - return false; - } - int i = num.length - 1; - while (true) { - i--; - if (num[i] < num[i + 1]) { - int j = num.length; - while (num[i] >= num[--j]) { - } - swap(num, i, j); - reverse(num, i + 1, num.length); - return true; - } - if (i == 0) { - reverse(num, 0, num.length); - return false; - } - } + private void swap(int[] num, int i, int j) { + int temp = num[i]; + num[i] = num[j]; + num[j] = temp; } - public ArrayList> permuteUnique(int[] num) { - Arrays.sort(num); - ArrayList> ans = new ArrayList>(); - do { - ArrayList l = new ArrayList(); - for (int n : num) { - l.add(n); - } - ans.add(l); - } while (nextPermutation(num)); - return ans; - } } public static class UnitTest { From 455c20559b69c947e4d13b850b2d8f97eabad9eb Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 13 Aug 2018 00:08:54 -0700 Subject: [PATCH 312/456] modify first_missing_positive --- .../FirstMissingPositive.java | 36 +++++++++---------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/main/java/first_missing_positive/FirstMissingPositive.java b/src/main/java/first_missing_positive/FirstMissingPositive.java index a678dba..771a4ac 100644 --- a/src/main/java/first_missing_positive/FirstMissingPositive.java +++ b/src/main/java/first_missing_positive/FirstMissingPositive.java @@ -2,30 +2,26 @@ public class FirstMissingPositive { - public class Solution { - public int firstMissingPositive(int[] A) { - int n = A.length; - for (int i = 0; i < n; i++) { - if (A[i] <= 0) { - A[i] = n + 1; - } + public int firstMissingPositive(int[] nums) { + int n = nums.length; + for (int i = 0; i < n; ++i) { + while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) { + int tmp = nums[i]; + nums[i] = nums[nums[i] - 1]; + nums[tmp - 1] = tmp; } - for (int i = 0; i < n; i++) { - int temp = Math.abs(A[i]); - if (temp <= n && A[temp - 1] > 0) { - A[temp - 1] = -A[temp - 1]; - } - } - for (int i = 0; i < n; i++) { - if (A[i] > 0) { - return i + 1; - } - } - return n + 1; } + for (int i = 0; i < n; ++i) { + if (nums[i] != i + 1) return i + 1; + } + return n + 1; } - public static class UnitTest { + public static void main(String[] args) { + FirstMissingPositive f =new FirstMissingPositive(); + int[] a = {3,4,-1,1}; + System.out.println(f.firstMissingPositive(a)); + } } From 6cc40c20ad56a95901cc567cbf5022b87b1a492a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 13 Aug 2018 00:21:25 -0700 Subject: [PATCH 313/456] modify combination_sum_ii --- .../combination_sum_ii/CombinationSumII.java | 58 +++++-------------- 1 file changed, 16 insertions(+), 42 deletions(-) diff --git a/src/main/java/combination_sum_ii/CombinationSumII.java b/src/main/java/combination_sum_ii/CombinationSumII.java index 12edcdb..5cdffb9 100644 --- a/src/main/java/combination_sum_ii/CombinationSumII.java +++ b/src/main/java/combination_sum_ii/CombinationSumII.java @@ -1,6 +1,5 @@ package combination_sum_ii; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -8,52 +7,27 @@ public class CombinationSumII { public class Solution { - private void search(List nums, List counts, - int index, int target, ArrayDeque s, - ArrayList> ans) { - if (target == 0) { - ans.add(new ArrayList(s)); - } - if (target <= 0 || index == nums.size()) { - return; - } - int n = nums.get(index); - int count = counts.get(index); - for (int i = 0; i <= count; i++) { - search(nums, counts, index + 1, target - i * n, s, ans); - s.offerLast(n); - } - for (int i = 0; i <= count; i++) { - s.removeLast(); - } + public List> combinationSum2(int[] num, int target) { + List> res = new ArrayList<>(); + List out = new ArrayList<>(); + Arrays.sort(num); + combinationSum2DFS(num, target, 0, out, res); + return res; } - public ArrayList> combinationSum2(int[] num, - int target) { - ArrayList> ans = new ArrayList>(); - if (num.length == 0) { - return ans; - } - Arrays.sort(num); - List nums = new ArrayList(); - List counts = new ArrayList(); - int count = 1; - int i = 1; - for (; i < num.length; i++) { - if (num[i] != num[i - 1]) { - nums.add(num[i - 1]); - counts.add(count); - count = 1; - } else { - count++; + private void combinationSum2DFS(int[] num, int target, int start, List out, List> res) { + if (target < 0) return; + else if (target == 0) res.add(new ArrayList<>(out)); + else { + for (int i = start; i < num.length; ++i) { + if (i > start && num[i] == num[i - 1]) continue; + out.add(num[i]); + combinationSum2DFS(num, target - num[i], i + 1, out, res); // no duplicate + out.remove(out.size()-1); } - } - nums.add(num[i - 1]); - counts.add(count); - search(nums, counts, 0, target, new ArrayDeque(), ans); - return ans; } + } public static class UnitTest { From 103fff6b50c6132b71c5c131bab3022a6928dde6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 13 Aug 2018 00:23:07 -0700 Subject: [PATCH 314/456] modify combination_sum --- .../java/combination_sum/CombinationSum.java | 42 ++++++++----------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/main/java/combination_sum/CombinationSum.java b/src/main/java/combination_sum/CombinationSum.java index 98fcbc4..a907154 100644 --- a/src/main/java/combination_sum/CombinationSum.java +++ b/src/main/java/combination_sum/CombinationSum.java @@ -1,37 +1,31 @@ package combination_sum; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; +import java.util.List; public class CombinationSum { public class Solution { - private void search(int[] n, int index, int target, - ArrayDeque s, ArrayList> ans) { - if (target == 0) { - ans.add(new ArrayList(s)); - return; - } - if (index == n.length || target < n[index]) { - return; - } - - for (int i = 0; i <= target / n[index]; i++) { - search(n, index + 1, target - i * n[index], s, ans); - s.offerLast(n[index]); - } - for (int i = 0; i <= target / n[index]; i++) { - s.removeLast(); - } + public List> combinationSum(int[] num, int target) { + List> res = new ArrayList<>(); + List out = new ArrayList<>(); + Arrays.sort(num); + combinationSum2DFS(num, target, 0, out, res); + return res; } - public ArrayList> combinationSum(int[] candidates, - int target) { - ArrayList> ans = new ArrayList>(); - Arrays.sort(candidates); - search(candidates, 0, target, new ArrayDeque(), ans); - return ans; + private void combinationSum2DFS(int[] num, int target, int start, List out, List> res) { + if (target < 0) return; + else if (target == 0) res.add(new ArrayList<>(out)); + else { + for (int i = start; i < num.length; ++i) { + if (i > start && num[i] == num[i - 1]) continue; + out.add(num[i]); + combinationSum2DFS(num, target - num[i], i, out, res); // allows duplicate + out.remove(out.size()-1); + } + } } } From 493cac088a033b8a347ae0d4662efff3590ea022 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 13 Aug 2018 09:41:47 -0700 Subject: [PATCH 315/456] modify generate_parentheses --- .../GenerateParentheses.java | 30 ++++++++----------- 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/src/main/java/generate_parentheses/GenerateParentheses.java b/src/main/java/generate_parentheses/GenerateParentheses.java index ea5193e..f372435 100644 --- a/src/main/java/generate_parentheses/GenerateParentheses.java +++ b/src/main/java/generate_parentheses/GenerateParentheses.java @@ -1,30 +1,24 @@ package generate_parentheses; import java.util.ArrayList; -import java.util.Arrays; +import java.util.List; public class GenerateParentheses { public class Solution { - private void generateParenthesis(ArrayList ans, char[] s, - int left, int right, int n) { - if (left == n) { - Arrays.fill(s, left + right, n << 1, ')'); - ans.add(new String(s)); + public List generateParenthesis(int n) { + List res = new ArrayList(); + helper(n, n, "", res); + return res; + } + void helper(int left, int right, String out, List res) { + if (left < 0 || right < 0 || left > right) return; + if (left == 0 && right == 0) { + res.add(out); return; } - s[left + right] = '('; - generateParenthesis(ans, s, left + 1, right, n); - if (left > right) { - s[left + right] = ')'; - generateParenthesis(ans, s, left, right + 1, n); - } - } - - public ArrayList generateParenthesis(int n) { - ArrayList ans = new ArrayList(); - generateParenthesis(ans, new char[n << 1], 0, 0, n); - return ans; + helper(left - 1, right, out + "(", res); + helper(left, right - 1, out + ")", res); } } From 1d33cf00805e2a6590743cf2e1475a1a4a7a13bc Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 13 Aug 2018 16:37:16 -0700 Subject: [PATCH 316/456] modify text_justification --- .../text_justification/TextJustification.java | 79 +++++++------------ 1 file changed, 30 insertions(+), 49 deletions(-) diff --git a/src/main/java/text_justification/TextJustification.java b/src/main/java/text_justification/TextJustification.java index 5ba09ac..193fe84 100644 --- a/src/main/java/text_justification/TextJustification.java +++ b/src/main/java/text_justification/TextJustification.java @@ -1,66 +1,47 @@ package text_justification; import java.util.ArrayList; +import java.util.List; public class TextJustification { public class Solution { - private void appendSpace(StringBuilder line, int space) { - for (int i = 0; i < space; i++) { - line.append(' '); - } - } - - public ArrayList fullJustify(String[] words, int L) { - ArrayList ans = new ArrayList(); - if (words.length == 0) { - return ans; - } - int begin = 0; - int len = words[0].length(); - int current = 1; - while (current < words.length) { - if (len + words[current].length() + 1 <= L) { - len += words[current].length() + 1; - } else { - int wordCount = current - begin; - int padding = L - len + wordCount - 1; - StringBuilder line = new StringBuilder(); - if (wordCount == 1) { - line.append(words[begin]); - appendSpace(line, padding); - } else { - int slotSize = padding / (wordCount - 1); - int moreSlotCount = padding % (wordCount - 1); - for (int i = 0; i < moreSlotCount; i++) { - line.append(words[begin + i]); - appendSpace(line, slotSize + 1); - } - for (int i = moreSlotCount; i < wordCount - 1; i++) { - line.append(words[begin + i]); - appendSpace(line, slotSize); + public List fullJustify(String[] words, int maxWidth) { + List res = new ArrayList<>(); + int i = 0; + while (i < words.length) { + int j = i, len = 0; + while (j < words.length && len + words[j].length() + j - i <= maxWidth) { + len += words[j++].length(); + } + String out = ""; + int space = maxWidth - len; + for (int k = i; k < j; ++k) { + out += words[k]; + if (space > 0) { + int tmp; + if (j == words.length) { + if (j - k == 1) tmp = space; + else tmp = 1; + } else { + if (j - k - 1 > 0) { + if (space % (j - k - 1) == 0) tmp = space / (j - k - 1); + else tmp = space / (j - k - 1) + 1; + } else tmp = space; } - line.append(words[current - 1]); + //Strings.padEnd(out, tmp, ' '); + for(int a=0; a Date: Mon, 13 Aug 2018 19:07:37 -0700 Subject: [PATCH 317/456] modify count_and_say --- src/main/java/count_and_say/CountandSay.java | 30 +++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/src/main/java/count_and_say/CountandSay.java b/src/main/java/count_and_say/CountandSay.java index fe6d102..a5e026b 100644 --- a/src/main/java/count_and_say/CountandSay.java +++ b/src/main/java/count_and_say/CountandSay.java @@ -4,27 +4,23 @@ public class CountandSay { public class Solution { public String countAndSay(int n) { - String ans = "1"; - n--; - while (n > 0) { - n--; - StringBuilder builder = new StringBuilder(); - int count = 1; - for (int i = 1; i < ans.length(); i++) { - if (ans.charAt(i - 1) == ans.charAt(i)) { - count++; - } else { - builder.append(count); - builder.append(ans.charAt(i - 1)); - count = 1; + if (n <= 0) return ""; + String res = "1"; + while (--n != 0) { + String cur = ""; + for (int i = 0; i < res.length(); ++i) { + int cnt = 1; + while (i + 1 < res.length() && res.charAt(i) == res.charAt(i+1)) { + ++cnt; + ++i; } + cur += Integer.toString(cnt) + res.charAt(i); } - builder.append(count); - builder.append(ans.charAt(ans.length() - 1)); - ans = builder.toString(); + res = cur; } - return ans; + return res; } + } public static class UnitTest { From 0256cf67aab2f888a0d1313837ebdb22673c1dae Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 07:14:57 -0700 Subject: [PATCH 318/456] modify longest_valid_parentheses --- .../LongestValidParentheses.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/main/java/longest_valid_parentheses/LongestValidParentheses.java b/src/main/java/longest_valid_parentheses/LongestValidParentheses.java index 93bf7b4..d8581fd 100644 --- a/src/main/java/longest_valid_parentheses/LongestValidParentheses.java +++ b/src/main/java/longest_valid_parentheses/LongestValidParentheses.java @@ -1,29 +1,29 @@ package longest_valid_parentheses; +import java.util.Stack; + +import static java.lang.Math.max; + public class LongestValidParentheses { public class Solution { public int longestValidParentheses(String s) { - int[] dp = new int[s.length()]; - int max = 0; - for (int i = 0; i < s.length(); i++) { - if (s.charAt(i) == ')') { - int p = i - 1; - while (p >= 0) { - if (s.charAt(p) == '(') { - dp[i] = i - p + 1 + (p > 0 ? dp[p - 1] : 0); - break; - } else if (dp[p] == 0) { - break; + int res = 0, start = 0; + Stack m = new Stack<>(); + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) == '(') m.push(i); + else if (s.charAt(i) == ')') { + if (m.empty()) start = i + 1; + else { + m.pop(); + res = m.empty() ? max(res, i - start + 1) : max(res, i - m.peek()); } - p = p - dp[p]; } } - max = Math.max(max, dp[i]); + return res; } - return max; + } - } public static class UnitTest { From d35d8cbc56c25144eb27fcdc6bccb5429ec7ebfd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 07:46:00 -0700 Subject: [PATCH 319/456] modify next_permutation --- .../next_permutation/NextPermutation.java | 46 +++++++++---------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/src/main/java/next_permutation/NextPermutation.java b/src/main/java/next_permutation/NextPermutation.java index 85bfe37..6f89598 100644 --- a/src/main/java/next_permutation/NextPermutation.java +++ b/src/main/java/next_permutation/NextPermutation.java @@ -3,36 +3,34 @@ public class NextPermutation { public class Solution { - private void swap(int[] num, int i, int j) { - int temp = num[i]; - num[i] = num[j]; - num[j] = temp; - } - - private void reverse(int[] num, int begin, int end) { - end--; - while (begin < end) { - swap(num, begin++, end--); - } - } public void nextPermutation(int[] num) { - if (num.length <= 1) { - return; - } - int i = num.length - 1; - while (i > 0) { - i--; - if (num[i] < num[i + 1]) { - int j = num.length; - while (num[--j] <= num[i]) { + int i, j, n = num.length; + for (i = n - 2; i >= 0; --i) { + if (num[i + 1] > num[i]) { + for (j = n - 1; j >= i; --j) { + if (num[j] > num[i]) break; } - swap(num, i, j); - reverse(num, i + 1, num.length); + int tmp = num[i]; + num[i] = num[j]; + num[j] = tmp; + reverse(num, i + 1, num.length-1); return; } } - reverse(num, 0, num.length); + reverse(num, 0, num.length-1); + + } + + private void reverse(int[] a, int start, int end) { + if (a.length == 0 || a.length == 1) return; + while (start < end) { + int tmp = a[start]; + a[start] = a[end]; + a[end] = tmp; + start++; end--; + } + } } From 764f1fc5168d6e49e9376c2227706daafd83c5b5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 08:06:08 -0700 Subject: [PATCH 320/456] modify substring_with_concat --- .../SubstringwithConcatenationofAllWords.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java b/src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java index 7c04d16..d30a45c 100644 --- a/src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java +++ b/src/main/java/substring_with_concatenation_of_all_words/SubstringwithConcatenationofAllWords.java @@ -7,6 +7,8 @@ public class SubstringwithConcatenationofAllWords { public class Solution { public ArrayList findSubstring(String S, String[] L) { + ArrayList ans = new ArrayList(); + if (S.isEmpty() || L.length == 0) return ans; HashMap dict = new HashMap(); for (String l : L) { Integer count = dict.get(l); @@ -19,28 +21,25 @@ public ArrayList findSubstring(String S, String[] L) { int wordSize = L[0].length(); int windowSize = wordSize * L.length; - ArrayList ans = new ArrayList(); for (int i = 0; i <= S.length() - windowSize; i++) { HashMap temp = new HashMap(); - boolean skip = false; - for (int j = 0; j < windowSize; j += wordSize) { + boolean skip = false; int j = 0; + for (; j < windowSize; j += wordSize) { String word = S.substring(i + j, i + j + wordSize); Integer count = dict.get(word); if (count == null) { - skip = true; break; } Integer tempCount = temp.get(word); if (tempCount == null) { temp.put(word, 1); } else if (count == tempCount) { - skip = true; break; } else { temp.put(word, tempCount + 1); } } - if (!skip && dict.equals(temp)) { + if (j == windowSize) { ans.add(i); } } From d72919fd2ec8097c43753e5c41bc8a81c0513198 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 10:15:01 -0700 Subject: [PATCH 321/456] modify divide_two_integers --- .../DivideTwoIntegers.java | 49 ++++++------------- 1 file changed, 16 insertions(+), 33 deletions(-) diff --git a/src/main/java/divide_two_integers/DivideTwoIntegers.java b/src/main/java/divide_two_integers/DivideTwoIntegers.java index 33e1982..3816eb1 100644 --- a/src/main/java/divide_two_integers/DivideTwoIntegers.java +++ b/src/main/java/divide_two_integers/DivideTwoIntegers.java @@ -1,52 +1,35 @@ package divide_two_integers; -import static org.junit.Assert.assertEquals; - import org.junit.Test; public class DivideTwoIntegers { public class Solution { - // Try to implement without long public int divide(int dividend, int divisor) { - if (divisor == 0) { - throw new IllegalArgumentException("divisor is 0"); - } - if (divisor == Integer.MIN_VALUE) { - return dividend == Integer.MIN_VALUE ? 1 : 0; - } - boolean negative = (dividend > 0) ^ (divisor > 0); - divisor = Math.abs(divisor); - boolean overflow = dividend == Integer.MIN_VALUE; - if (overflow) { - dividend += divisor; - } - dividend = Math.abs(dividend); - int pow = divisor; - while ((pow << 1) > 0 && dividend >= (pow << 1)) { - pow <<= 1; - } - int ans = 0; - while (pow >= divisor) { - ans <<= 1; - if (dividend >= pow) { - dividend -= pow; - ans += 1; + long m = Math.abs((long)dividend), n = Math.abs((long)divisor), res = 0; + if (m < n) return 0; + while (m >= n) { + long t = n, p = 1; + while (m > (t << 1)) { + t <<= 1; + p <<= 1; + } + res += p; + m -= t; } - pow >>= 1; + if ((dividend < 0) ^ (divisor < 0)) res = -res; + return (int) (res > Integer.MAX_VALUE ? Integer.MAX_VALUE : res); // -INT_MIN could be invalid } - if (overflow) { - ans += 1; - } - return negative ? -ans : ans; + } - } public static class UnitTest { @Test public void testDivideWithOverflow() { Solution s = new DivideTwoIntegers().new Solution(); - assertEquals(Integer.MIN_VALUE, s.divide(Integer.MIN_VALUE, 1)); + System.out.println(s.divide(-2147483648, -1)); + + //assertEquals(Integer.MIN_VALUE, s.divide(Integer.MIN_VALUE, 1)); } } } From b8d25d96076ba79b63600d6364d7a3ba386fdb7d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 16:17:46 -0700 Subject: [PATCH 322/456] modify merge_two_sorted_lists --- .../MergeTwoSortedLists.java | 43 ++++++------------- 1 file changed, 12 insertions(+), 31 deletions(-) diff --git a/src/main/java/merge_two_sorted_lists/MergeTwoSortedLists.java b/src/main/java/merge_two_sorted_lists/MergeTwoSortedLists.java index e199695..a0b0e65 100644 --- a/src/main/java/merge_two_sorted_lists/MergeTwoSortedLists.java +++ b/src/main/java/merge_two_sorted_lists/MergeTwoSortedLists.java @@ -6,43 +6,24 @@ public class MergeTwoSortedLists { public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - ListNode head = null; - ListNode pre = null; - while (l1 != null && l2 != null) { - if (l1.val <= l2.val) { - if (head == null) { - head = l1; - } else { - pre.next = l1; - } - pre = l1; + ListNode dummy = new ListNode(0); + ListNode res = dummy; + ListNode cur = res; + while(l1 != null && l2 != null) { + if (l1.val < l2.val) { + cur.next = l1; l1 = l1.next; } else { - if (head == null) { - head = l2; - } else { - pre.next = l2; - } - pre = l2; + cur.next = l2; l2 = l2.next; } + cur = cur.next; } - if (l1 != null) { - if (head == null) { - head = l1; - } else { - pre.next = l1; - } - } - if (l2 != null) { - if (head == null) { - head = l2; - } else { - pre.next = l2; - } - } - return head; + if (l1 != null) cur.next = l1; + if (l2 != null) cur.next = l2; + return res.next; } + } public static class UnitTest { From 118ec990758f063187aa5d391f9bb9db7e5ab7a8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 20:32:55 -0700 Subject: [PATCH 323/456] 4sum --- src/main/java/_4sum/_4Sum.java | 65 +++++++++++----------------------- 1 file changed, 20 insertions(+), 45 deletions(-) diff --git a/src/main/java/_4sum/_4Sum.java b/src/main/java/_4sum/_4Sum.java index bf8eaa4..7af1619 100644 --- a/src/main/java/_4sum/_4Sum.java +++ b/src/main/java/_4sum/_4Sum.java @@ -1,58 +1,33 @@ package _4sum; -import java.util.ArrayList; -import java.util.Arrays; +import java.util.*; public class _4Sum { public class Solution { - private ArrayList list(int... ns) { - ArrayList l = new ArrayList(); - for (int n : ns) { - l.add(n); - } - return l; - } - - private void twoSum(int[] num, int a, int b, int start, int target, - ArrayList> quadruplets) { - int low = start; - int high = num.length - 1; - while (low < high) { - int sum = num[low] + num[high]; - if (sum < target) { - low++; - } else if (sum > target) { - high--; - } else { - quadruplets.add(list(a, b, num[low], num[high])); - do { - low++; - } while (low < high && num[low] == num[low - 1]); - do { - high--; - } while (low < high && num[high] == num[high + 1]); - } - } - } - - public ArrayList> fourSum(int[] num, int target) { - ArrayList> quadruplets = new ArrayList>(); - Arrays.sort(num); - for (int i = 0; i < num.length - 3; i++) { - if (i != 0 && num[i] == num[i - 1]) { - continue; - } - for (int j = i + 1; j < num.length - 2; j++) { - if (j != i + 1 && num[j] == num[j - 1]) { - continue; + public List> fourSum(int[] nums, int target) { + Set > res = new HashSet<>(); + Arrays.sort(nums); + for (int i = 0; i < (nums.length - 3); ++i) { + for (int j = i + 1; j < (nums.length - 2); ++j) { + int left = j + 1, right = nums.length - 1; + while (left < right) { + int sum = nums[i] + nums[j] + nums[left] + nums[right]; + if (sum == target) { + List out = new ArrayList<>(); + out.add(nums[i]); + out.add(nums[j]); + out.add(nums[left]); + out.add(nums[right]); + res.add(out); + ++left; --right; + } else if (sum < target) ++left; + else --right; } - twoSum(num, num[i], num[j], j + 1, - target - num[i] - num[j], quadruplets); } } - return quadruplets; + return new ArrayList<>(res); } } From 9ae90e988172f83a376b5378f4f7b701b7292a62 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 20:49:38 -0700 Subject: [PATCH 324/456] modify letter_combination --- .../LetterCombinationsofaPhoneNumber.java | 30 +++++++++---------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/main/java/letter_combinations_of_a_phone_number/LetterCombinationsofaPhoneNumber.java b/src/main/java/letter_combinations_of_a_phone_number/LetterCombinationsofaPhoneNumber.java index efb05d8..693838b 100644 --- a/src/main/java/letter_combinations_of_a_phone_number/LetterCombinationsofaPhoneNumber.java +++ b/src/main/java/letter_combinations_of_a_phone_number/LetterCombinationsofaPhoneNumber.java @@ -1,6 +1,7 @@ package letter_combinations_of_a_phone_number; import java.util.ArrayList; +import java.util.List; public class LetterCombinationsofaPhoneNumber { @@ -18,26 +19,23 @@ public class Solution { "wxyz" // 9 }; - private void search(ArrayList ans, String digits, int index, - char[] letters) { - if (index == digits.length()) { - ans.add(new String(letters)); - return; - } + public List letterCombinations(String digits) { + List res = new ArrayList<>(); + if (digits.isEmpty()) return res; + letterCombinationsDFS(digits, dict, 0, "", res); + return res; + } - String options = dict[digits.charAt(index) - '0']; - for (int i = 0; i < options.length(); i++) { - letters[index] = options.charAt(i); - search(ans, digits, index + 1, letters); + private void letterCombinationsDFS(String digits, String[] dict, int level, String out, List res) { + if (level == digits.length()) res.add(out); + else { + String str = dict[digits.charAt(level) - '0']; + for (int i = 0; i < str.length(); ++i) { + letterCombinationsDFS(digits, dict, level + 1, out + str.charAt(i), res); + } } } - public ArrayList letterCombinations(String digits) { - ArrayList ans = new ArrayList(); - char[] letters = new char[digits.length()]; - search(ans, digits, 0, letters); - return ans; - } } public static class UnitTest { From a189d586bde3d89edbf5e47cfe97d4967af2bbaf Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 21:00:22 -0700 Subject: [PATCH 325/456] modify 3sum --- src/main/java/_3sum/_3Sum.java | 60 +++++++++++----------------------- 1 file changed, 19 insertions(+), 41 deletions(-) diff --git a/src/main/java/_3sum/_3Sum.java b/src/main/java/_3sum/_3Sum.java index 328ff58..5c67d7a 100644 --- a/src/main/java/_3sum/_3Sum.java +++ b/src/main/java/_3sum/_3Sum.java @@ -1,56 +1,34 @@ package _3sum; -import java.util.ArrayList; -import java.util.Arrays; +import java.util.*; public class _3Sum { public class Solution { - private ArrayList makeTriplet(int a, int b, int c) { - ArrayList ans = new ArrayList(); - ans.add(a); - ans.add(b); - ans.add(c); - return ans; - } - - private void twoSum(ArrayList> ans, int a, - int[] num, int begin) { - int i = begin; - int j = num.length - 1; - while (i < j) { - int sum = num[i] + num[j]; - if (sum < -a) { - i++; - } else if (sum > -a) { - j--; - } else { - ans.add(makeTriplet(a, num[i], num[j])); - do { - i++; - } while (i < j && num[i] == num[i - 1]); - do { - j--; - } while (i < j && num[j] == num[j + 1]); - } - } - } - - public ArrayList> threeSum(int[] num) { - Arrays.sort(num); - ArrayList> ans = new ArrayList>(); - for (int i = 0; i < num.length - 2; i++) { - if (i > 0 && num[i] == num[i - 1]) { - continue; + public List> threeSum(int[] nums) { + Set> res = new HashSet<>(); + Arrays.sort(nums); + for (int k = 0; k < nums.length; ++k) { + if (nums[k] > 0) break; + int target = 0 - nums[k]; + int i = k + 1, j = nums.length - 1; + while (i < j) { + if (nums[i] + nums[j] == target) { + res.add(new ArrayList<>(Arrays.asList(nums[k], nums[i], nums[j]))); + while (i < j && nums[i] == nums[i + 1]) ++i; + while (i < j && nums[j] == nums[j - 1]) --j; + ++i; + --j; + } else if (nums[i] + nums[j] < target) ++i; + else --j; } - twoSum(ans, num[i], num, i + 1); } - return ans; + return new ArrayList<>(res); } } - public static class UnitTest { + public static class UnitTest { } } From 6b81c0b03a33518836eda19e712817ca4542b1a9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 21:08:10 -0700 Subject: [PATCH 326/456] modify 3sum_closest --- src/main/java/_3sum_closest/_3SumClosest.java | 40 ++++++++----------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/src/main/java/_3sum_closest/_3SumClosest.java b/src/main/java/_3sum_closest/_3SumClosest.java index 152eb89..9fce53c 100644 --- a/src/main/java/_3sum_closest/_3SumClosest.java +++ b/src/main/java/_3sum_closest/_3SumClosest.java @@ -1,35 +1,29 @@ package _3sum_closest; -import java.util.Arrays; +import java.util.*; public class _3SumClosest { public class Solution { - public int threeSumClosest(int[] num, int target) { - Arrays.sort(num); - int minSum = num[0] + num[1] + num[2]; - for (int i = 0; i < num.length - 2; i++) { - if (i > 0 && num[i] == num[i - 1]) { - continue; - } - int twoSum = target - num[i]; - int begin = i + 1; - int end = num.length - 1; - while (begin < end) { - int sum = num[begin] + num[end]; - if (Math.abs(twoSum - sum) < Math.abs(target - minSum)) { - minSum = sum + num[i]; - } - if (sum < twoSum) { - begin++; - } else if (sum > twoSum) { - end--; - } else { - return target; + public int threeSumClosest(int[] nums, int target) { + int closest = nums[0] + nums[1] + nums[2]; + int diff = Math.abs(closest - target); + Arrays.sort(nums); + for (int k = 0; k < nums.length; ++k) { + int i = k + 1, j = nums.length - 1; + while (i < j) { + int sum = nums[k] + nums[i] + nums[j]; + int newDiff = Math.abs(sum - target); + if (diff > newDiff) { + diff = newDiff; + closest = sum; } + if (sum < target) ++i; + else --j; + } } - return minSum; + return closest; } } From d1db4716188a4fe64f8b1d356911b4cf3674b4d6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 14 Aug 2018 22:53:20 -0700 Subject: [PATCH 327/456] modify longest_common_prefix --- .../LongestCommonPrefix.java | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/main/java/longest_common_prefix/LongestCommonPrefix.java b/src/main/java/longest_common_prefix/LongestCommonPrefix.java index 1414544..87b8022 100644 --- a/src/main/java/longest_common_prefix/LongestCommonPrefix.java +++ b/src/main/java/longest_common_prefix/LongestCommonPrefix.java @@ -4,22 +4,20 @@ public class LongestCommonPrefix { public class Solution { public String longestCommonPrefix(String[] strs) { - if (strs.length == 0) { - return ""; - } - - int longest = strs[0].length(); - for (int i = 1; i < strs.length; i++) { - longest = Math.min(strs[i].length(), longest); - for (int j = 0; j < longest; j++) { - if (strs[i].charAt(j) != strs[0].charAt(j)) { - longest = j; - break; + if (strs.length == 0) return ""; + String res = ""; + for (int j = 0; j < strs[0].length(); ++j) { + char c = strs[0].charAt(j); + for (int i = 1; i < strs.length; ++i) { + if (j >= strs[i].length() || strs[i].charAt(j) != c) { + return res; } } + res += c; } - return strs[0].substring(0, longest); + return res; } + } public static class UnitTest { From 5bef38ad9d7b472d51ecda6794e6534e46d9ad0b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 06:59:45 -0700 Subject: [PATCH 328/456] modify roman_to_integer --- .../java/roman_to_integer/RomantoInteger.java | 33 ++++++++----------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/src/main/java/roman_to_integer/RomantoInteger.java b/src/main/java/roman_to_integer/RomantoInteger.java index 5906303..be3ab8d 100644 --- a/src/main/java/roman_to_integer/RomantoInteger.java +++ b/src/main/java/roman_to_integer/RomantoInteger.java @@ -6,30 +6,25 @@ public class RomantoInteger { public class Solution { - private Map symbols = new HashMap(); + private Map m = new HashMap(); { - symbols.put('M', 1000); - symbols.put('D', 500); - symbols.put('C', 100); - symbols.put('L', 50); - symbols.put('X', 10); - symbols.put('V', 5); - symbols.put('I', 1); + m.put('M', 1000); + m.put('D', 500); + m.put('C', 100); + m.put('L', 50); + m.put('X', 10); + m.put('V', 5); + m.put('I', 1); } public int romanToInt(String s) { - int num = 0; - num += symbols.get(s.charAt(s.length() - 1)); - for (int i = s.length() - 2; i >= 0; i--) { - char c = s.charAt(i); - char nextC = s.charAt(i + 1); - if (symbols.get(c) < symbols.get(nextC)) { - num -= symbols.get(c); - } else { - num += symbols.get(c); - } + int res = 0; + for (int i = 0; i < s.length(); ++i) { + int val = m.get(s.charAt(i)); + if (i == s.length() - 1 || m.get(s.charAt(i+1)) <= m.get(s.charAt(i))) res += val; + else res -= val; } - return num; + return res; } } From 9f4bcd548494e7837a85694407e47a80b5be645e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 07:10:28 -0700 Subject: [PATCH 329/456] modify integer_to_roman --- .../java/integer_to_roman/IntegertoRoman.java | 44 +++++++------------ 1 file changed, 15 insertions(+), 29 deletions(-) diff --git a/src/main/java/integer_to_roman/IntegertoRoman.java b/src/main/java/integer_to_roman/IntegertoRoman.java index 00495ad..87ada62 100644 --- a/src/main/java/integer_to_roman/IntegertoRoman.java +++ b/src/main/java/integer_to_roman/IntegertoRoman.java @@ -3,40 +3,26 @@ public class IntegertoRoman { public class Solution { + public String intToRoman(int num) { - private final char[] symbols = new char[] { 'M', 'D', 'C', 'L', 'X', - 'V', 'I' }; + String res = ""; + char roman[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I'}; + int value[] = {1000, 500, 100, 50, 10, 5, 1}; - private String repeat(char c, int times) { - String re = ""; - for (int i = 0; i < times; i++) { - re += c; + for (int n = 0; n < 7; n += 2) { + int x = num / value[n]; + if (x < 4) { + for (int i = 1; i <= x; ++i) res += roman[n]; + } else if (x == 4) res = res + roman[n] + roman[n - 1]; + else if (x > 4 && x < 9) { + res += roman[n - 1]; + for (int i = 6; i <= x; ++i) res += roman[n]; + } else if (x == 9) res = res + roman[n] + roman[n - 2]; + num %= value[n]; } - return re; + return res; } - public String intToRoman(int num) { - String roman = ""; - int scala = 1000; - for (int i = 0; i < symbols.length; i += 2) { - int digit = num / scala; - num %= scala; - scala /= 10; - if (digit == 9) { - roman += symbols[i]; - roman += symbols[i - 2]; - } else if (digit >= 5) { - roman += symbols[i - 1]; - roman += repeat(symbols[i], digit - 5); - } else if (digit == 4) { - roman += symbols[i]; - roman += symbols[i - 1]; - } else { - roman += repeat(symbols[i], digit); - } - } - return roman; - } } public static class UnitTest { From f0f3dfe7385efab401226e54cb6b865a646dd18d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 07:44:09 -0700 Subject: [PATCH 330/456] modify palindrome_number --- .../palindrome_number/PalindromeNumber.java | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/main/java/palindrome_number/PalindromeNumber.java b/src/main/java/palindrome_number/PalindromeNumber.java index 717ea24..3096f3b 100644 --- a/src/main/java/palindrome_number/PalindromeNumber.java +++ b/src/main/java/palindrome_number/PalindromeNumber.java @@ -4,22 +4,19 @@ public class PalindromeNumber { public class Solution { public boolean isPalindrome(int x) { - if (x == 0) { - return true; + if (x < 0) return false; + int div = 1; + while (x / div >= 10) div *= 10; + while (x > 0) { + int left = x / div; + int right = x % 10; + if (left != right) return false; + x = (x % div) / 10; + div /= 100; } - if (x < 0 || x % 10 == 0) { - return false; - } - int y = 0; - do { - if (y == x / 10 || y == x) { - return true; - } - y = y * 10 + x % 10; - x = x / 10; - } while (x > y); - return y == x; + return true; } + } public static class UnitTest { From 06fe5d3a831809ec0edccebc31198d4d39f939e3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 07:56:50 -0700 Subject: [PATCH 331/456] modify atoi --- .../StringtoIntegeratoi.java | 43 ++++++------------- 1 file changed, 12 insertions(+), 31 deletions(-) diff --git a/src/main/java/string_to_integer_atoi/StringtoIntegeratoi.java b/src/main/java/string_to_integer_atoi/StringtoIntegeratoi.java index 01401a1..c7a402e 100644 --- a/src/main/java/string_to_integer_atoi/StringtoIntegeratoi.java +++ b/src/main/java/string_to_integer_atoi/StringtoIntegeratoi.java @@ -5,40 +5,21 @@ public class StringtoIntegeratoi { public class Solution { public int atoi(String str) { - int index = 0; - while (index < str.length() - && Character.isWhitespace(str.charAt(index))) { - index++; + if (str.isEmpty()) return 0; + int sign = 1, base = 0, i = 0, n = str.length(); + while (i < n && str.charAt(i) == ' ') ++i; + if (str.charAt(i) == '+' || str.charAt(i) == '-') { + sign = (str.charAt(i++) == '+') ? 1 : -1; } - if (index == str.length()) { - return 0; - } - boolean negative = false; - if (str.charAt(index) == '+') { - index++; - } else if (str.charAt(index) == '-') { - index++; - negative = true; - } - long ans = 0; - while (index < str.length() && Character.isDigit(str.charAt(index))) { - ans = ans * 10 + str.charAt(index) - '0'; - if (ans > Integer.MAX_VALUE + 1L) { - break; - } - index++; - } - if (negative) { - ans = -ans; - if (ans < Integer.MIN_VALUE) { - return Integer.MIN_VALUE; - } - } else { - if (ans > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; + while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') { + if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && + str.charAt(i) - '0' > 7)) { + return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE; } + base = 10 * base + (str.charAt(i++) - '0'); } - return (int) ans; + return base * sign; + } } From ca78f264d50b5c204bd8fc0652968cb4a947e273 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 08:08:02 -0700 Subject: [PATCH 332/456] modify reverse_int --- .../java/reverse_integer/ReverseInteger.java | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/src/main/java/reverse_integer/ReverseInteger.java b/src/main/java/reverse_integer/ReverseInteger.java index 99a7bb3..5046295 100644 --- a/src/main/java/reverse_integer/ReverseInteger.java +++ b/src/main/java/reverse_integer/ReverseInteger.java @@ -4,25 +4,14 @@ public class ReverseInteger { public class Solution { public int reverse(int x) { - if (x == Integer.MIN_VALUE) { - return 0; - } - boolean negative = x < 0; - if (negative) { - x = -x; - } - int y = 0; + long res = 0; while (x != 0) { - int mod = x % 10; - if (y > (Integer.MAX_VALUE - mod) / 10) { - // y * 10 + mod > Integer.MAX_VALUE - return 0; - } - y = y * 10 + mod; + res = 10 * res + x % 10; x /= 10; } - return negative ? -y : y; + return (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) ? 0 : (int)res; } + } public static class UnitTest { From b4ec3289fcc6cb830dcaf823a46527d3341743e1 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 10:14:12 -0700 Subject: [PATCH 333/456] modify longest_palindrome_substring --- .../LongestPalindromicSubstring.java | 52 ++++++------------- 1 file changed, 16 insertions(+), 36 deletions(-) diff --git a/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java b/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java index 83b0e67..e75d33f 100644 --- a/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java +++ b/src/main/java/longest_palindromic_substring/LongestPalindromicSubstring.java @@ -1,50 +1,30 @@ package longest_palindromic_substring; -import static org.junit.Assert.assertEquals; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class LongestPalindromicSubstring { public class Solution { public String longestPalindrome(String s) { - String t = "^#"; - for (int i = 0; i < s.length(); i++) { - t += s.charAt(i); - t += '#'; - } - t += '$'; - - int[] p = new int[t.length()]; - int id = 1; - p[1] = 1; - int rightIndex = 2; - for (int i = 2; i < t.length() - 1; i++) { - if (rightIndex > i) { - p[i] = Math.min(p[2 * id - i], rightIndex - i); - } else { - p[i] = 1; - } - while (t.charAt(i + p[i]) == t.charAt(i - p[i])) { - p[i]++; - } - if (rightIndex < i + p[i]) { - rightIndex = i + p[i]; - id = i; - } - } - - int maxId = 1; - for (int i = 2; i < t.length() - 1; i++) { - if (p[maxId] < p[i]) { - maxId = i; + // DP dp[i][j] - if substr(i,j) is palindrome + boolean [][] dp = new boolean[s.length()][s.length()]; + int left = 0, right = 0, len = 0; + for (int i = 0; i < s.length(); ++i) { + for (int j = 0; j < i; ++j) { + dp[j][i] = (s.charAt(i) == s.charAt(j) && (i - j < 2 || dp[j + 1][i - 1] == true)); + if (dp[j][i] && len < i - j + 1) { + len = i - j + 1; + left = j; + right = i; + } } + dp[i][i] = true; } - - int length = p[maxId] - 1; - int startIndex = (maxId - p[maxId]) / 2; - return s.substring(startIndex, startIndex + length); + return s.substring(left, right + 1); } + } public static class UnitTest { From d62f59c36fbc5c708bb350c7dc2443076ecee0d3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 10:40:37 -0700 Subject: [PATCH 334/456] modify longest_substring_wo_repeating_chars --- ...estSubstringWithoutRepeatingCharacters.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/main/java/longest_substring_without_repeating_characters/LongestSubstringWithoutRepeatingCharacters.java b/src/main/java/longest_substring_without_repeating_characters/LongestSubstringWithoutRepeatingCharacters.java index f31e15c..690c921 100644 --- a/src/main/java/longest_substring_without_repeating_characters/LongestSubstringWithoutRepeatingCharacters.java +++ b/src/main/java/longest_substring_without_repeating_characters/LongestSubstringWithoutRepeatingCharacters.java @@ -6,18 +6,14 @@ public class LongestSubstringWithoutRepeatingCharacters { public class Solution { public int lengthOfLongestSubstring(String s) { - int[] prevPos = new int[Character.MAX_VALUE + 1]; - Arrays.fill(prevPos, -1); - int substringBegin = 0; - int maxSubstringLen = 0; - for (int i = 0; i < s.length(); i++) { - substringBegin = Math.max(substringBegin, - prevPos[s.charAt(i)] + 1); - prevPos[s.charAt(i)] = i; - maxSubstringLen = Math.max(maxSubstringLen, i - substringBegin - + 1); + int[] m = new int[256]; Arrays.fill(m, -1); + int res = 0, left = -1; + for (int i = 0; i < s.length(); ++i) { + left = Math.max(left, m[s.charAt(i)]); + m[s.charAt(i)] = i; + res = Math.max(res, i - left); } - return maxSubstringLen; + return res; } } From cc5638fe8f52386a1ff62eb7bacbc0a78ef948de Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 12:36:40 -0700 Subject: [PATCH 335/456] modify median_of_two_sorted_arrays --- .../MedianofTwoSortedArrays.java | 44 +++++++------------ 1 file changed, 15 insertions(+), 29 deletions(-) diff --git a/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java b/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java index e473616..7cffcee 100644 --- a/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java +++ b/src/main/java/median_of_two_sorted_arrays/MedianofTwoSortedArrays.java @@ -2,43 +2,29 @@ import org.junit.Test; +import java.util.Arrays; + import static org.junit.Assert.assertEquals; public class MedianofTwoSortedArrays { public class Solution { - private int findKth(int A[], int m, int B[], int n, int k) { - if (m == 0) { - return B[k - 1]; - } - if (n == 0) { - return A[k - 1]; - } - if (m + n == k) { - return Math.max(A[m - 1], B[n - 1]); - } - if (m > n) { - return findKth(B, n, A, m, k); - } - int x = Math.min(m, k / 2 + 1); - int y = k + 1 - x; - if (A[x - 1] < B[y - 1]) { - return findKth(A, m, B, y - 1, k); - } else if (A[x - 1] > B[y - 1]) { - return findKth(A, x - 1, B, n, k); - } else { - return A[x - 1]; - } + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int m = nums1.length, n = nums2.length, left = (m + n + 1) / 2, right = (m + n + 2) / 2; + return (findKth(nums1, nums2, left) + findKth(nums1, nums2, right)) / 2.0; } - - public double findMedianSortedArrays(int A[], int B[]) { - int n = A.length + B.length; - if (n % 2 == 1) { - return findKth(A, A.length, B, B.length, n / 2 + 1); + int findKth(int[] nums1, int[] nums2, int k) { + int m = nums1.length, n = nums2.length; + if (m > n) return findKth(nums2, nums1, k); + if (m == 0) return nums2[k - 1]; + if (k == 1) return Math.min(nums1[0], nums2[0]); + int i = Math.min(m, k / 2), j = Math.min(n, k / 2); + if (nums1[i - 1] > nums2[j - 1]) { + return findKth(nums1, Arrays.copyOfRange(nums2, j, n), k - j); + } else { + return findKth(Arrays.copyOfRange(nums1, i, m), nums2, k - i); } - return (findKth(A, A.length, B, B.length, n / 2) + - findKth(A, A.length, B, B.length, n / 2 + 1)) / 2.0; } } From 28cfcdef5aa768b8f55513816c003a3840bf1f00 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 14:54:22 -0700 Subject: [PATCH 336/456] add valid_sudoku --- src/main/java/valid_sudoku/ValidSudoku.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main/java/valid_sudoku/ValidSudoku.java b/src/main/java/valid_sudoku/ValidSudoku.java index 5798ccf..4271018 100644 --- a/src/main/java/valid_sudoku/ValidSudoku.java +++ b/src/main/java/valid_sudoku/ValidSudoku.java @@ -4,20 +4,21 @@ public class ValidSudoku { public class Solution { public boolean isValidSudoku(char[][] board) { - boolean[][] rows = new boolean[9][9]; - boolean[][] columns = new boolean[9][9]; - boolean[][] cells = new boolean[9][9]; - for (int i = 0; i < 9; i++) { - for (int j = 0; j < 9; j++) { + int m = board.length, n = board[0].length; + boolean[][] rows = new boolean[m][n]; + boolean[][] columns = new boolean[m][n]; + boolean[][] cells = new boolean[m][n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { if (board[i][j] == '.') { continue; } - int num = board[i][j] - '1'; - if (rows[i][num] || columns[j][num] - || cells[i / 3 * 3 + j / 3][num]) { + int c = board[i][j] - '1'; + if (rows[i][c] || columns[c][j] + || cells[i / 3 * 3 + j / 3][c]) { return false; } - rows[i][num] = columns[j][num] = cells[i / 3 * 3 + j / 3][num] = true; + rows[i][c] = columns[c][j] = cells[i / 3 * 3 + j / 3][c] = true; } } return true; From f0df749e4d696dfd99eb2f1cb51d5395dc0b8073 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 15:32:27 -0700 Subject: [PATCH 337/456] modify sudoku_solver --- src/main/java/sudoku_solver/SudokuSolver.java | 73 +++++++++++-------- 1 file changed, 44 insertions(+), 29 deletions(-) diff --git a/src/main/java/sudoku_solver/SudokuSolver.java b/src/main/java/sudoku_solver/SudokuSolver.java index 7256795..43a9bdc 100644 --- a/src/main/java/sudoku_solver/SudokuSolver.java +++ b/src/main/java/sudoku_solver/SudokuSolver.java @@ -1,47 +1,62 @@ package sudoku_solver; +import java.util.Arrays; + public class SudokuSolver { public class Solution { - private boolean isValid(char[][] board, int row, int column, char c) { - int cellRow = row - row % 3; - int cellColumn = column - column % 3; - for (int i = 0; i < 9; i++) { - if (board[i][column] == c || board[row][i] == c - || board[cellRow + i / 3][cellColumn + i % 3] == c) { + public boolean solveSudoku(char[][] board){ + for(int i = 0; i < 9; i++){ + for(int j = 0; j < 9; j++){ + if(board[i][j] != '.') + continue; + for(char k = '1'; k <= '9'; k++){ + board[i][j] = k; + if(checkValid(board,i,j)){ + if(solveSudoku(board)) + return true; + } + board[i][j] = '.'; + } return false; } } return true; } - private boolean search(char[][] board, int pos) { - while (pos < 81) { - if (board[pos / 9][pos % 9] == '.') { - break; + private boolean checkValid(char[][] board, int x, int y){ + boolean[] flags = new boolean[9]; + for(int i = 0; i < 9; ++i) + if(board[x][i] >= '1' && board[x][i] <= '9'){ + if(!flags[board[x][i] - '1']) + flags[board[x][i] - '1'] = true; + else + return false; } - pos++; - } - if (pos == 81) { - return true; - } - int row = pos / 9; - int column = pos % 9; - for (char c = '1'; c <= '9'; c++) { - if (isValid(board, row, column, c)) { - board[row][column] = c; - if (search(board, pos + 1)) { - return true; - } + Arrays.fill(flags, false); + for(int i = 0; i < 9; ++i) + if(board[i][y] >= '1' && board[i][y] <= '9'){ + if(!flags[board[i][y] - '1']) + flags[board[i][y] - '1'] = true; + else + return false; } - } - board[row][column] = '.'; - return false; - } + int xx = x/3*3; + int yy = y/3*3; + Arrays.fill(flags, false); + for(int i = 0; i < 3; ++i) + for(int j = 0; j < 3; ++j) + if(board[xx+i][yy+j] >= '1' && board[xx+i][yy+j]<= '9'){ + if(!flags[board[xx+i][yy+j]-'1']) + flags[board[xx+i][yy+j]-'1'] = true; + else + return false; + } - public void solveSudoku(char[][] board) { - search(board, 0); + return true; } + + } public static class UnitTest { From 7d68b7879119157817910b46a9fa282f1e24b37c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 16:18:20 -0700 Subject: [PATCH 338/456] modify regular_exp_matching --- .../RegularExpressionMatching.java | 43 +++++++------------ 1 file changed, 15 insertions(+), 28 deletions(-) diff --git a/src/main/java/regular_expression_matching/RegularExpressionMatching.java b/src/main/java/regular_expression_matching/RegularExpressionMatching.java index b7a382b..a3c1739 100644 --- a/src/main/java/regular_expression_matching/RegularExpressionMatching.java +++ b/src/main/java/regular_expression_matching/RegularExpressionMatching.java @@ -5,36 +5,23 @@ public class RegularExpressionMatching { public class Solution { public boolean isMatch(String s, String p) { - boolean[][] dp = new boolean[p.length() + 1][s.length() + 1]; - dp[0][0] = true; - for (int i = 1; i <= p.length(); i++) { - dp[i][0] = p.charAt(i - 1) == '*' && dp[i - 2][0]; - for (int j = 1; j <= s.length(); j++) { - if (p.charAt(i - 1) == '*') { - if (dp[i - 2][j]) { - dp[i][j] = true; - continue; - } - char prev = p.charAt(i - 2); - for (int k = j; k > 0; k--) { - if (prev != '.' && prev != s.charAt(k - 1)) { - break; - } - if (dp[i - 2][k - 1]) { - dp[i][j] = true; - break; - } - } - } else { - dp[i][j] = dp[i - 1][j - 1] - && (p.charAt(i - 1) == '.' || p.charAt(i - 1) == s - .charAt(j - 1)); - } - } - + if (p.isEmpty()) return s.isEmpty(); + if (p.length() == 1) { + return (s.length() == 1 && (s.charAt(0) == p.charAt(0) || + p.charAt(0) == '.')); + } + if (p.charAt(1) != '*') { + if (s.isEmpty()) return false; + return (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') && + isMatch(s.substring(1), p.substring(1)); } - return dp[p.length()][s.length()]; + while (!s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.')) { + if (isMatch(s, p.substring(2))) return true; + s = s.substring(1); + } + return isMatch(s, p.substring(2)); } + } public static class UnitTest { From c17cba92dff80b3059611b41cf7e2fd9973e21bd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 15 Aug 2018 19:09:43 -0700 Subject: [PATCH 339/456] modify wildcard_matching --- .../wildcard_matching/WildcardMatching.java | 40 ++++++------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/src/main/java/wildcard_matching/WildcardMatching.java b/src/main/java/wildcard_matching/WildcardMatching.java index b1e44f8..67ae1e5 100644 --- a/src/main/java/wildcard_matching/WildcardMatching.java +++ b/src/main/java/wildcard_matching/WildcardMatching.java @@ -4,41 +4,25 @@ public class WildcardMatching { public class Solution { - private int minLength(String p) { - int len = 0; - for (int i = 0; i < p.length(); i++) { - if (p.charAt(i) != '*') { - len++; - } - } - return len; - } - public boolean isMatch(String s, String p) { - if (s.length() < minLength(p)) { - return false; + int m = s.length(), n = p.length(); + boolean[][] dp = new boolean[m+1][n+1]; + dp[0][0] = true; + for (int i = 1; i <= n; ++i) { + if (p.charAt(i-1) == '*') dp[0][i] = dp[0][i - 1]; } - boolean[] dp = new boolean[s.length() + 1]; - dp[0] = true; - for (int i = 1; i <= p.length(); i++) { - for (int j = s.length(); j > 0; j--) { - if (p.charAt(i - 1) == '*') { - for (int k = 0; k <= j; k++) { - if (dp[k]) { - dp[j] = true; - break; - } - } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p.charAt(j-1) == '*') { + dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; } else { - dp[j] = dp[j - 1] - && (p.charAt(i - 1) == '?' || p.charAt(i - 1) == s - .charAt(j - 1)); + dp[i][j] = (s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '?') && dp[i - 1][j - 1]; } } - dp[0] = p.charAt(i - 1) == '*' && dp[0]; } - return dp[s.length()]; + return dp[m][n]; } + } public static class UnitTest { From d8ccd2dbbb1176bbc8b108b232e47e97198efcf7 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 16 Aug 2018 14:16:17 -0700 Subject: [PATCH 340/456] add all_O1_data_structure --- .../AllO1DataStructure.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/main/java/all_O1_data_structure/AllO1DataStructure.java diff --git a/src/main/java/all_O1_data_structure/AllO1DataStructure.java b/src/main/java/all_O1_data_structure/AllO1DataStructure.java new file mode 100644 index 0000000..a09043e --- /dev/null +++ b/src/main/java/all_O1_data_structure/AllO1DataStructure.java @@ -0,0 +1,76 @@ +package all_O1_data_structure; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.TreeMap; + +/** + * Created by lxie on 8/16/18. + */ +class AllOne { + /** + * 核心在于构建两个索引,一个是 key-fre,一个是fre-set(key) 这样才能实现快速的查找 + */ + TreeMap> reversedIndex; + HashMap index; + /** Initialize your data structure here. */ + public AllOne() { + this.reversedIndex = new TreeMap<>(); + this.index = new HashMap<>(); + } + + /** Inserts a new key with value 1. Or increments an existing key by 1. */ + + public void inc(String key) { + if (this.index.containsKey(key) == false){ + this.index.put(key,1); + if(this.reversedIndex.containsKey(1) == false) + this.reversedIndex.put(1,new HashSet()); + this.reversedIndex.get(1).add(key); + } else{ + int currentCounts = this.index.get(key); + this.reversedIndex.get(currentCounts).remove(key); + // 这里必须要做remove,因为treemap要直接firstkey()或者lastkey,下面dec同理 + if(this.reversedIndex.get(currentCounts).size() == 0){ + this.reversedIndex.remove(currentCounts); + } + if(this.reversedIndex.containsKey(currentCounts + 1) == false){ + this.reversedIndex.put(currentCounts + 1,new HashSet<>()); + } + this.index.put(key,currentCounts + 1); + this.reversedIndex.get(currentCounts + 1).add(key); + } + } + + /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ + public void dec(String key) { + if(this.index.containsKey(key)){ + int currentCounts = this.index.get(key); + this.reversedIndex.get(currentCounts).remove(key); + if(this.reversedIndex.get(currentCounts).size() == 0){ + this.reversedIndex.remove(currentCounts); + } + if(currentCounts == 1){ + this.index.remove(key); + } else{ + if(this.reversedIndex.containsKey(currentCounts - 1) == false){ + this.reversedIndex.put(currentCounts - 1,new HashSet<>()); + } + this.reversedIndex.get(currentCounts -1).add(key); + this.index.put(key,currentCounts - 1); + } + } + } + + /** Returns one of the keys with maximal value. */ + public String getMaxKey() { + if (this.index.size() == 0 ) return ""; + return this.reversedIndex.get(this.reversedIndex.lastKey()).iterator().next(); + } + + /** Returns one of the keys with Minimal value. */ + public String getMinKey() { + if (this.index.size() == 0 ) return ""; + return this.reversedIndex.get(this.reversedIndex.firstKey()).iterator().next(); + } +} \ No newline at end of file From 0ab822895d6ecf4705b540cd0be28d7fc408893f Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 16 Aug 2018 20:54:23 -0700 Subject: [PATCH 341/456] add lru_cache --- src/main/java/lru_cache/LRUCache.java | 73 +++++++++++++++++++++------ 1 file changed, 57 insertions(+), 16 deletions(-) diff --git a/src/main/java/lru_cache/LRUCache.java b/src/main/java/lru_cache/LRUCache.java index fc22901..30c8567 100644 --- a/src/main/java/lru_cache/LRUCache.java +++ b/src/main/java/lru_cache/LRUCache.java @@ -1,30 +1,71 @@ package lru_cache; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.HashMap; public class LRUCache { - private LinkedHashMap map; - - @SuppressWarnings("serial") - public LRUCache(final int capacity) { - assert capacity > 0; - map = new LinkedHashMap(16, 0.75f, true) { - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > capacity; - } - }; + private class Node{ + Node prev; + Node next; + int key; + int value; + + public Node(int key, int value) { + this.key = key; + this.value = value; + this.prev = null; + this.next = null; + } + } + + private int capacity; + private HashMap hs = new HashMap(); + private Node head = new Node(-1, -1); + private Node tail = new Node(-1, -1); + + public LRUCache(int capacity) { + this.capacity = capacity; + tail.prev = head; + head.next = tail; } public int get(int key) { - Integer value = map.get(key); - if (value == null) { + if( !hs.containsKey(key)) { return -1; } - return value; + + // remove current + Node current = hs.get(key); + current.prev.next = current.next; + current.next.prev = current.prev; + + // move current to tail + move_to_tail(current); + + return hs.get(key).value; } public void put(int key, int value) { - map.put(key, value); + // get 这个方法会把key挪到最末端,因此,不需要再调用 move_to_tail + if (get(key) != -1) { + hs.get(key).value = value; + return; + } + + if (hs.size() == capacity) { + hs.remove(head.next.key); + head.next = head.next.next; + head.next.prev = head; + } + + Node insert = new Node(key, value); + hs.put(key, insert); + move_to_tail(insert); + } + + private void move_to_tail(Node current) { + current.prev = tail.prev; + tail.prev = current; + current.prev.next = current; + current.next = tail; } } From 2656784ac8cca2ff951145a28f78f40c038ddb87 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 17 Aug 2018 07:06:09 -0700 Subject: [PATCH 342/456] add delete_node_in_bst --- .../delete_node_in_bst/DeleteNodeInBst.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/delete_node_in_bst/DeleteNodeInBst.java diff --git a/src/main/java/delete_node_in_bst/DeleteNodeInBst.java b/src/main/java/delete_node_in_bst/DeleteNodeInBst.java new file mode 100644 index 0000000..909d6d7 --- /dev/null +++ b/src/main/java/delete_node_in_bst/DeleteNodeInBst.java @@ -0,0 +1,35 @@ +package delete_node_in_bst; + +import common.TreeNode; + +/** + * Created by lxie on 8/17/18. + */ +public class DeleteNodeInBst { + + public class Solution { + public TreeNode deleteNode(TreeNode root, int key) { + if (root == null) return null; + if (root.val > key) { + root.left = deleteNode(root.left, key); + } else if (root.val < key) { + root.right = deleteNode(root.right, key); + } else { + if (root.left == null || root.right == null) { + root = (root.left != null) ? root.left : root.right; + } else { + TreeNode cur = root.right; + while (cur.left != null) cur = cur.left; + root.val = cur.val; + root.right = deleteNode(root.right, cur.val); + } + } + return root; + } + } + + public class UnitTest { + + } + +} From c9fa06b7118e0b3ea898c1e081e0f0f9ae7dc8dd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 17 Aug 2018 16:43:21 -0700 Subject: [PATCH 343/456] modify two_sum --- src/main/java/two_sum/TwoSum.java | 56 ++++++++----------------------- 1 file changed, 14 insertions(+), 42 deletions(-) diff --git a/src/main/java/two_sum/TwoSum.java b/src/main/java/two_sum/TwoSum.java index 6aaa1be..5b3e842 100644 --- a/src/main/java/two_sum/TwoSum.java +++ b/src/main/java/two_sum/TwoSum.java @@ -1,51 +1,23 @@ package two_sum; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import java.util.HashMap; -import org.junit.Test; - -public class TwoSum { - - public class Solution { - public int[] twoSum(final int[] numbers, int target) { - List pos = new ArrayList(); - for (int i = 0; i < numbers.length; i++) { - pos.add(i); - } - Collections.sort(pos, new Comparator() { - @Override - public int compare(Integer o1, Integer o2) { - return numbers[o1] - numbers[o2]; - } - }); - - int i = 0; - int j = numbers.length - 1; - while (i < j) { - int sum = numbers[pos.get(i)] + numbers[pos.get(j)]; - if (sum < target) { - i++; - } else if (sum > target) { - j--; - } else { - int[] ans = new int[2]; - ans[0] = Math.min(pos.get(i), pos.get(j)) + 1; - ans[1] = Math.max(pos.get(i), pos.get(j)) + 1; - return ans; - } +class Solution { + public int[] twoSum(int[] nums, int target) { + HashMap m = new HashMap(); + int[] res = new int[2]; + for (int i = 0; i < nums.length; ++i) { + if (m.containsKey(target - nums[i])) { + res[0] = i; + res[1] = m.get(target - nums[i]); + break; } - // Impossible for the test set - return null; + m.put(nums[i], i); } + return res; } - public static class UnitTest { - @Test - public void test() { - new TwoSum().new Solution().twoSum(new int[] { 5, 75, 25 }, 100); - } + public class UnitTest { + } } From 789afe91f981b6e1c88d56ea9baaea260d1e54be Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 17 Aug 2018 22:25:12 -0700 Subject: [PATCH 344/456] add happy_number --- src/main/java/happy_number/HappyNumber.java | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/main/java/happy_number/HappyNumber.java diff --git a/src/main/java/happy_number/HappyNumber.java b/src/main/java/happy_number/HappyNumber.java new file mode 100644 index 0000000..7291eb1 --- /dev/null +++ b/src/main/java/happy_number/HappyNumber.java @@ -0,0 +1,31 @@ +package happy_number; + +import java.util.HashSet; +import java.util.Set; + +/** + * Created by lxie on 8/17/18. + */ +public class HappyNumber { + + public class Solution { + boolean isHappy(int n) { + Set s = new HashSet<>(); + while (n != 1) { + int t = 0; + while (n != 0) { + t += (n % 10) * (n % 10); + n /= 10; + } + n = t; + if (s.contains(n)) break; + else s.add(n); + } + return n == 1; + } + } + + public class UnitTest { + + } +} From 7d8b0f5f8a7baf6ccf86fcaac6c7d280e19b5a37 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 18 Aug 2018 00:33:52 -0700 Subject: [PATCH 345/456] add longest_palindromic_subsequence --- .../LongestPalindromeSubsequence.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/longest_palindromic_subsequence/LongestPalindromeSubsequence.java diff --git a/src/main/java/longest_palindromic_subsequence/LongestPalindromeSubsequence.java b/src/main/java/longest_palindromic_subsequence/LongestPalindromeSubsequence.java new file mode 100644 index 0000000..2ba5adc --- /dev/null +++ b/src/main/java/longest_palindromic_subsequence/LongestPalindromeSubsequence.java @@ -0,0 +1,30 @@ +package longest_palindromic_subsequence; + +/** + * Created by lxie on 8/18/18. + */ +public class LongestPalindromeSubsequence { + + public class Solution { + public int longestPalindromeSubseq(String s) { + int n = s.length(); + int[][] dp = new int[n][n]; + for (int i = n - 1; i >= 0; --i) { + dp[i][i] = 1; + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]); + } + } + } + return dp[0][n - 1]; + } + } + + public class UnitTest { + + } + +} From bb46130f085ed66aaaa910f19688937e8c9e79b9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 18 Aug 2018 10:08:00 -0700 Subject: [PATCH 346/456] add employee_importance --- .../EmployeeImportance.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/employee_importance/EmployeeImportance.java diff --git a/src/main/java/employee_importance/EmployeeImportance.java b/src/main/java/employee_importance/EmployeeImportance.java new file mode 100644 index 0000000..e20425c --- /dev/null +++ b/src/main/java/employee_importance/EmployeeImportance.java @@ -0,0 +1,49 @@ +package employee_importance; + +import java.util.*; + +/** + * Created by lxie on 8/18/18. + */ + + +// Employee info +class Employee { + // It's the unique id of each node; + // unique id of this employee + public int id; + // the importance value of this employee + public int importance; + // the id of direct subordinates + public List subordinates; +}; + + +public class EmployeeImportance { + + public class Solution { + public int getImportance(List employees, int id) { + Set s = new HashSet<>(); + Map m = new HashMap<>(); + for (Employee e : employees) + m.put(e.id, e); // fast find + return helper(id, m, s); + } + + private int helper(int id, Map m, Set s) { + if (s.contains(id)) return 0; + s.add(id); + int res = m.get(id).importance; + for (int num : m.get(id).subordinates) { + res += helper(num, m, s); + } + return res; + } + } + + public class UnitTest { + + + } + +} From 5a41ae1d0a63b277febc98bb5fd887069f84f7bb Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 18 Aug 2018 11:01:36 -0700 Subject: [PATCH 347/456] add replace_words --- src/main/java/replace_words/RepaceWords.java | 76 ++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/main/java/replace_words/RepaceWords.java diff --git a/src/main/java/replace_words/RepaceWords.java b/src/main/java/replace_words/RepaceWords.java new file mode 100644 index 0000000..3aea96c --- /dev/null +++ b/src/main/java/replace_words/RepaceWords.java @@ -0,0 +1,76 @@ +package replace_words; + +import java.util.List; + +/** + * Created by lxie on 8/18/18. + */ +public class RepaceWords { + + class Solution { + + private class TreeNode{ + private boolean isWord; + private TreeNode[] children; + + public TreeNode() { + isWord = false; + children = new TreeNode[26]; + } + + } + + public String replaceWords(List dict, String sentence) { + TreeNode root = buildTrie(dict); + StringBuilder sb = new StringBuilder(); + int start = 0, end = 0; + while (start < sentence.length()) { + if (sentence.charAt(start) == ' ') { + sb.append(' '); + start++; + } else { + end = start; + while (end < sentence.length() && sentence.charAt(end) != ' ') { + end++; + } + String word = sentence.substring(start, end); + String prefix = findPrefix(root, word); + sb.append(prefix.isEmpty() ? word : prefix); + start = end; + } + } + return sb.toString(); + } + + private TreeNode buildTrie(List dict) { + TreeNode root = new TreeNode(); + for (String word: dict) { + TreeNode node = root; + for (char ch: word.toCharArray()) { + if (node.children[ch - 'a'] == null) + node.children[ch - 'a'] = new TreeNode(); + node = node.children[ch - 'a']; + } + node.isWord = true; + + } + return root; + } + + private String findPrefix(TreeNode root, String word) { + TreeNode node = root; + StringBuilder sb = new StringBuilder(); + for (char ch : word.toCharArray()) { + if (node.isWord || node.children[ch - 'a'] == null) + break; + + sb.append(ch); + node = node.children[ch - 'a']; + } + + return node.isWord ? sb.toString() : ""; + } + } + + +} From ab68a42961212b40a4cd22a3fcc7427325db44d4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 18 Aug 2018 23:14:22 -0700 Subject: [PATCH 348/456] add k_empty_slots --- src/main/java/k_empty_slots/KEmptySlots.java | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/k_empty_slots/KEmptySlots.java diff --git a/src/main/java/k_empty_slots/KEmptySlots.java b/src/main/java/k_empty_slots/KEmptySlots.java new file mode 100644 index 0000000..b1175c1 --- /dev/null +++ b/src/main/java/k_empty_slots/KEmptySlots.java @@ -0,0 +1,29 @@ +package k_empty_slots; + +/** + * Created by lxie on 8/18/18. + */ +public class KEmptySlots { + + public class Solution { + + public int kEmptySlots(int[] flowers, int k) { + int res = Integer.MAX_VALUE, left = 0, right = k + 1, n = flowers.length; + int[] days = new int[n]; + for (int i = 0; i < n; ++i) days[flowers[i] - 1] = i + 1; + for (int i = 0; right < n; ++i) { + if (days[i] < days[left] || days[i] <= days[right]) { + if (i == right) res = Math.min(res, Math.max(days[left], days[right])); + left = i; + right = k + 1 + i; + } + } + return (res == Integer.MAX_VALUE) ? -1 : res; + } + } + + public class UnitTest { + + + } +} From abe66b4ca8fd84000391edde4da79d966d524ab5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 19 Aug 2018 00:38:50 -0700 Subject: [PATCH 349/456] add next_cloest_time --- .../next_closest_time/NextClosestTime.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/next_closest_time/NextClosestTime.java diff --git a/src/main/java/next_closest_time/NextClosestTime.java b/src/main/java/next_closest_time/NextClosestTime.java new file mode 100644 index 0000000..8d020ab --- /dev/null +++ b/src/main/java/next_closest_time/NextClosestTime.java @@ -0,0 +1,33 @@ +package next_closest_time; + +/** + * Created by lxie on 8/18/18. + */ +public class NextClosestTime { + + public String nextClosestTime(String time) { + StringBuilder res = new StringBuilder("0000"); + int[] v = {600, 60, 10, 1}; + int found = time.indexOf(":"); + int cur = Integer.parseInt(time.substring(0, found)) * 60 + + Integer.parseInt(time.substring(found + 1)); + for (int i = 1, d = 0; i <= 1440; ++i) { + int next = (cur + i) % 1440; + for (d = 0; d < 4; ++d) { + res.setCharAt(d, (char) ('0' + next / v[d])); + next %= v[d]; + if (time.indexOf(res.charAt(d)) < 0) break; + } + if (d >= 4) break; + } + return res.substring(0, 2) + ":" + res.substring(2); + } + + public static void main(String[] args) { + NextClosestTime n = new NextClosestTime(); + System.out.println(n.nextClosestTime("23:59")); + + } + + +} From 553df8dcd672e8f7d959ecfc0c1c765049d0f678 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 19 Aug 2018 07:28:11 -0700 Subject: [PATCH 350/456] license_key_formatting --- .../LicenseKeyFormatting.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/main/java/license_key_formatting/LicenseKeyFormatting.java diff --git a/src/main/java/license_key_formatting/LicenseKeyFormatting.java b/src/main/java/license_key_formatting/LicenseKeyFormatting.java new file mode 100644 index 0000000..296f81a --- /dev/null +++ b/src/main/java/license_key_formatting/LicenseKeyFormatting.java @@ -0,0 +1,25 @@ +package license_key_formatting; + +/** + * Created by lxie on 8/19/18. + */ +public class LicenseKeyFormatting { + + public class Solution { + public String licenseKeyFormatting(String S, int K) { + StringBuilder res = new StringBuilder(); + for (int i = (int)S.length() - 1; i >= 0; --i) { + if (S.charAt(i) != '-') { + ((res.length() % (K + 1) - K) != 0? res : res.append('-')). + append(Character.toUpperCase(S.charAt(i))); + } + } + return res.reverse().toString(); + } + } + + public class UnitTest { + + + } +} From 656337338e9174021061d584c2cdbd7f1a7a93c6 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 19 Aug 2018 15:04:18 -0700 Subject: [PATCH 351/456] add sentence_screen_fitting --- .../SentenceScreenFitting.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/sentence_screen_fitting/SentenceScreenFitting.java diff --git a/src/main/java/sentence_screen_fitting/SentenceScreenFitting.java b/src/main/java/sentence_screen_fitting/SentenceScreenFitting.java new file mode 100644 index 0000000..b855c27 --- /dev/null +++ b/src/main/java/sentence_screen_fitting/SentenceScreenFitting.java @@ -0,0 +1,34 @@ +package sentence_screen_fitting; + +import java.util.List; + +/** + * Created by lxie on 8/19/18. + */ +public class SentenceScreenFitting { + + public class Solution { + + public int wordsTyping(List sentence, int rows, int cols) { + String all = ""; + for (String word : sentence) all += (word + " "); + int start = 0, len = all.length(); + for (int i = 0; i < rows; ++i) { + start += cols; + if (all.charAt(start % len) == ' ') { + ++start; + } else { + while (start > 0 && all.charAt(start - 1) % len != ' ') { + --start; + } + } + } + return start / len; + } + } + + public class UnitTest { + + + } +} From 9512726e3dde205791b95fe465694a4e89a6486c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 19 Aug 2018 15:32:20 -0700 Subject: [PATCH 352/456] add valid_word_square --- .../valid_word_square/ValidWordSquare.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/valid_word_square/ValidWordSquare.java diff --git a/src/main/java/valid_word_square/ValidWordSquare.java b/src/main/java/valid_word_square/ValidWordSquare.java new file mode 100644 index 0000000..d4c7c6e --- /dev/null +++ b/src/main/java/valid_word_square/ValidWordSquare.java @@ -0,0 +1,34 @@ +package valid_word_square; + +/** + * Created by lxie on 8/19/18. + */ +public class ValidWordSquare { + + public class Solution { + public boolean validWordSquare(String[] words) { + // Write your code here + char[][] square = new char[words.length][words.length]; + + for (int i = 0; i < words.length; i++) { + square[i] = words[i].toCharArray(); + } + + for (int i = 0; i < square.length; i++) { + for (int j = 0; j <= i; j++) { + if (square[i][j] != square[j][i]) { + return false; + } + } + } + + return true; + } + + } + + public class UnitTest { + + + } +} From b0fd3ffaec1617deaf68fc0df521d595cb2e4140 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 19 Aug 2018 17:05:23 -0700 Subject: [PATCH 353/456] add word_squares --- .../valid_word_square/ValidWordSquare.java | 2 +- src/main/java/word_squares/WordSquares.java | 97 +++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 src/main/java/word_squares/WordSquares.java diff --git a/src/main/java/valid_word_square/ValidWordSquare.java b/src/main/java/valid_word_square/ValidWordSquare.java index d4c7c6e..f7ba05e 100644 --- a/src/main/java/valid_word_square/ValidWordSquare.java +++ b/src/main/java/valid_word_square/ValidWordSquare.java @@ -24,7 +24,7 @@ public boolean validWordSquare(String[] words) { return true; } - + } public class UnitTest { diff --git a/src/main/java/word_squares/WordSquares.java b/src/main/java/word_squares/WordSquares.java new file mode 100644 index 0000000..be7c4ef --- /dev/null +++ b/src/main/java/word_squares/WordSquares.java @@ -0,0 +1,97 @@ +package word_squares; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 8/19/18. + */ +public class WordSquares { + + public class Solution { + class TrieNode { + List startWith; + TrieNode[] children; + + TrieNode() { + startWith = new ArrayList<>(); + children = new TrieNode[26]; + } + } + + class Trie { + TrieNode root; + + Trie(String[] words) { + root = new TrieNode(); + for (String w : words) { + TrieNode cur = root; + for (char ch : w.toCharArray()) { + int idx = ch - 'a'; + if (cur.children[idx] == null) + cur.children[idx] = new TrieNode(); + cur.children[idx].startWith.add(w); + cur = cur.children[idx]; + } + } + } + + List findByPrefix(String prefix) { + List ans = new ArrayList<>(); + TrieNode cur = root; + for (char ch : prefix.toCharArray()) { + int idx = ch - 'a'; + if (cur.children[idx] == null) + return ans; + + cur = cur.children[idx]; + } + ans.addAll(cur.startWith); + return ans; + } + } + + public List> wordSquares(String[] words) { + List> ans = new ArrayList<>(); + if (words == null || words.length == 0) + return ans; + int len = words[0].length(); + Trie trie = new Trie(words); + List ansBuilder = new ArrayList<>(); + for (String w : words) { + ansBuilder.add(w); + search(len, trie, ans, ansBuilder); + ansBuilder.remove(ansBuilder.size() - 1); + } + + return ans; + } + + private void search(int len, Trie tr, List> ans, + List ansBuilder) { + if (ansBuilder.size() == len) { + ans.add(new ArrayList<>(ansBuilder)); + return; + } + + int idx = ansBuilder.size(); + StringBuilder prefixBuilder = new StringBuilder(); + for (String s : ansBuilder) + prefixBuilder.append(s.charAt(idx)); + List startWith = tr.findByPrefix(prefixBuilder.toString()); + for (String sw : startWith) { + ansBuilder.add(sw); + search(len, tr, ans, ansBuilder); + ansBuilder.remove(ansBuilder.size() - 1); + } + } + } + + + public class UnitTest { + + + + } + +} From c3a28b3e437135296e6dee88cc6bd58d4548bb62 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 19 Aug 2018 21:15:10 -0700 Subject: [PATCH 354/456] add decode_string --- src/main/java/decode_string/DecodeString.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/decode_string/DecodeString.java diff --git a/src/main/java/decode_string/DecodeString.java b/src/main/java/decode_string/DecodeString.java new file mode 100644 index 0000000..bd64da0 --- /dev/null +++ b/src/main/java/decode_string/DecodeString.java @@ -0,0 +1,43 @@ +package decode_string; + +/** + * Created by lxie on 8/19/18. + */ +public class DecodeString { + + public class Solution { + public String decodeString(String s) { + int[] i = {0}; + return decode(s, i); + } + + private String decode(String s, int[] i) { + String res = ""; + int n = s.length(); + while (i[0] < n && s.charAt(i[0]) != ']') { + if (s.charAt(i[0]) < '0' || s.charAt(i[0]) > '9') { + res += s.charAt(i[0]++); + } else { + int cnt = 0; + while (i[0] < n && s.charAt(i[0]) >= '0' && + s.charAt(i[0]) <= '9') { + cnt = cnt * 10 + s.charAt(i[0]++) - '0'; + } + ++i[0]; // skip '[' + String t = decode(s, i); + ++i[0]; // skip ']' and continue + while (cnt-- > 0) { + res += t; + } + } + } + return res; + } + + } + + public class UnitTest { + + + } +} From 8da231150f6a599d2fef84d3480696059edad741 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 20 Aug 2018 00:01:49 -0700 Subject: [PATCH 355/456] add missing_range --- src/main/java/missing_range/MissingRange.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/missing_range/MissingRange.java diff --git a/src/main/java/missing_range/MissingRange.java b/src/main/java/missing_range/MissingRange.java new file mode 100644 index 0000000..c731b4b --- /dev/null +++ b/src/main/java/missing_range/MissingRange.java @@ -0,0 +1,32 @@ +package missing_range; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 8/19/18. + */ +public class MissingRange { + + public class Solution { + public List findMissingRanges(List nums, int lower, int upper) { + List res = new ArrayList<>(); + int l = lower; + for (int i = 0; i <= nums.size(); ++i) { + int r = (i < nums.size() && nums.get(i) <= upper) ? nums.get(i) : upper + 1; + if (l == r) ++l; + else if (r > l) { + res.add(r - l == 1 ? Integer.toString(l) : Integer.toString(l) + "->" + + Integer.toString(r - 1)); + l = r + 1; + } + } + return res; + } + } + + public class UnitTest { + + + } +} From 65160bf07302f0244da252d13a17573dbb77b357 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 20 Aug 2018 07:17:15 -0700 Subject: [PATCH 356/456] add maximum_vacation_days --- .../MaximumVacationDays.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/maximum_vacation_days/MaximumVacationDays.java diff --git a/src/main/java/maximum_vacation_days/MaximumVacationDays.java b/src/main/java/maximum_vacation_days/MaximumVacationDays.java new file mode 100644 index 0000000..b433120 --- /dev/null +++ b/src/main/java/maximum_vacation_days/MaximumVacationDays.java @@ -0,0 +1,34 @@ +package maximum_vacation_days; + +/** + * Created by lxie on 8/20/18. + */ +public class MaximumVacationDays { + + public class Solution { + + public int maxVacationDays(int[][] flights, int[][] days) { + int n = flights.length, k = days[0].length, res = 0; + int[][] dp = new int[n][k]; + for (int j = k - 1; j >= 0; --j) { + for (int i = 0; i < n; ++i) { + dp[i][j] = days[i][j]; + for (int p = 0; p < n; ++p) { + if ((i == p || (flights[i][p]) != 0 && j < k - 1)) { + dp[i][j] = Math.max(dp[i][j], dp[p][j + 1] + days[i][j]); + } + if (j == 0 && (i == 0 || flights[0][i] != 0)) + res = Math.max(res, dp[i][0]); + } + } + } + return res; + } + + } + + public class UnitTest { + + + } +} From 722855af4885826e8ac8b040f3fceccc8874eade Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 21 Aug 2018 07:24:37 -0700 Subject: [PATCH 357/456] pacific_atlantic_water_flow --- .../MaximumVacationDays.java | 2 +- .../OceanWaterFlow.java | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/main/java/pacific_atlantic_water_flow/OceanWaterFlow.java diff --git a/src/main/java/maximum_vacation_days/MaximumVacationDays.java b/src/main/java/maximum_vacation_days/MaximumVacationDays.java index b433120..541b53b 100644 --- a/src/main/java/maximum_vacation_days/MaximumVacationDays.java +++ b/src/main/java/maximum_vacation_days/MaximumVacationDays.java @@ -24,7 +24,7 @@ public int maxVacationDays(int[][] flights, int[][] days) { } return res; } - + } public class UnitTest { diff --git a/src/main/java/pacific_atlantic_water_flow/OceanWaterFlow.java b/src/main/java/pacific_atlantic_water_flow/OceanWaterFlow.java new file mode 100644 index 0000000..9c3c7c2 --- /dev/null +++ b/src/main/java/pacific_atlantic_water_flow/OceanWaterFlow.java @@ -0,0 +1,56 @@ +package pacific_atlantic_water_flow; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 8/21/18. + */ +public class OceanWaterFlow { + + public class Solution { + + public List pacificAtlantic(int[][] matrix) { + if (matrix.length == 0 || matrix[0].length == 0) return new ArrayList<>(); + List res = new ArrayList<>(); + int m = matrix.length, n = matrix[0].length; + boolean[][] pacific = new boolean[m][n]; + boolean[][] atlantic = new boolean[m][n]; + for (int i = 0; i < m; ++i) { + dfs(matrix, pacific, Integer.MIN_VALUE, i, 0); + dfs(matrix, atlantic, Integer.MIN_VALUE, i, n - 1); + } + for (int i = 0; i < n; ++i) { + dfs(matrix, pacific, Integer.MIN_VALUE, 0, i); + dfs(matrix, atlantic, Integer.MIN_VALUE, m - 1, i); + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (pacific[i][j] && atlantic[i][j]) { + int[] out = {i, j}; + res.add(out); + } + } + } + return res; + } + void dfs(int[][] matrix, boolean[][] visited, int pre, int i, int j) { + int m = matrix.length, n = matrix[0].length; + if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || matrix[i][j] < pre) return; + visited[i][j] = true; + dfs(matrix, visited, matrix[i][j], i + 1, j); + dfs(matrix, visited, matrix[i][j], i - 1, j); + dfs(matrix, visited, matrix[i][j], i, j + 1); + dfs(matrix, visited, matrix[i][j], i, j - 1); + } + + + } + + public class UnitTest { + + + + } + +} From 3e9a5ad0701dbe77f85d3ac59148ab602cab2397 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 21 Aug 2018 21:18:53 -0700 Subject: [PATCH 358/456] add longest_word_in_dict_through_deleting --- .../LongestWordDeleting.java | 32 +++++++++++++++++++ .../QueueReconsByHeight.java | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/main/java/longest_word_in_dict_through_deleting/LongestWordDeleting.java diff --git a/src/main/java/longest_word_in_dict_through_deleting/LongestWordDeleting.java b/src/main/java/longest_word_in_dict_through_deleting/LongestWordDeleting.java new file mode 100644 index 0000000..5b9993b --- /dev/null +++ b/src/main/java/longest_word_in_dict_through_deleting/LongestWordDeleting.java @@ -0,0 +1,32 @@ +package longest_word_in_dict_through_deleting; + +import java.util.List; + +/** + * Created by lxie on 8/21/18. + */ +public class LongestWordDeleting { + + public class Solution { + public String findLongestWord(String s, List d) { + String res = ""; + for (String str : d) { + int i = 0; + for (char c : s.toCharArray()) { + if (i < str.length() && c == str.charAt(i)) ++i; + } + if (i == str.length() && str.length() >= res.length()) { + if (str.length() > res.length() || str.compareTo(res) < 0) { + res = str; + } + } + } + return res; + } + } + + public class UnitTest { + + + } +} diff --git a/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java b/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java index 6873469..6e168e8 100644 --- a/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java +++ b/src/main/java/queue_reconstruct_by_height/QueueReconsByHeight.java @@ -23,7 +23,7 @@ public int compare(int[] arr1, int[] arr2){ int[] p = peopleL.get(i); if (p[1] != i) { peopleL.remove(i); - peopleL.add(p[1], p); + peopleL.add(p[1], p); // (idx, element) } } From 96baae1402834386ecc97de9f61fbfd8e51e6a2b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 22 Aug 2018 07:49:53 -0700 Subject: [PATCH 359/456] add evaluate_division --- .../evaluate_division/EvaluateDivision.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/main/java/evaluate_division/EvaluateDivision.java diff --git a/src/main/java/evaluate_division/EvaluateDivision.java b/src/main/java/evaluate_division/EvaluateDivision.java new file mode 100644 index 0000000..dd3775e --- /dev/null +++ b/src/main/java/evaluate_division/EvaluateDivision.java @@ -0,0 +1,69 @@ +package evaluate_division; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Created by lxie on 8/22/18. + */ +public class EvaluateDivision { + + public static class Solution { + + public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { + double[] res = new double[queries.length]; + for (int i=0; i s = new HashSet<>(); + for (String[] a : equations) { + s.add(a[0]); + s.add(a[1]); + } + for (int i = 0; i < queries.length; ++i) { + String[] query = queries[i]; + if (s.contains(query[0]) && s.contains(query[1])) { + List v = new ArrayList<>(); // visited exprs + res[i] = helper(equations, values, query, v); + } + } + return res; + } + + private double helper(String[][] equations, double[] values, String[] query, List v) { + for (int i = 0; i < equations.length; ++i) { + if (equations[i][0] == query[0] && equations[i][1] == query[1]) return values[i]; + if (equations[i][0] == query[1] && equations[i][1] == query[0]) return 1.0 / values[i]; + } + for (int i = 0; i < equations.length; ++i) { + if (!v.contains(i) && equations[i][0] == query[0]) { // case 1, 2 + v.add(i); // visited + String[] expr = {equations[i][1], query[1]}; + double t = values[i] * helper(equations, values, expr, v); + if (t > 0) return t; + else v.remove(v.size()-1); + } + if (!v.contains(i) && equations[i][1] == query[0]) { // case 3 + v.add(i); + String[] expr = {equations[i][0], query[1]}; + double t = helper(equations, values, expr, v) / values[i]; + if (t > 0) return t; + else v.remove(v.size()-1); + } + } + return -1.0; + } + + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + String[][] equations = {{"a", "b"}, {"b", "c"}}; + double[] values = {2.0, 3.0}; + String[][] queries = {{"a", "c"}, {"b", "c"}, {"a", "e"}, {"a", "a"}, {"x", "x"}}; + double[] res = sol.calcEquation(equations, values, queries); + System.out.println(res.toString()); + } + +} From 8532e888c1af2cd05adab7a4554d8977b4ead3d8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 22 Aug 2018 14:36:02 -0700 Subject: [PATCH 360/456] add perfect_rectangle --- .../perfect_rectangle/PerfectRectangle.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/perfect_rectangle/PerfectRectangle.java diff --git a/src/main/java/perfect_rectangle/PerfectRectangle.java b/src/main/java/perfect_rectangle/PerfectRectangle.java new file mode 100644 index 0000000..083f4ab --- /dev/null +++ b/src/main/java/perfect_rectangle/PerfectRectangle.java @@ -0,0 +1,53 @@ +package perfect_rectangle; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 8/22/18. + */ +public class PerfectRectangle { + + public class Solution { + public boolean isRectangleCover(int[][] rectangles) { + Map m = new HashMap<>(); + int min_x = Integer.MAX_VALUE, min_y = Integer.MAX_VALUE, + max_x = Integer.MIN_VALUE, max_y = Integer.MIN_VALUE, area = 0, cnt = 0; + for (int[] rect : rectangles) { + min_x = Math.min(min_x, rect[0]); + min_y = Math.min(min_y, rect[1]); + max_x = Math.max(max_x, rect[2]); + max_y = Math.max(max_y, rect[3]); + area += (rect[2] - rect[0]) * (rect[3] - rect[1]); + if (!isValid(m, Integer.toString(rect[0]) + "_" + Integer.toString(rect[1]), 1)) return false; // bottom-left + if (!isValid(m, Integer.toString(rect[0]) + "_" + Integer.toString(rect[3]), 2)) return false; // top-left + if (!isValid(m, Integer.toString(rect[2]) + "_" + Integer.toString(rect[3]), 4)) return false; // top-right + if (!isValid(m, Integer.toString(rect[2]) + "_" + Integer.toString(rect[1]), 8)) return false; // bottom-right + } + for (Map.Entry it : m.entrySet() ) { + int t = it.getValue(); + if (t != 15 && t != 12 && t != 10 && t != 9 && t != 6 && t != 5 && t!= 3) { + ++cnt; + } + } + return cnt == 4 && area == (max_x - min_x) * (max_y - min_y); + } + + private boolean isValid(Map m, String corner, int type) { + int val = 0; + if (m.containsKey(corner)) val = m.get(corner); + if ((val & type) != 0) return false; // cannot be same type of corner twice + m.put(corner, val|type); + return true; + } + + + } + + public class UnitTest { + + + + } + +} From 180e6da3425ceff2a43c1fe51ffc5419d3ca2df0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 22 Aug 2018 22:46:55 -0700 Subject: [PATCH 361/456] modify flip_game_ii --- src/main/java/flip_game_ii/FlipGameII.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/flip_game_ii/FlipGameII.java b/src/main/java/flip_game_ii/FlipGameII.java index 17398f4..e6dee6f 100644 --- a/src/main/java/flip_game_ii/FlipGameII.java +++ b/src/main/java/flip_game_ii/FlipGameII.java @@ -10,7 +10,7 @@ public class Solution { public boolean canWin(String s) { for (int i = 1; i < s.length(); ++i) { if (s.charAt(i) == '+' && s.charAt(i-1) == '+' && - !canWin(s.substring(0, i) + "--" + s.substring(i + 1))) { + !canWin(s.substring(0, i-1) + "--" + s.substring(i + 1))) { return true; } } From 461916b99d0a5803a68d9dd75933bfbfff90f580 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 25 Aug 2018 10:06:59 -0700 Subject: [PATCH 362/456] add_bold_tag_in_string --- .../AddBoldTagInString.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/add_bold_tag_in_string/AddBoldTagInString.java diff --git a/src/main/java/add_bold_tag_in_string/AddBoldTagInString.java b/src/main/java/add_bold_tag_in_string/AddBoldTagInString.java new file mode 100644 index 0000000..7644d69 --- /dev/null +++ b/src/main/java/add_bold_tag_in_string/AddBoldTagInString.java @@ -0,0 +1,42 @@ +package add_bold_tag_in_string; + +/** + * Created by lxie on 8/25/18. + */ +public class AddBoldTagInString { + + public String addBoldTag(String s, String[] dict) { + String res = ""; + int n = s.length(), end = 0; + boolean[] bold = new boolean[n]; + for (int i = 0; i < n; ++i) { + for (String word : dict) { + int len = word.length(); + if (i + len <= n && s.substring(i, i+len).equals(word)) { + end = Math.max(end, i + len); + } + } + bold[i] = end > i; + } + for (int i = 0; i < n; ++i) { + if (!bold[i]) { + res += (s.charAt(i)); + continue; + } + int j = i; + while (j < n && bold[j]) ++j; + res += "" + s.substring(i, j) + ""; + i = j-1; + } + return res; + } + + public static void main(String[] args) { + + AddBoldTagInString as = new AddBoldTagInString(); + String[] dict = {"abc","123"}; //{"aaa","aab","bc"}; + System.out.println(as.addBoldTag("abcxyz123", dict)); + + } + +} From d52afe2eea7552135aa3be3a4b40d45fba8fdf53 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 25 Aug 2018 12:44:35 -0700 Subject: [PATCH 363/456] add encode_string_shortest_lengh --- .../EncodeStringShortestLength.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/encode_string_shortest_lengh/EncodeStringShortestLength.java diff --git a/src/main/java/encode_string_shortest_lengh/EncodeStringShortestLength.java b/src/main/java/encode_string_shortest_lengh/EncodeStringShortestLength.java new file mode 100644 index 0000000..f3eef2c --- /dev/null +++ b/src/main/java/encode_string_shortest_lengh/EncodeStringShortestLength.java @@ -0,0 +1,40 @@ +package encode_string_shortest_lengh; + +/** + * Created by lxie on 8/25/18. + */ +public class EncodeStringShortestLength { + + public static class Solution { + + public String encode(String s) { + int n = s.length(); + String[][] dp = new String[n][n]; + for (int step = 1; step <= n; ++step) { + for (int i = 0; i + step - 1 < n; ++i) { + int j = i + step - 1; + dp[i][j] = s.substring(i, i+step); + for (int k = i; k < j; ++k) { + String left = dp[i][k], right = dp[k + 1][j]; + if (left.length() + right.length() < dp[i][j].length()) { + dp[i][j] = left + right; + } + } + String t = s.substring(i, j+1), replace = ""; + int pos = (t + t).indexOf(t, 1); + if (pos >= t.length()) replace = t; + else replace = Integer.toString(t.length() / pos) + '[' + dp[i][i + pos - 1] + ']'; + if (replace.length() < dp[i][j].length()) dp[i][j] = replace; + } + } + return dp[0][n - 1]; + } + + } + + public static void main(String[] args) { + Solution sol = new Solution(); + System.out.println(sol.encode("abbbabbbcabbbabbbc")); + + } +} From 4cdb468b67ea308b935d023ce184c4e69530527d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 25 Aug 2018 22:52:57 -0700 Subject: [PATCH 364/456] add find_duplicate_subtrees --- .../FindDuplicateSubtrees.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/find_duplicate_subtrees/FindDuplicateSubtrees.java diff --git a/src/main/java/find_duplicate_subtrees/FindDuplicateSubtrees.java b/src/main/java/find_duplicate_subtrees/FindDuplicateSubtrees.java new file mode 100644 index 0000000..12d90bc --- /dev/null +++ b/src/main/java/find_duplicate_subtrees/FindDuplicateSubtrees.java @@ -0,0 +1,38 @@ +package find_duplicate_subtrees; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 8/25/18. + */ +public class FindDuplicateSubtrees { + + public class Solution { + public List findDuplicateSubtrees(TreeNode root) { + List res = new ArrayList<>(); + Map m = new HashMap<>(); + helper(root, m, res); + return res; + } + + private String helper(TreeNode node, Map m, List res) { + if (node == null) return "#"; + String str = Integer.toString(node.val) + "," + helper(node.left, m, res) + "," + + helper(node.right, m, res); + if (m.containsKey(str) && m.get(str) == 1) res.add(node); + if (!m.containsKey(str)) m.put(str, 1); + else m.put(str, m.get(str)+1); + return str; + } + } + + public class UnitTest { + + } + +} From 57bcb048d1c3fb008f86eba9960ec27fd0bbbbc3 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 26 Aug 2018 14:01:15 -0700 Subject: [PATCH 365/456] sort_transformed_array --- .../SortTransformedArray.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/sort_transformed_array/SortTransformedArray.java diff --git a/src/main/java/sort_transformed_array/SortTransformedArray.java b/src/main/java/sort_transformed_array/SortTransformedArray.java new file mode 100644 index 0000000..58703b4 --- /dev/null +++ b/src/main/java/sort_transformed_array/SortTransformedArray.java @@ -0,0 +1,33 @@ +package sort_transformed_array; + +/** + * Created by lxie on 8/26/18. + */ +public class SortTransformedArray { + + public class Solution { + public int[] sortTransformedArray(int[] nums, int a, int b, int c) { + int n = nums.length, i = 0, j = n - 1; + int[] res = new int[n]; + int idx = a >= 0 ? n - 1 : 0; + while (i <= j) { + if (a >= 0) { + res[idx--] = cal(nums[i], a, b, c) >= cal(nums[j], a, b, c) ? cal(nums[i++], a, b, c) : cal(nums[j--], a, b, c); + } else { + res[idx++] = cal(nums[i], a, b, c) >= cal(nums[j], a, b, c) ? cal(nums[j--], a, b, c) : cal(nums[i++], a, b, c); + } + } + return res; + } + int cal(int x, int a, int b, int c) { + return a * x * x + b * x + c; + } + + } + + public class UnitTest { + + } + + +} From a6ba6472bedad45b2c027f4e5e795ef86857f4ea Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 26 Aug 2018 15:18:05 -0700 Subject: [PATCH 366/456] add min_unique_word_abbrev --- .../MinUniqueWordAbbrev.java | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java diff --git a/src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java b/src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java new file mode 100644 index 0000000..da8fb60 --- /dev/null +++ b/src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java @@ -0,0 +1,85 @@ +package min_unique_word_abbrev; + +import javafx.util.Pair; + +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * Created by lxie on 8/26/18. + */ +public class MinUniqueWordAbbrev { + + public class Solution { + public String minAbbreviation(String target, String[] dictionary) { + if (dictionary.length == 0) return Integer.toString((int)target.length()); + //priority_queue, vector>, greater>> q; + PriorityQueue> q; + q = generate(target); + while (!q.isEmpty()) { + Pair t = q.peek(); q.poll(); + boolean no_conflict = true; + for (String word : dictionary) { + if (valid(word, t.getValue())) { + no_conflict = false; + break; + } + } + if (no_conflict) return t.getValue(); + } + return ""; + } + + + private PriorityQueue> generate(String target) { + PriorityQueue> res = new PriorityQueue<>(50, new Comparator>() { + @Override + public int compare(Pair o1, Pair o2) { + return o1.getKey() - o2.getKey(); + } + }); + for (int i = 0; i < Math.pow(2, target.length()); ++i) { + String out = ""; + int cnt = 0, size = 0; + for (int j = 0; j < target.length(); ++j) { + if (((i >> j) & 1) != 0) ++cnt; + else { + if (cnt != 0) { + out += Integer.toString(cnt); + cnt = 0; + ++size; + } + out += target.charAt(j); + ++size; + } + } + if (cnt > 0) { + out += Integer.toString(cnt); + ++size; + } + res.add(new Pair(size, out)); + } + return res; + } + + private boolean valid(String word, String abbr) { + int m = word.length(), n = abbr.length(), p = 0, cnt = 0; + for (int i = 0; i < abbr.length(); ++i) { + if (abbr.charAt(i) >= '0' && abbr.charAt(i) <= '9') { + if (cnt == 0 && abbr.charAt(i) == '0') return false; + cnt = 10 * cnt + abbr.charAt(i) - '0'; + } else { + p += cnt; + if (p >= m || word.charAt(p++) != abbr.charAt(i)) return false; + cnt = 0; + } + } + return p + cnt == m; + } + } + + public class UnitTest { + + + } +} From dadae954430b241ec86e1424e03c7a02bce71475 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 26 Aug 2018 17:18:54 -0700 Subject: [PATCH 367/456] add optimal_account_balance --- .../OptimalAccountBalancing.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/main/java/optimal_account_balance/OptimalAccountBalancing.java diff --git a/src/main/java/optimal_account_balance/OptimalAccountBalancing.java b/src/main/java/optimal_account_balance/OptimalAccountBalancing.java new file mode 100644 index 0000000..d39901e --- /dev/null +++ b/src/main/java/optimal_account_balance/OptimalAccountBalancing.java @@ -0,0 +1,60 @@ +package optimal_account_balance; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 8/26/18. + */ +public class OptimalAccountBalancing { + + public int minTransfers(int[][] transactions) { + Map m = new HashMap<>(); + for (int[] t : transactions) { + if(m.containsKey(t[0])) + m.put(t[0], m.get(t[0]) - t[2]); + else + m.put(t[0], -t[2]); + + if(m.containsKey(t[1])) + m.put(t[1], m.get(t[1]) + t[2]); + else + m.put(t[1], t[2]); + } + + List accnt = new ArrayList<>(); + for (Map.Entry a : m.entrySet()) { + if (a.getValue() != 0) accnt.add(a.getValue()); + } + return helper(accnt, 0, accnt.size(), 0); + } + + private int helper(List accnt, int start, int n, int num) { + int res = Integer.MAX_VALUE; + while (start < n && accnt.get(start) == 0) ++start; + for (int i = start + 1; i < n; ++i) { + if ((accnt.get(i) < 0 && accnt.get(start) > 0) || (accnt.get(i) > 0 && accnt.get(start) < 0)) { + accnt.set(i, accnt.get(i) + accnt.get(start)); // start set to 0 and update i + res = Math.min(res, helper(accnt, start + 1, n, num + 1)); + accnt.set(i, accnt.get(i) - accnt.get(start)); + } + } + return res == Integer.MAX_VALUE ? num : res; + } + + public static void main(String[] args) { + + OptimalAccountBalancing ob = new OptimalAccountBalancing(); + int[][] transactions = {{0,1,10}, {2,0,5}}; // {{0,1,10}, {1,0,1}, {1,2,5}, {2,0,5}}; + System.out.println(ob.minTransfers(transactions)); + + + } + + + + + +} From 5a2a741af4788faeed21b7dc976070ad92cf928b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 27 Aug 2018 01:00:24 -0700 Subject: [PATCH 368/456] modify longest_consecutive_sequence --- .../LongestConsecutiveSequence.java | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/src/main/java/longest_consecutive_sequence/LongestConsecutiveSequence.java b/src/main/java/longest_consecutive_sequence/LongestConsecutiveSequence.java index 0e068f6..1b0af5e 100644 --- a/src/main/java/longest_consecutive_sequence/LongestConsecutiveSequence.java +++ b/src/main/java/longest_consecutive_sequence/LongestConsecutiveSequence.java @@ -1,30 +1,26 @@ package longest_consecutive_sequence; -import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; public class LongestConsecutiveSequence { public class Solution { - public int longestConsecutive(int[] num) { - HashSet nums = new HashSet(); - for (int n : num) { - nums.add(n); - } - int ans = 0; - for (int n : num) { - int i = n - 1; - while (nums.contains(i)) { - nums.remove(i); - i--; - } - int j = n + 1; - while (nums.contains(j)) { - nums.remove(j); - j++; + public int longestConsecutive(int[] nums) { + int res = 0; + Map m = new HashMap<>(); + for (int d : nums) { + if (!m.containsKey(d)) { + int left = m.containsKey(d - 1) ? m.get(d - 1) : 0; + int right = m.containsKey(d + 1) ? m.get(d + 1) : 0; + int sum = left + right + 1; + m.put(d, sum); + res = Math.max(res, sum); + m.put(d - left, sum); + m.put(d + right, sum); } - ans = Math.max(ans, j - i - 1); } - return ans; + return res; } } From b8bec0e8a1725ea27db6a72b54a3df34e9de0f43 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 27 Aug 2018 07:34:41 -0700 Subject: [PATCH 369/456] add 24_game --- src/main/java/_24game/Solve24Game.java | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/main/java/_24game/Solve24Game.java diff --git a/src/main/java/_24game/Solve24Game.java b/src/main/java/_24game/Solve24Game.java new file mode 100644 index 0000000..36bcd97 --- /dev/null +++ b/src/main/java/_24game/Solve24Game.java @@ -0,0 +1,55 @@ +package _24game; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 8/27/18. + */ +public class Solve24Game { + + public class Solution { + + public boolean judgePoint24(int[] nums) { + double eps = 0.001; + char[] ops = {'+', '-', '*', '/'}; + double[] arr = new double[nums.length]; + for(int i=0; i t = new ArrayList<>(); + for (int k = 0; k < nums.length; ++k) { + if (k != i && k != j) t.add((double) nums[k]); + } + for (char op : ops) { + if ((op == '+' || op == '*') && i > j) continue; + if (op == '/' && nums[j] < eps) continue; + switch(op) { + case '+': t.add((double) nums[i] + nums[j]); break; + case '-': t.add((double) nums[i] - nums[j]); break; + case '*': t.add((double) nums[i] * nums[j]); break; + case '/': t.add((double) nums[i] / nums[j]); break; + } + double[] t1 = t.stream().mapToDouble(d -> d).toArray(); + if (helper(t1, ops, eps)) return true; + t.remove(t.size()-1); + } + } + } + return false; + } + } + + public class UnitTest { + + + } + +} From 7a028438c43001ce12b8e1123a07a76fbb1afd09 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 27 Aug 2018 14:19:21 -0700 Subject: [PATCH 370/456] add the_maze --- src/main/java/the_maze/TheMaze.java | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/the_maze/TheMaze.java diff --git a/src/main/java/the_maze/TheMaze.java b/src/main/java/the_maze/TheMaze.java new file mode 100644 index 0000000..3a720be --- /dev/null +++ b/src/main/java/the_maze/TheMaze.java @@ -0,0 +1,49 @@ +package the_maze; + +import java.util.Arrays; + +/** + * Created by lxie on 8/27/18. + */ +public class TheMaze { + + public class Solution { + + public int[][] dirs = {{0,-1},{-1,0},{0,1},{1,0}}; + + boolean hasPath(int[][] maze, int[] start, int[] destination) { + if (maze.length == 0 || maze[0].length == 0) return true; + int m = maze.length, n = maze[0].length; + int[][] dp = new int[m][n]; + for (int[] a : dp) Arrays.fill(a, -1); + return helper(maze, dp, start[0], start[1], destination[0], destination[1]); + } + + private boolean helper(int[][] maze, int[][] dp, int i, int j, int di, int dj) { + if (i == di && j == dj) return true; + if (dp[i][j] != -1) return dp[i][j] == 1 ? true : false; + boolean res = false; + int m = maze.length, n = maze[0].length; + maze[i][j] = -1; + for (int[] dir : dirs) { + int x = i, y = j; + while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] != 1) { + x += dir[0]; y += dir[1]; + } + x -= dir[0]; y -= dir[1]; + if (maze[x][y] != -1) { + res |= helper(maze, dp, x, y, di, dj); // either way + } + } + dp[i][j] = res ? 1 : 0; + return res; + } + } + + public class UnitTest { + + + + } + +} From 12ddd75443d929d738e0b2b8c6b5709f13ac7bce Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 27 Aug 2018 15:16:21 -0700 Subject: [PATCH 371/456] add the_maze_ii --- src/main/java/the_maze_ii/TheMazeII.java | 51 ++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/java/the_maze_ii/TheMazeII.java diff --git a/src/main/java/the_maze_ii/TheMazeII.java b/src/main/java/the_maze_ii/TheMazeII.java new file mode 100644 index 0000000..0bfbce8 --- /dev/null +++ b/src/main/java/the_maze_ii/TheMazeII.java @@ -0,0 +1,51 @@ +package the_maze_ii; + +import java.util.Arrays; + +/** + * Created by lxie on 8/27/18. + */ +public class TheMazeII { + + public class Solution { + + public int[][] dirs = {{0,-1},{-1,0},{0,1},{1,0}}; + + public int shortestDistance(int[][] maze, int[] start, int[] destination) { + int m = maze.length, n = maze[0].length; + int[][] dists = new int[m][n]; + for (int[] a : dists) Arrays.fill(a, Integer.MAX_VALUE); + + dists[start[0]][start[1]] = 0; + helper(maze, start[0], start[1], destination, dists); + int res = dists[destination[0]][destination[1]]; + return (res == Integer.MAX_VALUE) ? -1 : res; + } + + private void helper(int[][] maze, int i, int j, int[] destination, int[][] dists) { + if (i == destination[0] && j == destination[1]) return; + int m = maze.length, n = maze[0].length; + for (int[] d : dirs) { + int x = i, y = j, dist = dists[x][y]; + while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0) { + x += d[0]; + y += d[1]; + ++dist; + } + x -= d[0]; + y -= d[1]; + --dist; + if (dists[x][y] > dist) { + dists[x][y] = dist; + helper(maze, x, y, destination, dists); + } + } + } + } + + public class UnitTest{ + + } + + +} From 58fa27792e4bef20b3d6beb30e64bbbae9261071 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 27 Aug 2018 23:10:54 -0700 Subject: [PATCH 372/456] add redundant_connection --- .../RedundantConnection.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/redundant_connection/RedundantConnection.java diff --git a/src/main/java/redundant_connection/RedundantConnection.java b/src/main/java/redundant_connection/RedundantConnection.java new file mode 100644 index 0000000..233f3dc --- /dev/null +++ b/src/main/java/redundant_connection/RedundantConnection.java @@ -0,0 +1,33 @@ +package redundant_connection; + +import java.util.Arrays; + +/** + * Created by lxie on 8/27/18. + */ +public class RedundantConnection { + + public class Solution { + public int[] findRedundantDirectedConnection(int[][] edges) { + int[] root = new int[2001]; + Arrays.fill(root, -1); + for (int[] edge : edges) { + int x = find(root, edge[0]), y = find(root, edge[1]); + if (x == y) return edge; + root[x] = y; + } + return null; + } + int find(int[] root, int i) { + while (root[i] != -1) { + i = root[i]; + } + return i; + } + } + + public class UnitTest { + + } + +} From 23b00539022610554ee7d886e644dc740d7645c1 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 28 Aug 2018 07:21:22 -0700 Subject: [PATCH 373/456] add nth_digit --- src/main/java/nth_digit/NthDigit.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/nth_digit/NthDigit.java diff --git a/src/main/java/nth_digit/NthDigit.java b/src/main/java/nth_digit/NthDigit.java new file mode 100644 index 0000000..01c4b71 --- /dev/null +++ b/src/main/java/nth_digit/NthDigit.java @@ -0,0 +1,27 @@ +package nth_digit; + +/** + * Created by lxie on 8/28/18. + */ +public class NthDigit { + + public class Solution { + int findNthDigit(int n) { + long len = 1, cnt = 9, start = 1; + while (n > len * cnt) { + n -= len * cnt; + ++len; + cnt *= 10; + start *= 10; + } + start += (n - 1) / len; + String t = Long.toString(start); + return t.charAt((n - 1) % (int)len) - '0'; + } + } + + public class UnitTest { + + + } +} From 188966cda5eab6365df944f7c830f7cb629e9714 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 28 Aug 2018 11:11:42 -0700 Subject: [PATCH 374/456] add diagonal_traverse --- .../diagonal_traverse/DiagonalTraverse.java | 31 +++++++++++++++++++ src/main/java/nth_digit/NthDigit.java | 1 - 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 src/main/java/diagonal_traverse/DiagonalTraverse.java diff --git a/src/main/java/diagonal_traverse/DiagonalTraverse.java b/src/main/java/diagonal_traverse/DiagonalTraverse.java new file mode 100644 index 0000000..ba59cd6 --- /dev/null +++ b/src/main/java/diagonal_traverse/DiagonalTraverse.java @@ -0,0 +1,31 @@ +package diagonal_traverse; + +/** + * Created by lxie on 8/28/18. + */ +public class DiagonalTraverse { + + public class Solution { + public int[] findDiagonalOrder(int[][] matrix) { + if (matrix.length == 0 || matrix[0].length == 0) return null; + int m = matrix.length, n = matrix[0].length, r = 0, c = 0, k = 0; + int[] res = new int[m*n]; + int[][] dirs = {{-1,1}, {1,-1}}; + for (int i = 0; i < m * n; ++i) { + res[i] = matrix[r][c]; + r += dirs[k][0]; + c += dirs[k][1]; + if (r >= m) {r = m - 1; c += 2; k = 1 - k;} + if (c >= n) {c = n - 1; r += 2; k = 1 - k;} + if (r < 0) {r = 0; k = 1 - k;} + if (c < 0) {c = 0; k = 1 - k;} + } + return res; + } + } + + public class UnitTest { + + } + +} diff --git a/src/main/java/nth_digit/NthDigit.java b/src/main/java/nth_digit/NthDigit.java index 01c4b71..eba5401 100644 --- a/src/main/java/nth_digit/NthDigit.java +++ b/src/main/java/nth_digit/NthDigit.java @@ -22,6 +22,5 @@ int findNthDigit(int n) { public class UnitTest { - } } From d56a794a7ac961774832cfe75923656f60051a20 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 28 Aug 2018 16:50:21 -0700 Subject: [PATCH 375/456] add find_permutation --- .../find_permutation/FindPermutation.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/find_permutation/FindPermutation.java diff --git a/src/main/java/find_permutation/FindPermutation.java b/src/main/java/find_permutation/FindPermutation.java new file mode 100644 index 0000000..4b6b0a7 --- /dev/null +++ b/src/main/java/find_permutation/FindPermutation.java @@ -0,0 +1,37 @@ +package find_permutation; + +/** + * Created by lxie on 8/28/18. + */ +public class FindPermutation { + public int[] findPermutation(String s) { + int n = s.length(); + int[] res = new int[n+1]; + for (int i = 0; i < n + 1; ++i) res[i] = i + 1; + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == 'D') { + int j = i; + while (s.charAt(i) == 'D' && i < n) ++i; + reverse(res, j, i ); + --i; + } + } + return res; + } + + private void reverse(int[] a, int i, int j) { + while (i < j) { + int t = a[j]; + a[j] = a[i]; + a[i] = t; + i++; j--; + } + } + + public static void main(String[] args) { + FindPermutation f = new FindPermutation(); + int[] res = f.findPermutation("DDIIDI"); + System.out.println(res); + } + +} From c768873f561d3d120858cabc97d27c994e33f906 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 29 Aug 2018 09:53:17 -0700 Subject: [PATCH 376/456] add count_of_range_sum --- .../count_of_range_sum/CountOfRangeSum.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/count_of_range_sum/CountOfRangeSum.java diff --git a/src/main/java/count_of_range_sum/CountOfRangeSum.java b/src/main/java/count_of_range_sum/CountOfRangeSum.java new file mode 100644 index 0000000..852ad1c --- /dev/null +++ b/src/main/java/count_of_range_sum/CountOfRangeSum.java @@ -0,0 +1,40 @@ +package count_of_range_sum; + +/** + * Created by lxie on 8/29/18. + */ +public class CountOfRangeSum { + + public class Solution { + + public int countRangeSum(int[] nums, int lower, int upper) { + long[] sums = new long[nums.length+1]; + for (int i = 0; i < nums.length; ++i) { + sums[i + 1] = sums[i] + nums[i]; + } + return countAndMergeSort(sums, 0, sums.length, lower, upper); + } + + private int countAndMergeSort(long[] sums, int start, int end, int lower, int upper) { + if (end - start <= 1) return 0; + int mid = start + (end - start) / 2; + int cnt = countAndMergeSort(sums, start, mid, lower, upper) + countAndMergeSort(sums, mid, end, lower, upper); + int j = mid, k = mid, t = mid; + long[] cache = new long[end-start]; + for (int i = start, r = 0; i < mid; ++i, ++r) { + while (k < end && sums[k] - sums[i] < lower) ++k; + while (j < end && sums[j] - sums[i] <= upper) ++j; + while (t < end && sums[t] < sums[i]) cache[r++] = sums[t++]; + cache[r] = sums[i]; + cnt += j - k; + } + for (int i = 0; i < t-start; ++i) sums[start+i] = cache[i]; + return cnt; + } + } + + public class UnitTest { + + + } +} From e851d5fee13ba9bd8f65ab429dedb59d94ba7e1d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 29 Aug 2018 09:59:53 -0700 Subject: [PATCH 377/456] add comments for count_of_range_sum --- src/main/java/count_of_range_sum/CountOfRangeSum.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/count_of_range_sum/CountOfRangeSum.java b/src/main/java/count_of_range_sum/CountOfRangeSum.java index 852ad1c..a264905 100644 --- a/src/main/java/count_of_range_sum/CountOfRangeSum.java +++ b/src/main/java/count_of_range_sum/CountOfRangeSum.java @@ -15,6 +15,10 @@ public int countRangeSum(int[] nums, int lower, int upper) { return countAndMergeSort(sums, 0, sums.length, lower, upper); } + // j是第一个满足 sums[j] - sums[i] > upper 的下标 + // k是第一个满足 sums[k] - sums[i] >= lower 的下标 + // cache用于缓存merge sort结果 + private int countAndMergeSort(long[] sums, int start, int end, int lower, int upper) { if (end - start <= 1) return 0; int mid = start + (end - start) / 2; From 9c7db967b083ee1a9005a06e3d6b534324f41c9e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 31 Aug 2018 10:20:56 -0700 Subject: [PATCH 378/456] add max_xor_two_numbers_in_array --- src/main/java/LFU_cache/LFUCache.java | 68 +++++++++++++++++++ .../count_of_range_sum/CountOfRangeSum.java | 4 +- .../MaxXorTwoNumbersInArray.java | 39 +++++++++++ 3 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 src/main/java/LFU_cache/LFUCache.java create mode 100644 src/main/java/max_xor_two_numbers_in_array/MaxXorTwoNumbersInArray.java diff --git a/src/main/java/LFU_cache/LFUCache.java b/src/main/java/LFU_cache/LFUCache.java new file mode 100644 index 0000000..af9ead0 --- /dev/null +++ b/src/main/java/LFU_cache/LFUCache.java @@ -0,0 +1,68 @@ +package LFU_cache; + +import javafx.util.Pair; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 8/29/18. + */ +public class LFUCache { + + private int cap, minFreq; + private Map> m = new HashMap<>(); // key - value, freq + private Map> freq = new HashMap<>(); // freq - keys + private Map iter = new HashMap<>(); // key - key_pos in freq + + public LFUCache(int capacity) { + cap = capacity; + } + + public int get(int key) { + if (!m.containsKey(key)) return -1; + freq.get(m.get(key).getValue()).remove((int)iter.get(key)); + m.put(key, new Pair(m.get(key).getKey(), m.get(key).getValue()+1)); + if (!freq.containsKey(m.get(key).getValue())) + freq.put(m.get(key).getValue(), new ArrayList<>()); + freq.get(m.get(key).getValue()).add(key); + iter.put(key, freq.get(m.get(key).getValue()).size()-1); + if (freq.get(minFreq).size() == 0) ++minFreq; + return m.get(key).getKey(); + } + + public void put(int key, int value) { + if (cap <= 0) return; + if (get(key) != -1) { + m.put(key, new Pair(value, 1)); + return; + } + if (m.size() >= cap) { + m.remove(freq.get(minFreq).get(0)); + iter.remove(freq.get(minFreq).get(0)); + freq.get(minFreq).remove(0); + } + m.put(key, new Pair(value, 1)); + if (!freq.containsKey(1)) freq.put(1, new ArrayList<>()); + freq.get(1).add(key); + iter.put(key, freq.get(1).size() - 1); + minFreq = 1; + } + + public static void main(String[] args) { + LFUCache cache = new LFUCache( 2 /* capacity */ ); + cache.put(1, 1); + cache.put(2, 2); + System.out.println(cache.get(1)); // returns 1 + cache.put(3, 3); // evicts key 2 + System.out.println(cache.get(2)); // returns -1 (not found) + System.out.println(cache.get(3)); // returns 3. + cache.put(4, 4); // evicts key 1. + System.out.println(cache.get(1)); // returns -1 (not found) + System.out.println(cache.get(3)); // returns 3 + System.out.println(cache.get(4)); // returns 4 + } + +} diff --git a/src/main/java/count_of_range_sum/CountOfRangeSum.java b/src/main/java/count_of_range_sum/CountOfRangeSum.java index a264905..fb5cfa8 100644 --- a/src/main/java/count_of_range_sum/CountOfRangeSum.java +++ b/src/main/java/count_of_range_sum/CountOfRangeSum.java @@ -17,8 +17,8 @@ public int countRangeSum(int[] nums, int lower, int upper) { // j是第一个满足 sums[j] - sums[i] > upper 的下标 // k是第一个满足 sums[k] - sums[i] >= lower 的下标 - // cache用于缓存merge sort结果 - + // cache用于缓存merge sort结果(len=t)最后替换sums + private int countAndMergeSort(long[] sums, int start, int end, int lower, int upper) { if (end - start <= 1) return 0; int mid = start + (end - start) / 2; diff --git a/src/main/java/max_xor_two_numbers_in_array/MaxXorTwoNumbersInArray.java b/src/main/java/max_xor_two_numbers_in_array/MaxXorTwoNumbersInArray.java new file mode 100644 index 0000000..a459789 --- /dev/null +++ b/src/main/java/max_xor_two_numbers_in_array/MaxXorTwoNumbersInArray.java @@ -0,0 +1,39 @@ +package max_xor_two_numbers_in_array; + +import java.util.HashSet; +import java.util.Set; + +/** + * Created by lxie on 8/31/18. + */ +public class MaxXorTwoNumbersInArray { + + public class Solution { + + public int findMaximumXOR(int[] nums) { + int res = 0, mask = 0; + for (int i = 31; i >= 0; --i) { + mask |= (1 << i); + Set s = new HashSet<>(); + for (int num : nums) { + s.add(num & mask); + } + int t = res | (1 << i); + for (int prefix : s) { + if (s.contains(t ^ prefix)) { + res = t; + break; + } + } + } + return res; + } + } + + public class UnitTest { + + + + } + +} From 1cbb6b7dd3b0b11f474882ae02661090ffaf1374 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 31 Aug 2018 13:06:33 -0700 Subject: [PATCH 379/456] add sequence_reconstruction --- .../SequenceReconstruction.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/sequence_reconstruction/SequenceReconstruction.java diff --git a/src/main/java/sequence_reconstruction/SequenceReconstruction.java b/src/main/java/sequence_reconstruction/SequenceReconstruction.java new file mode 100644 index 0000000..f645c32 --- /dev/null +++ b/src/main/java/sequence_reconstruction/SequenceReconstruction.java @@ -0,0 +1,38 @@ +package sequence_reconstruction; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 8/31/18. + */ +public class SequenceReconstruction { + + public class Solution { + public boolean sequenceReconstruction(int[] org, int[][] seqs) { + Map m = new HashMap<>(); + Map pre = new HashMap<>(); + for (int i = 0; i < org.length; ++i) m.put(org[i], i); + for (int[] seq : seqs) { + for (int i = 0; i < seq.length; ++i) { + if (!m.containsKey(seq[i])) return false; + if (i > 0 && m.get(seq[i - 1]) >= m.get(seq[i])) return false; + if (!pre.containsKey(seq[i])) { + pre.put(seq[i], (i > 0) ? m.get(seq[i - 1]) : -1); + } else { + pre.put(seq[i], Math.max(pre.get(seq[i]), (i > 0) ? m.get(seq[i - 1]) : -1)); + } + } + } + for (int i = 0; i < org.length; ++i) { + if (pre.get(org[i]) != i - 1) return false; + } + return true; + } + } + + public class UnitTest { + + } + +} From 77234deed4c2f6b730984f5e85c8170c06973214 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 1 Sep 2018 13:54:50 -0700 Subject: [PATCH 380/456] add design_search_autocomplete_system --- .../SearchAutoComplete.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/main/java/design_search_autocomplete_system/SearchAutoComplete.java diff --git a/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java b/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java new file mode 100644 index 0000000..e8e1e06 --- /dev/null +++ b/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java @@ -0,0 +1,64 @@ +package design_search_autocomplete_system; + +import javafx.util.Pair; + +import java.util.*; + +/** + * Created by lxie on 9/1/18. + */ +public class SearchAutoComplete { + + public Map freq = new HashMap<>(); + public String data = null; + + public void SearchAutoComplete(String[] sentences, int[] times) { + for (int i = 0; i < sentences.length; ++i) { + if (freq.containsKey(sentences[i])) + freq.put(sentences[i], freq.get(sentences[i])+times[i]); + else + freq.put(sentences[i], times[i]); + } + data = ""; + } + + public List input(char c) { + if (c == '#') { + if (freq.containsKey(data)) + freq.put(data, freq.get(data)+1); + else + freq.put(data, 1); + data = ""; + return null; + } + data += c; + PriorityQueue> q = new PriorityQueue<>(50, new Comparator>() { + @Override + public int compare(Pair o1, Pair o2) { + if (o1.getValue() != o2.getValue()) + return o1.getValue() - o1.getValue(); + else + return o1.getKey().compareTo(o2.getKey()); + }}); + + for (Map.Entry f : freq.entrySet()) { + boolean matched = true; + for (int i = 0; i < data.length(); ++i) { + if (data.toCharArray()[i] != f.getKey().toCharArray()[i]) { + matched = false; + break; + } + } + if (matched) { + q.add(new Pair(f.getKey(), f.getValue())); + if (q.size() > 3) q.poll(); + } + } + List res = new ArrayList<>(); + for (int i = q.size() - 1; i >= 0; --i) { + res.add(q.peek().getKey()); q.poll(); + } + return res; + } + +} From e95036feffe944632932795850209c3bdf941605 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 1 Sep 2018 16:59:13 -0700 Subject: [PATCH 381/456] add next_greater_element_ii --- .../NextGreaterElementII.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/next_greater_element_ii/NextGreaterElementII.java diff --git a/src/main/java/next_greater_element_ii/NextGreaterElementII.java b/src/main/java/next_greater_element_ii/NextGreaterElementII.java new file mode 100644 index 0000000..3ee802a --- /dev/null +++ b/src/main/java/next_greater_element_ii/NextGreaterElementII.java @@ -0,0 +1,33 @@ +package next_greater_element_ii; + +import java.util.Arrays; +import java.util.Stack; + +/** + * Created by lxie on 9/1/18. + */ +public class NextGreaterElementII { + + public class Solution { + public int[] nextGreaterElements(int[] nums) { + int n = nums.length; + int[] res = new int[n]; Arrays.fill(res, -1); + Stack st = new Stack<>(); + for (int i = 0; i < 2 * n; ++i) { + int num = nums[i % n]; + while (!st.empty() && nums[st.peek()] < num) { + res[st.peek()] = num; st.pop(); + } + if (i < n) st.push(i); // when i>n-1, we seek next larger for those in stack only + } + return res; + } + } + + public class UnitTest { + + + + } + +} From 88ad203a70a99eafa4c67855db9a54fc7e8a2cfd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 1 Sep 2018 17:38:40 -0700 Subject: [PATCH 382/456] add find_mode_in_bst --- .../java/find_mode_in_bst/FindModeInBST.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/find_mode_in_bst/FindModeInBST.java diff --git a/src/main/java/find_mode_in_bst/FindModeInBST.java b/src/main/java/find_mode_in_bst/FindModeInBST.java new file mode 100644 index 0000000..d26b556 --- /dev/null +++ b/src/main/java/find_mode_in_bst/FindModeInBST.java @@ -0,0 +1,49 @@ +package find_mode_in_bst; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +/** + * Created by lxie on 9/1/18. + */ +public class FindModeInBST { + + public class Solution { + + public int[] findMode(TreeNode root) { + if (root == null) return new int[0]; + List res = new ArrayList<>(); + TreeNode p = root, pre = null; + Stack s = new Stack<>(); + int mx = 0, cnt = 1;; + while (!s.isEmpty() || p != null) { + while (p != null) { + s.push(p); + p = p.left; + } + p = s.peek(); s.pop(); + if (pre != null) { + cnt = (p.val == pre.val) ? cnt + 1 : 1; + } + if (cnt >= mx) { + if (cnt > mx) res.clear(); + res.add(p.val); + mx = cnt; + } + pre = p; + p = p.right; + } + return res.stream().mapToInt(i->i).toArray(); + } + + } + + public class UnitTest { + + + } + +} From 47a938f3db9eb44194efbc34919fc381ca33bd85 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 2 Sep 2018 07:56:52 -0700 Subject: [PATCH 383/456] remove_k_digits --- .../java/remove_k_digits/RemoveKDigits.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/remove_k_digits/RemoveKDigits.java diff --git a/src/main/java/remove_k_digits/RemoveKDigits.java b/src/main/java/remove_k_digits/RemoveKDigits.java new file mode 100644 index 0000000..3b180ff --- /dev/null +++ b/src/main/java/remove_k_digits/RemoveKDigits.java @@ -0,0 +1,32 @@ +package remove_k_digits; + +/** + * Created by lxie on 9/1/18. + */ +public class RemoveKDigits { + + public class Solution { + + public String removeKdigits(String num, int k) { + String res = ""; + int n = num.length(), keep = n - k; + for (char c : num.toCharArray()) { + while (k != 0 && res.length() != 0 && res.charAt(res.length()-1) > c) { + res = res.substring(0, res.length()-1); + --k; // remove at most k numbers + } + res += c; + } + res = res.substring(0, keep); + while (res.length() != 0 && res.charAt(0) == '0') res = res.substring(1); + return res.isEmpty() ? "0" : res; + } + + } + + public class UnitTest { + + } + + +} From ab53ac83a06fbe244a40cb586729abe64a035014 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 2 Sep 2018 09:42:34 -0700 Subject: [PATCH 384/456] add linked_list_random_node --- .../LinkedListRandomNode.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/linked_list_random_node/LinkedListRandomNode.java diff --git a/src/main/java/linked_list_random_node/LinkedListRandomNode.java b/src/main/java/linked_list_random_node/LinkedListRandomNode.java new file mode 100644 index 0000000..570d0e4 --- /dev/null +++ b/src/main/java/linked_list_random_node/LinkedListRandomNode.java @@ -0,0 +1,37 @@ +package linked_list_random_node; + +import common.ListNode; + +import java.util.Random; + +/** + * Created by lxie on 9/2/18. + */ +public class LinkedListRandomNode { + + public class Solution { + + private ListNode head = null; + + public Solution(ListNode head) { + this.head = head; + } + + public int getRandom() { + int res = head.val, i = 2; + ListNode cur = head.next; + Random generator = new Random(); + while (cur != null) { + int j = generator.nextInt(i); // reservior sampling size = 1 + if (j == 0) res = cur.val; + ++i; + cur = cur.next; + } + return res; + } + } + + public class UnitTest { + + } +} From 2d25bdc99c712799841c37ede7f6c39e9b5fdfa9 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 2 Sep 2018 15:11:53 -0700 Subject: [PATCH 385/456] add heaters --- src/main/java/heaters/Heaters.java | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/heaters/Heaters.java diff --git a/src/main/java/heaters/Heaters.java b/src/main/java/heaters/Heaters.java new file mode 100644 index 0000000..bc47e67 --- /dev/null +++ b/src/main/java/heaters/Heaters.java @@ -0,0 +1,32 @@ +package heaters; + +import java.util.Arrays; + +/** + * Created by lxie on 9/2/18. + */ +public class Heaters { + + public class Solution { + + public int findRadius(int[] houses, int[] heaters) { + int n = heaters.length, j = 0, res = 0; + Arrays.sort(houses); + Arrays.sort(heaters); + for (int i = 0; i < houses.length; ++i) { + int cur = houses[i]; + while (j < n - 1 && Math.abs(heaters[j + 1] - cur) <= Math.abs(heaters[j] - cur)) { + ++j; + } + res = Math.max(res, Math.abs(heaters[j] - cur)); + } + return res; + } + + } + + public class UnitTest { + + } + +} From 4171f8e927088ac0cd5bc580b9682ce65df61ca7 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 3 Sep 2018 15:27:19 -0700 Subject: [PATCH 386/456] add repeated_substring_pattern --- .../RepeatedSubstringPattern.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/repeated_substring_pattern/RepeatedSubstringPattern.java diff --git a/src/main/java/repeated_substring_pattern/RepeatedSubstringPattern.java b/src/main/java/repeated_substring_pattern/RepeatedSubstringPattern.java new file mode 100644 index 0000000..8140698 --- /dev/null +++ b/src/main/java/repeated_substring_pattern/RepeatedSubstringPattern.java @@ -0,0 +1,32 @@ +package repeated_substring_pattern; + +/** + * Created by lxie on 9/3/18. + */ +public class RepeatedSubstringPattern { + + public class Solution { + + public boolean repeatedSubstringPattern(String str) { + int n = str.length(); + for (int i = n / 2; i >= 1; --i) { + if (n % i == 0) { + int c = n / i; + String t = ""; + for (int j = 0; j < c; ++j) { + t += str.substring(0, i); + } + if (t.compareTo(str) == 0) return true; + } + } + return false; + } + } + + public class UnitTest { + + + } + + +} From c3afd5d5b9424ed24d4b32ad7d9058483ee31ada Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 3 Sep 2018 18:26:53 -0700 Subject: [PATCH 387/456] add zero_one_matrix --- .../java/zero_one_matrix/ZeroOneMatrix.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/zero_one_matrix/ZeroOneMatrix.java diff --git a/src/main/java/zero_one_matrix/ZeroOneMatrix.java b/src/main/java/zero_one_matrix/ZeroOneMatrix.java new file mode 100644 index 0000000..040d90a --- /dev/null +++ b/src/main/java/zero_one_matrix/ZeroOneMatrix.java @@ -0,0 +1,44 @@ +package zero_one_matrix; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by lxie on 9/3/18. + */ +public class ZeroOneMatrix { + + public class Solution { + + public int[][] updateMatrix(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int[][] dirs = {{0,-1},{-1,0},{0,1},{1,0}}; + Queue q = new LinkedList<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == 0) q.add(new int[]{i, j}); + else matrix[i][j] = Integer.MAX_VALUE; + } + } + while (!q.isEmpty()) { + int[] t = q.peek(); q.poll(); + for (int[] dir : dirs) { + int x = t[0] + dir[0], y = t[1] + dir[1]; + if (x < 0 || x >= m || y < 0 || y >= n || + matrix[x][y] <= matrix[t[0]][t[1]]) continue; + matrix[x][y] = matrix[t[0]][t[1]] + 1; + q.add(new int[]{x, y}); + } + } + return matrix; + } + } + + public class UnitTest { + + + + } + + +} From e0bf0bfa82f67087437203097b87cb9ac636766f Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 4 Sep 2018 07:27:08 -0700 Subject: [PATCH 388/456] add predict_the_winner --- .../predict_the_winner/PredictTheWinner.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/predict_the_winner/PredictTheWinner.java diff --git a/src/main/java/predict_the_winner/PredictTheWinner.java b/src/main/java/predict_the_winner/PredictTheWinner.java new file mode 100644 index 0000000..49490f9 --- /dev/null +++ b/src/main/java/predict_the_winner/PredictTheWinner.java @@ -0,0 +1,33 @@ +package predict_the_winner; + +import java.util.Arrays; + +/** + * Created by lxie on 9/4/18. + */ +public class PredictTheWinner { + + public class Solution { + + public boolean PredictTheWinner(int[] nums) { + int n = nums.length; + int[][] dp = new int[n][n]; + for(int[] a : dp) Arrays.fill(a, -1); + return canWin(nums, 0, n - 1, dp) >= 0; + } + + private int canWin(int[] nums, int s, int e, int[][] dp) { + if (dp[s][e] == -1) { + dp[s][e] = (s == e) ? nums[s] : + Math.max(nums[s] - canWin(nums, s + 1, e, dp), nums[e] - canWin(nums, s, e - 1, dp)); + } + return dp[s][e]; + } + + } + + public class UnitTest { + + + } +} From 9cbc96ae7a1cc3acd27eb9ac340956bd45435d9a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 5 Sep 2018 08:01:25 -0700 Subject: [PATCH 389/456] add valid_word_abbrev --- .../valid_word_abbrev/ValidWordAbbrev.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/valid_word_abbrev/ValidWordAbbrev.java diff --git a/src/main/java/valid_word_abbrev/ValidWordAbbrev.java b/src/main/java/valid_word_abbrev/ValidWordAbbrev.java new file mode 100644 index 0000000..411b1db --- /dev/null +++ b/src/main/java/valid_word_abbrev/ValidWordAbbrev.java @@ -0,0 +1,32 @@ +package valid_word_abbrev; + +/** + * Created by lxie on 9/5/18. + */ +public class ValidWordAbbrev { + + public class Solution { + + public boolean validWordAbbreviation(String word, String abbr) { + int i = 0, j = 0, m = word.length(), n = abbr.length(); + while (i < m && j < n) { + if (abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') { + if (abbr.charAt(j) == '0') return false; + int val = 0; + while (j < n && abbr.charAt(j) >= '0' && abbr.charAt(j) <= '9') { + val = val * 10 + abbr.charAt(j++) - '0'; + } + i += val; + } else { + if (word.charAt(i++) != abbr.charAt(j++)) return false; + } + } + return i == m && j == n; + } + } + + public class UnitTest { + + } + +} From 836d8567cfb701f9d0737a37458c5ec5a65fdaee Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 6 Sep 2018 09:17:50 -0700 Subject: [PATCH 390/456] add create_max_number --- .../create_max_number/CreateMaxNumber.java | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/main/java/create_max_number/CreateMaxNumber.java diff --git a/src/main/java/create_max_number/CreateMaxNumber.java b/src/main/java/create_max_number/CreateMaxNumber.java new file mode 100644 index 0000000..2775616 --- /dev/null +++ b/src/main/java/create_max_number/CreateMaxNumber.java @@ -0,0 +1,80 @@ +package create_max_number; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 9/5/18. + */ +public class CreateMaxNumber { + + public static class Solution { + + public int[] maxNumber(int[] nums1, int[] nums2, int k) { + int m = nums1.length, n = nums2.length; + int[] res = {}; + for (int i = Math.max(0, k - n); i <= Math.min(k, m); ++i) { + // constraint: k-i <= n, i <=m, i = [0, k] + int[] merged = mergeVector(maxVector(nums1, i), maxVector(nums2, k - i)); + res = maxArray(res, merged) == 0 ? res : merged; + } + return res; + } + + private int[] maxVector(int[] nums, int k) { + int drop = nums.length - k; + List res = new ArrayList<>(); + for (int num : nums) { + while (drop != 0 && res.size() != 0 && res.get(res.size()-1) < num) { + res.remove(res.size()-1); + --drop; + } + res.add(num); + } + res = res.subList(0, k); + return res.stream().mapToInt(i->i).toArray(); + } + + private int[] mergeVector(int[] nums1, int[] nums2) { // just a merge sort + List res = new ArrayList<>(); + int i = 0, j = 0; + while (i < nums1.length && j < nums2.length) { + if (maxArray(Arrays.copyOfRange(nums1, i, nums1.length), + Arrays.copyOfRange(nums2, j, nums2.length)) == 0) { + res.add(nums1[i++]); + } else { + res.add(nums2[j++]); + } + } + + if (i < nums1.length) { + for (int k = i; k < nums1.length; ++k) res.add(nums1[k]); + } else { + for (int k = j; k < nums2.length; ++k) res.add(nums2[k]); + } + + return res.stream().mapToInt(m->m).toArray(); + } + + private int maxArray(int[] a, int[] b) { + int i = 0, j = 0; + while (i < a.length && j < b.length) { + if (a[i] > b[j]) return 0; + else if(a[i] < b[j]) return 1; + i++; j++; + } + if(i == a.length) return 1; + else return 0; + } + } + + public static void main(String[] args) { + Solution sol = new Solution(); + int[] a = {6,7}; + int[] b = {6,0,4}; + int[] res = sol.maxNumber(a, b, 5); + System.out.println(res); + } + +} From 88941d01b1ffb00d8f7594bddf24b0f83b01f923 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 8 Sep 2018 14:48:18 -0700 Subject: [PATCH 391/456] add minimum_absolute_diff_bst --- .../MinAbsoluteDiffBst.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/minimum_absolute_diff_bst/MinAbsoluteDiffBst.java diff --git a/src/main/java/minimum_absolute_diff_bst/MinAbsoluteDiffBst.java b/src/main/java/minimum_absolute_diff_bst/MinAbsoluteDiffBst.java new file mode 100644 index 0000000..6b99dbd --- /dev/null +++ b/src/main/java/minimum_absolute_diff_bst/MinAbsoluteDiffBst.java @@ -0,0 +1,33 @@ +package minimum_absolute_diff_bst; + +import common.TreeNode; + +/** + * Created by lxie on 9/8/18. + */ +public class MinAbsoluteDiffBst { + + public class Solution { + + public int getMinimumDifference(TreeNode root) { + int res[] = {Integer.MAX_VALUE}, pre[] = {-1}; + inorder(root, pre, res); + return res[0]; + } + + private void inorder(TreeNode root, int[] pre, int[] res) { + if (root == null) return; + inorder(root.left, pre, res); + if (pre[0] != -1) res[0] = Math.min(res[0], root.val - pre[0]); + pre[0] = root.val; + inorder(root.right, pre, res); + } + + } + + public class UnitTest { + + + + } +} From e466f3d791622e3964d025b05a2aae6a92bba1d1 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 9 Sep 2018 15:39:03 -0700 Subject: [PATCH 392/456] modify sort_chars_by_frequence --- .../SortCharsByFrequency.java | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java index 5674b6b..8328790 100644 --- a/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java +++ b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java @@ -1,7 +1,8 @@ package sort_chars_by_frequency; -import java.util.HashMap; -import java.util.Map; +import javafx.util.Pair; + +import java.util.*; /** * Created by lxie on 7/25/18. @@ -12,33 +13,36 @@ public class SortCharsByFrequency { public String frequencySort(String s) { String res = ""; - String[] v = new String[s.length()+1]; - for (int i=0; i> q = new PriorityQueue<>(100, + new Comparator>() { + @Override + public int compare(Pair o1, Pair o2) { + return o2.getKey() - o1.getKey(); + } + }); + Map m = new HashMap<>(); for (char c : s.toCharArray()) { - if (!m.containsKey(c)) { + if (m.containsKey(c)) + m.put(c, m.get(c) + 1); + else m.put(c, 1); - } else { - m.put(c, m.get(c)+1); - } } - for (Map.Entry a : m.entrySet()) { - for(int i=0; i 0; --i) { - if (!v[i].isEmpty()) { - res += v[i]; - } + for (Map.Entry a : m.entrySet()) + q.add(new Pair(a.getValue(), a.getKey())); + while (!q.isEmpty()) { + Pair t = q.peek(); q.poll(); + for (int i=0; i Date: Sun, 9 Sep 2018 23:48:11 -0700 Subject: [PATCH 393/456] add shopping_offers --- .../java/shopping_offers/ShoppingOffers.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/shopping_offers/ShoppingOffers.java diff --git a/src/main/java/shopping_offers/ShoppingOffers.java b/src/main/java/shopping_offers/ShoppingOffers.java new file mode 100644 index 0000000..5f4520d --- /dev/null +++ b/src/main/java/shopping_offers/ShoppingOffers.java @@ -0,0 +1,38 @@ +package shopping_offers; + +import java.util.List; + +/** + * Created by lxie on 9/9/18. + */ +public class ShoppingOffers { + + public class Solution { + + public int shoppingOffers(List price, List> special, List needs) { + int res = 0, n = price.size(); + for (int i = 0; i < n; ++i) { + res += price.get(i) * needs.get(i); + } + for (List offer : special) { + boolean isValid = true; + for (int j = 0; j < n; ++j) { + if (needs.get(j) - offer.get(j) < 0) isValid = false; + needs.set(j, needs.get(j) - offer.get(j)); + } + if (isValid) { + res = Math.min(res, shoppingOffers(price, special, needs) + offer.get(offer.size()-1)); + } + for (int j = 0; j < n; ++j) { + needs.set(j, needs.get(j) + offer.get(j)); // backtracking + } + } + return res; + } + } + + public class UnitTest { + + } + +} From 9698103262164f848477517b62ac8df2fd1202c4 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 10 Sep 2018 07:24:09 -0700 Subject: [PATCH 394/456] add smallest_bood_base --- .../smallest_good_base/SmallestGoodBase.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/smallest_good_base/SmallestGoodBase.java diff --git a/src/main/java/smallest_good_base/SmallestGoodBase.java b/src/main/java/smallest_good_base/SmallestGoodBase.java new file mode 100644 index 0000000..3b7e532 --- /dev/null +++ b/src/main/java/smallest_good_base/SmallestGoodBase.java @@ -0,0 +1,33 @@ +package smallest_good_base; + +/** + * Created by lxie on 9/10/18. + */ +public class SmallestGoodBase { + + public class Solution { + + public String smallestGoodBase(String n) { + long num = Long.parseLong(n); + for (int i = (int) (Math.log(num + 1) / Math.log(2)); i >= 2; --i) { // smallest base first: 2^m <= n + long left = 2, right = (long) Math.pow(num, 1.0 / (i - 1)) + 1; + while (left < right) { + long mid = left + (right - left) / 2, sum = 0; + for (int j = 0; j < i; ++j) { + sum = sum * mid + 1; + } + if (sum == num) return Long.toString(mid); + else if (sum < num) left = mid + 1; + else right = mid; + } + } + return Long.toString(num - 1); + } + } + + public class UnitTest { + + + } + +} From 9e3dde71cdfcacd0686bfcf60e5ba375084bb503 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 10 Sep 2018 09:19:50 -0700 Subject: [PATCH 395/456] add magic_string --- src/main/java/magic_string/MagicString.java | 36 +++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/magic_string/MagicString.java diff --git a/src/main/java/magic_string/MagicString.java b/src/main/java/magic_string/MagicString.java new file mode 100644 index 0000000..2001039 --- /dev/null +++ b/src/main/java/magic_string/MagicString.java @@ -0,0 +1,36 @@ +package magic_string; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 9/10/18. + */ +public class MagicString { + + public class Solution { + + public int magicalString(int n) { + if (n <= 0) return 0; + if (n <= 3) return 1; + int res = 1, head = 2, tail = 3, num = 1; + List v = new ArrayList<>(Arrays.asList(1, 2, 2)); + while (tail < n) { + for (int i = 0; i < v.get(head); ++i) { + v.add(num); + if (num == 1 && tail < n) ++res; + ++tail; + } + num ^= 3; + ++head; + } + return res; + } + + } + + public class UnitTest { + + } +} From a311bb4f0c46baf88f3b02f56c0253ef5d05cfd5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 10 Sep 2018 15:46:53 -0700 Subject: [PATCH 396/456] add sliding_window_median --- .../SlidingWindowMedian.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/main/java/sliding_window_median/SlidingWindowMedian.java diff --git a/src/main/java/sliding_window_median/SlidingWindowMedian.java b/src/main/java/sliding_window_median/SlidingWindowMedian.java new file mode 100644 index 0000000..f9c5608 --- /dev/null +++ b/src/main/java/sliding_window_median/SlidingWindowMedian.java @@ -0,0 +1,75 @@ +package sliding_window_median; + +import com.google.common.primitives.Doubles; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +/** + * Created by lxie on 9/10/18. + */ +public class SlidingWindowMedian { + + public double[] medianSlidingWindow(int[] nums, int k) { + List res = new ArrayList<>(); + if (nums == null || nums.length == 0) { + return Doubles.toArray(res); + } + PriorityQueue minHeap = new PriorityQueue<>(); + PriorityQueue maxHeap = new PriorityQueue<>(new Comparator() { + public int compare(Integer x, Integer y) { + return y - x; + } + }); + + double curMedian; + if (k > 1) { + maxHeap.add(nums[0]); + for (int i = 1; i < k - 1; i++) { + int x = maxHeap.peek(); + if (nums[i] <= x) { + maxHeap.add(nums[i]); + } else { + minHeap.add(nums[i]); + } + } + curMedian = maxHeap.peek(); + } else { + curMedian = 0; + } + + for (int i = k - 1; i < nums.length; i++) { + if (nums[i] <= curMedian) { + maxHeap.add(nums[i]); + } else { + minHeap.add(nums[i]); + } + while (maxHeap.size() > minHeap.size()+1) { + minHeap.add(maxHeap.poll()); + } + while (maxHeap.size() < minHeap.size()) { + maxHeap.add(minHeap.poll()); + } + curMedian = maxHeap.peek(); + res.add(curMedian); + if (nums[i - k + 1] <= curMedian) { + maxHeap.remove(nums[i - k + 1]); + } else { + minHeap.remove(nums[i - k + 1]); + } + } + + return Doubles.toArray(res); + } + + public static void main(String[] args) { + SlidingWindowMedian s = new SlidingWindowMedian(); + int[] a = {1,3,-1,-3,5,3,6,7}; + double[] res = s.medianSlidingWindow(a, 3); + System.out.println(res); + + } + +} From d1b76821dd0074ef1af88012ed7df6461ef419ea Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 10 Sep 2018 21:03:19 -0700 Subject: [PATCH 397/456] add ones_and_zeroes --- .../java/ones_and_zeroes/OnesAndZeroes.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/ones_and_zeroes/OnesAndZeroes.java diff --git a/src/main/java/ones_and_zeroes/OnesAndZeroes.java b/src/main/java/ones_and_zeroes/OnesAndZeroes.java new file mode 100644 index 0000000..93572a7 --- /dev/null +++ b/src/main/java/ones_and_zeroes/OnesAndZeroes.java @@ -0,0 +1,37 @@ +package ones_and_zeroes; + +/** + * Created by lxie on 9/10/18. + */ +public class OnesAndZeroes { + + public class Solution { + + public int findMaxForm(String[] strs, int m, int n) { + int[][] dp = new int[m+1][n+1]; + for (String str : strs) { + int zeros = 0, ones = 0; + for (char c : str.toCharArray()) { + if (c == '0') ++zeros; + else + ++ones; + } + for (int i = m; i >= zeros; --i) { + for (int j = n; j >= ones; --j) { + dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1); + } + } + } + return dp[m][n]; + } + + + } + + public class UnitTest { + + + } + + +} From 8143d758e9c65352084311c022c86d58950dc3d5 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 13 Sep 2018 07:32:53 -0700 Subject: [PATCH 398/456] add redundant_connection_ii sliding_window_median system_dependencies --- .../RedundantConnectionII.java | 45 +++++ .../SlidingWindowMedian.java | 7 +- .../SystemDependencies.java | 187 ++++++++++++++++++ .../SystemDependenciesUnitTest.java | 139 +++++++++++++ 4 files changed, 373 insertions(+), 5 deletions(-) create mode 100644 src/main/java/redundant_connection_ii/RedundantConnectionII.java create mode 100644 src/main/java/system_dependencies/SystemDependencies.java create mode 100644 src/main/java/system_dependencies/SystemDependenciesUnitTest.java diff --git a/src/main/java/redundant_connection_ii/RedundantConnectionII.java b/src/main/java/redundant_connection_ii/RedundantConnectionII.java new file mode 100644 index 0000000..dbf8f11 --- /dev/null +++ b/src/main/java/redundant_connection_ii/RedundantConnectionII.java @@ -0,0 +1,45 @@ +package redundant_connection_ii; + +/** + * Created by lxie on 9/11/18. + */ +public class RedundantConnectionII { + + public class Solution { + + public int[] findRedundantDirectedConnection(int[][] edges) { + int n = edges.length; + int[] root = new int[n+1]; + int[] first = new int[2], second = new int[2]; + for (int[] edge : edges) { + if (root[edge[1]] == 0) { + root[edge[1]] = edge[0]; + } else { + first[0] = root[edge[1]]; first[1] = edge[1]; + second[0] = edge[0]; second[1] = edge[1]; + edge[1] = 0; + } + } + for (int i = 0; i <= n; ++i) root[i] = i; + for (int[] edge : edges) { + if (edge[1] == 0) continue; + int x = getRoot(root, edge[0]), y = getRoot(root, edge[1]); + if (x == y) return first[0] == 0 ? edge : first; + root[x] = y; + } + return second; + } + + private int getRoot(int[] root, int i) { + return i == root[i] ? i : getRoot(root, root[i]); + } + + + } + + public class UnitTest { + + + } + +} diff --git a/src/main/java/sliding_window_median/SlidingWindowMedian.java b/src/main/java/sliding_window_median/SlidingWindowMedian.java index f9c5608..15b43e5 100644 --- a/src/main/java/sliding_window_median/SlidingWindowMedian.java +++ b/src/main/java/sliding_window_median/SlidingWindowMedian.java @@ -2,10 +2,7 @@ import com.google.common.primitives.Doubles; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.PriorityQueue; +import java.util.*; /** * Created by lxie on 9/10/18. @@ -68,7 +65,7 @@ public static void main(String[] args) { SlidingWindowMedian s = new SlidingWindowMedian(); int[] a = {1,3,-1,-3,5,3,6,7}; double[] res = s.medianSlidingWindow(a, 3); - System.out.println(res); + System.out.println("result is " + Arrays.toString(res)); } diff --git a/src/main/java/system_dependencies/SystemDependencies.java b/src/main/java/system_dependencies/SystemDependencies.java new file mode 100644 index 0000000..28a86e2 --- /dev/null +++ b/src/main/java/system_dependencies/SystemDependencies.java @@ -0,0 +1,187 @@ +package system_dependencies; + +import java.util.*; + +import static system_dependencies.SystemDependencies.FileStatus.EXPLICITYLY_INSTALLED; +import static system_dependencies.SystemDependencies.FileStatus.IMPLICITYLY_INSTALLED; +import static system_dependencies.SystemDependencies.FileStatus.NOT_INSTALLED; + +/** + * The SystemDependencies program implements an application that + * supports file dependencies during file installations and + * removals. + * + * @author Liang Xie + * @version 1.0 + * @since 2018-09-12 + */ +public class SystemDependencies { + + public enum FileStatus + { + NOT_INSTALLED, EXPLICITYLY_INSTALLED, IMPLICITYLY_INSTALLED; + } + + private final int maxn =10000; // maximum 10000 files in total + private int cnt = 0; + /* a mapping between file name and id */ + public Map name2id = new HashMap<>(); + + public String[] name = new String[maxn]; + + /* file dependency graphs - depend on and depended on */ + public List> depend = new ArrayList<>(); // depend on + public List> depend2 = new ArrayList<>(); // depended on + + /* status array for the files */ + public FileStatus[] status = new FileStatus[maxn]; + + /* installed files in a list */ + public List installed = new ArrayList<>(); + + /* constructor */ + public SystemDependencies() { + for (int i = 0; i < maxn; ++i) { + this.depend.add(new ArrayList<>()); + this.depend2.add(new ArrayList<>()); + } + Arrays.fill(status, NOT_INSTALLED); + Arrays.fill(name, ""); + } + + /** + * This method is used to obtain an integer ID given the file + * name string. + * @param itemName file name string + * @return int returns an integer ID. + */ + public int getID(String itemName) { + if(!name2id.containsKey(itemName)) { + // create an integer ID if does not exist + name[++cnt] = itemName; + name2id.put(itemName, cnt); + } + return name2id.get(itemName); + + } + + /** + * This method is used to check if a file is needed by dependants + * @param item file ID + * @return boolean returns true if there is dependants on the file. + */ + public boolean needed(int item) { + for(int i = 0; i < depend2.get(item).size();i++) + if(status[depend2.get(item).get(i)] != NOT_INSTALLED) return true; + return false; + } + + /** + * This method is used to install a file given the current dependencies + * @param item file ID + * @param toplevel whether the file is at top-level + * @return void + */ + public void install(int item, boolean toplevel) { + if(status[item] == NOT_INSTALLED) { + // for all dependents call install (not toplevel) + for(int i = 0; i < depend.get(item).size();i++) { + install(depend.get(item).get(i), false); + } + System.out.println(" Installing " + name[item]); + // toplevel - explicitly installed + status[item] = toplevel ? EXPLICITYLY_INSTALLED : IMPLICITYLY_INSTALLED; + installed.add(item); + } + } + + /** + * This method is used to remove a file given the current dependencies + * @param item file ID + * @param toplevel whether the file is at top-level + * @return void + */ + public void remove(int item, boolean toplevel) { + /* remove the file that has no dependents and is at toplevel or + implicitly installed */ + if((toplevel || status[item] == IMPLICITYLY_INSTALLED) &&!needed(item)) { + status[item] = NOT_INSTALLED; + installed.remove(new Integer(item)); + System.out.println(" Removing " + name[item]); + + // for all dependents call remove (not toplevel) + for(int i = 0; i < depend.get(item).size();i++) { + remove(depend.get(item).get(i), false); + } + } + } + + /** + * This method prints out installed files according to the + * installation order + */ + public void list() { + for(int i = 0; i < installed.size(); i++) { + System.out.println(" " + name[installed.get(i)]); + } + } + + public static void main(String[] args) { + SystemDependencies sdep = new SystemDependencies(); + String line = "", cmd = ""; + + Scanner scanner = new Scanner(System.in); + while(true) { + line = scanner.nextLine(); + System.out.println(line); + String[] params = line.split(" "); + + /* cmd is END */ + if(params[0].equals("END")) break; + + /* cmd is LIST */ + if(params[0].equals("LIST")) sdep.list(); + else { + int i1 = sdep.getID(params[1]); + /* cmd is DEPEND */ + if(params[0].equals("DEPEND")) { + // add dependencies to the graphs + for(int i = 2; i < params.length; ++i) { + int i2 = sdep.getID(params[i]); + sdep.depend.get(i1).add(i2); + sdep.depend2.get(i2).add(i1); + } + } + /* cmd is INSTALL */ + else if(params[0].equals("INSTALL")) { + if(sdep.status[i1] != NOT_INSTALLED) + System.out.println(" " + params[1] + " is already installed."); + else + sdep.install(i1, true); + } + /* cmd is REMOVE */ + else { + if(sdep.status[i1] == NOT_INSTALLED) + System.out.println(" " + params[1] + " is not installed."); + else if(sdep.needed(i1)) + System.out.println(" " + params[1] +" is still needed."); + else sdep.remove(i1, true); + + } + + } + } + } + + + + + + + + + + + + +} diff --git a/src/main/java/system_dependencies/SystemDependenciesUnitTest.java b/src/main/java/system_dependencies/SystemDependenciesUnitTest.java new file mode 100644 index 0000000..16cc558 --- /dev/null +++ b/src/main/java/system_dependencies/SystemDependenciesUnitTest.java @@ -0,0 +1,139 @@ +package system_dependencies; + +import org.junit.Assert; +import org.junit.Test; + +import static system_dependencies.SystemDependencies.FileStatus.EXPLICITYLY_INSTALLED; +import static system_dependencies.SystemDependencies.FileStatus.IMPLICITYLY_INSTALLED; +import static system_dependencies.SystemDependencies.FileStatus.NOT_INSTALLED; + +/** + * Created by lxie on 9/12/18. + */ +public class SystemDependenciesUnitTest { + + SystemDependencies sdep = new SystemDependencies(); + + public SystemDependenciesUnitTest() { + setupDependencies(); + } + + @Test + public void testGetID(){ + // first id is TELNET(1) + int id = sdep.getID("TELNET"); + Assert.assertEquals(id, 1); + + // last id is HTML(6), 6 files in total + id = sdep.getID("HTML"); + Assert.assertEquals(id, 6); + + // add a new id = 7 for FIREWALL(7) + id = sdep.getID("FIREWALL"); + Assert.assertEquals(id, 7); + } + + @Test + public void testNeeded(){ + /* HTML(6) is needed by BROWSER(5) */ + sdep.install(5, true); + boolean res = sdep.needed(6); + Assert.assertEquals(res, true); + + /* FIREWALL(7) is not needed by anyone */ + res = sdep.needed(7); + Assert.assertEquals(res, false); + + /* a non-existing file id = 15 is not needed */ + res = sdep.needed(15); + Assert.assertEquals(res, false); + } + + @Test + public void testInstall(){ + /* install NETCARD(3) -> NETCARD(3) */ + sdep.install(3, true); + Assert.assertEquals(sdep.status[3], EXPLICITYLY_INSTALLED); + Assert.assertEquals(sdep.installed.contains(3), true); + + /* install TELNET(1) -> TCPIP(2), TELNET(1) */ + sdep.install(1, true); + Assert.assertEquals(sdep.status[2], IMPLICITYLY_INSTALLED); + Assert.assertEquals(sdep.installed.contains(2), true); + Assert.assertEquals(sdep.status[1], EXPLICITYLY_INSTALLED); + Assert.assertEquals(sdep.installed.contains(1), true); + + /* install a new file foo(7) -> foo(7) */ + int id = sdep.getID("foo"); + sdep.install(7, true); + Assert.assertEquals(sdep.status[7], EXPLICITYLY_INSTALLED); + Assert.assertEquals(sdep.installed.contains(7), true); + + /* install a file that already exists, nothing should change */ + sdep.install(7, true); + Assert.assertEquals(sdep.status[7], EXPLICITYLY_INSTALLED); + Assert.assertEquals(sdep.installed.contains(7), true); + + } + + @Test + public void testRemove(){ + + testInstall(); + + /* remove NETCARD(3) -> still needed by others */ + sdep.remove(3, true); + Assert.assertEquals(sdep.status[3], EXPLICITYLY_INSTALLED); + Assert.assertEquals(sdep.installed.contains(3), true); + + /* remove TELNET(1) -> removed TELNET(1), TCPIP(2)*/ + sdep.remove(1, true); + Assert.assertEquals(sdep.status[1], NOT_INSTALLED); + Assert.assertEquals(sdep.installed.contains(1), false); + // TCPIP implicitely installed is also removed (not needed by others) + Assert.assertEquals(sdep.status[2], NOT_INSTALLED); + Assert.assertEquals(sdep.installed.contains(2), false); + + /* remove foo(7) -> removed foo(7) */ + sdep.remove(7, true); + Assert.assertEquals(sdep.status[1], NOT_INSTALLED); + Assert.assertEquals(sdep.installed.contains(7), false); + + } + + /* this function sets up the dependency graphs */ + public void setupDependencies(){ + String[] depends = { "DEPEND TELNET TCPIP NETCARD", + "DEPEND TCPIP NETCARD", + "DEPEND DNS TCPIP NETCARD", + "DEPEND BROWSER TCPIP HTML"}; + for (String line : depends) { + String[] params = line.split(" "); + int i1 = sdep.getID(params[1]); + /* cmd is DEPEND */ + if(params[0].equals("DEPEND")) { + // add dependencies to the graphs + for(int i = 2; i < params.length; ++i) { + int i2 = sdep.getID(params[i]); + sdep.depend.get(i1).add(i2); + sdep.depend2.get(i2).add(i1); + } + } + } + + } + + + + + + + + + + + + + + +} From 57af40ad864ea838ac17cf88d2ace09551ff46f0 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 13 Sep 2018 08:46:18 -0700 Subject: [PATCH 399/456] add convex_polygon --- .../java/convex_polygon/ConvexPolygon.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/convex_polygon/ConvexPolygon.java diff --git a/src/main/java/convex_polygon/ConvexPolygon.java b/src/main/java/convex_polygon/ConvexPolygon.java new file mode 100644 index 0000000..6474268 --- /dev/null +++ b/src/main/java/convex_polygon/ConvexPolygon.java @@ -0,0 +1,30 @@ +package convex_polygon; + +/** + * Created by lxie on 9/13/18. + */ +public class ConvexPolygon { + + public class Solution { + + public boolean isConvex(int[][] points) { + int n = points.length; long pre = 0, cur = 0; + for (int i = 0; i < n; ++i) { + int dx1 = points[(i + 1) % n][0] - points[i][0]; + int dx2 = points[(i + 2) % n][0] - points[i][0]; + int dy1 = points[(i + 1) % n][1] - points[i][1]; + int dy2 = points[(i + 2) % n][1] - points[i][1]; + cur = dx1 * dy2 - dx2 * dy1; + if (cur != 0) { // ignore 0 case + if (cur * pre < 0) return false; + else pre = cur; + } + } + return true; + } + } + + public class UnitTest { + + } +} From 3a779d0db6f943d24a2ba68d6af8615c9cc9bc5a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 13 Sep 2018 08:54:00 -0700 Subject: [PATCH 400/456] add delete_ops_two_strings --- .../DeleteOpsTwoStrings.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/delete_ops_two_strings/DeleteOpsTwoStrings.java diff --git a/src/main/java/delete_ops_two_strings/DeleteOpsTwoStrings.java b/src/main/java/delete_ops_two_strings/DeleteOpsTwoStrings.java new file mode 100644 index 0000000..e0b7147 --- /dev/null +++ b/src/main/java/delete_ops_two_strings/DeleteOpsTwoStrings.java @@ -0,0 +1,33 @@ +package delete_ops_two_strings; + +/** + * Created by lxie on 9/13/18. + */ +public class DeleteOpsTwoStrings { + + public class Solution { + + public int minDistance(String word1, String word2) { + int n1 = word1.length(), n2 = word2.length(); + int[][] dp = new int[n1+1][n2+1]; + for (int i = 0; i <= n1; ++i) dp[i][0] = i; + for (int j = 0; j <= n2; ++j) dp[0][j] = j; + for (int i = 1; i <= n1; ++i) { + for (int j = 1; j <= n2; ++j) { + if (word1.charAt(i - 1) == word2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[n1][n2]; + } + } + + public class UnitTest { + + } + + +} From cf4137a919a3847dbe7ce2d1b6f39f318c35c828 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 13 Sep 2018 09:24:32 -0700 Subject: [PATCH 401/456] add shortest_unsorted_continuous_subarray --- .../ShortestUnsortedContinuousSubarray.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java diff --git a/src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java b/src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java new file mode 100644 index 0000000..1341819 --- /dev/null +++ b/src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java @@ -0,0 +1,29 @@ +package shortest_unsorted_continuous_subarray; + +/** + * Created by lxie on 9/13/18. + */ +public class ShortestUnsortedContinuousSubarray { + + public class Solution { + + public int findUnsortedSubarray(int[] nums) { + int n = nums.length, start = -1, end = -2; + int mn = nums[n - 1], mx = nums[0]; + for (int i = 1; i < n; ++i) { + mx = Math.max(mx, nums[i]); + mn = Math.min(mn, nums[n - 1 - i]); + if (mx > nums[i]) end = i; + if (mn < nums[n - 1 - i]) start = n - 1 - i; + } + return end - start + 1; + } + } + + public class UnitTest { + + } + + + +} From 54d404b906df3c89ec88b17aa302a3c489453751 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 13 Sep 2018 12:23:52 -0700 Subject: [PATCH 402/456] add max_sum_3_nonoverlapping_subarrays --- .../Sum3NonOverlappingSubarrays.java | 57 +++++++++++++++++++ .../ShortestUnsortedContinuousSubarray.java | 2 - 2 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java diff --git a/src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java b/src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java new file mode 100644 index 0000000..2e158ee --- /dev/null +++ b/src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java @@ -0,0 +1,57 @@ +package max_sum_3_nonoverlapping_subarrays; + +import java.util.Arrays; + +/** + * Created by lxie on 9/13/18. + */ +public class Sum3NonOverlappingSubarrays { + + public class Solution { + + public int[] maxSumOfThreeSubarrays(int[] nums, int k) { + int n = nums.length, mx = Integer.MIN_VALUE; + int[] sums = new int[n+1]; + int[] res = new int[3]; + int[] left = new int[n]; + int[] right = new int[n]; Arrays.fill(right, n-k); + for (int i = 0; i < n; ++i) sums[i+1] = sums[i] + nums[i]; // sums[0] = 0 + + for (int i = k, total = sums[k] - sums[0]; i < n; ++i) { + if (sums[i + 1] - sums[i + 1 - k] > total) { + left[i] = i + 1 - k; + total = sums[i + 1] - sums[i + 1 - k]; + } else { + left[i] = left[i - 1]; + } + } + for (int i = n - 1 - k, total = sums[n] - sums[n - k]; i >= 0; --i) { + if (sums[i + k] - sums[i] >= total) { + right[i] = i; + total = sums[i + k] - sums[i]; + } else { + right[i] = right[i + 1]; + } + } + for (int i = k; i <= n - 2 * k; ++i) { + int l = left[i - 1], r = right[i + k]; + int total = (sums[i + k] - sums[i]) + (sums[l + k] - sums[l]) + (sums[r + k] - sums[r]); + if (mx < total) { + mx = total; + res[0] = l; res[1] = i; res[2] = r; + } + } + return res; + } + + + + + } + + public class UnitTest { + + + } + +} diff --git a/src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java b/src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java index 1341819..4a407a6 100644 --- a/src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java +++ b/src/main/java/shortest_unsorted_continuous_subarray/ShortestUnsortedContinuousSubarray.java @@ -24,6 +24,4 @@ public class UnitTest { } - - } From d6f863655f8709b2507344f1525df4841cc6e218 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 14 Sep 2018 01:20:36 -0700 Subject: [PATCH 403/456] add longest_line_consecutive_one_in_matrix --- .../LongestLineConsecutiveOneInMatrix.java | 37 +++++++++++++++++++ .../Sum3NonOverlappingSubarrays.java | 1 + 2 files changed, 38 insertions(+) create mode 100644 src/main/java/longest_line_consecutive_one_in_matrix/LongestLineConsecutiveOneInMatrix.java diff --git a/src/main/java/longest_line_consecutive_one_in_matrix/LongestLineConsecutiveOneInMatrix.java b/src/main/java/longest_line_consecutive_one_in_matrix/LongestLineConsecutiveOneInMatrix.java new file mode 100644 index 0000000..c922968 --- /dev/null +++ b/src/main/java/longest_line_consecutive_one_in_matrix/LongestLineConsecutiveOneInMatrix.java @@ -0,0 +1,37 @@ +package longest_line_consecutive_one_in_matrix; + +import static java.lang.Math.max; + +/** + * Created by lxie on 9/14/18. + */ +public class LongestLineConsecutiveOneInMatrix { + + public class Solution { + + public int longestLine(int[][] M) { + if (M.length == 0 || M[0].length == 0) return 0; + int m = M.length, n = M[0].length, res = 0; + int[][][] dp = new int[m][n][4]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (M[i][j] == 0) continue; + for (int k = 0; k < 4; ++k) dp[i][j][k] = 1; + if (j > 0) dp[i][j][0] += dp[i][j - 1][0]; // horizonal + if (i > 0) dp[i][j][1] += dp[i - 1][j][1]; // vertical + if (i > 0 && j < n - 1) dp[i][j][2] += dp[i - 1][j + 1][2]; // diagonal + if (i > 0 && j > 0) dp[i][j][3] += dp[i - 1][j - 1][3]; // anti-diagonal + res = max(res, max(dp[i][j][0], dp[i][j][1])); + res = max(res, max(dp[i][j][2], dp[i][j][3])); + } + } + return res; + } + } + + public class UnitTest { + + + } + +} diff --git a/src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java b/src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java index 2e158ee..fd7383f 100644 --- a/src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java +++ b/src/main/java/max_sum_3_nonoverlapping_subarrays/Sum3NonOverlappingSubarrays.java @@ -35,6 +35,7 @@ public int[] maxSumOfThreeSubarrays(int[] nums, int k) { } for (int i = k; i <= n - 2 * k; ++i) { int l = left[i - 1], r = right[i + k]; + // total = left_largest + current + right_largest int total = (sums[i + k] - sums[i]) + (sums[l + k] - sums[l]) + (sums[r + k] - sums[r]); if (mx < total) { mx = total; From 54921eaad0bf93e2a53f493e323edd9cb0abe9fc Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 14 Sep 2018 10:11:09 -0700 Subject: [PATCH 404/456] add subarray_sum_equals_k --- .../SubarraySumEqualsK.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/SubarraySumEqualsK/SubarraySumEqualsK.java diff --git a/src/main/java/SubarraySumEqualsK/SubarraySumEqualsK.java b/src/main/java/SubarraySumEqualsK/SubarraySumEqualsK.java new file mode 100644 index 0000000..83349e6 --- /dev/null +++ b/src/main/java/SubarraySumEqualsK/SubarraySumEqualsK.java @@ -0,0 +1,37 @@ +package SubarraySumEqualsK; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 9/14/18. + */ +public class SubarraySumEqualsK { + + public class Solution { + + public int subarraySum(int[] nums, int k) { + int res = 0, sum = 0, n = nums.length; + Map m = new HashMap<>(); + m.put(0, 1); + + for (int i = 0; i < n; ++i) { + sum += nums[i]; + if (m.containsKey(sum - k)) { + res += m.get(sum - k); + } + if (m.containsKey(sum)) { + m.put(sum, m.get(sum)+1); + } else { + m.put(sum, 1); + } + } + return res; + } + } + + public class UnitTest { + + } + +} From 97200ebfef4e980f1733ecc2d057c45ac93c638a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 14 Sep 2018 10:13:16 -0700 Subject: [PATCH 405/456] move dir --- .../SubarraySumEqualsK.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/main/java/{SubarraySumEqualsK => subarray_sum_equal_k}/SubarraySumEqualsK.java (100%) diff --git a/src/main/java/SubarraySumEqualsK/SubarraySumEqualsK.java b/src/main/java/subarray_sum_equal_k/SubarraySumEqualsK.java similarity index 100% rename from src/main/java/SubarraySumEqualsK/SubarraySumEqualsK.java rename to src/main/java/subarray_sum_equal_k/SubarraySumEqualsK.java From 322ce613d72b590924c03ad574047c5fb5993b47 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 15 Sep 2018 08:03:27 -0700 Subject: [PATCH 406/456] add student_attendence_record_ii --- .../StudentAttendanceRecordII.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/student_attendance_record_ii/StudentAttendanceRecordII.java diff --git a/src/main/java/student_attendance_record_ii/StudentAttendanceRecordII.java b/src/main/java/student_attendance_record_ii/StudentAttendanceRecordII.java new file mode 100644 index 0000000..cf8ea28 --- /dev/null +++ b/src/main/java/student_attendance_record_ii/StudentAttendanceRecordII.java @@ -0,0 +1,34 @@ +package student_attendance_record_ii; + +/** + * Created by lxie on 9/15/18. + */ +public class StudentAttendanceRecordII { + + public class Solution { + + public int checkRecord(int n) { + int M = 1000000007; + long[] P = new long[n + 1]; + long[] PorL = new long[n + 1]; + + P[0] = 1; PorL[0] = 1; PorL[1] = 2; + for (int i = 1; i <= n; ++i) { + P[i] = PorL[i - 1]; + if (i > 1) PorL[i] = (P[i] + P[i - 1] + P[i - 2]) % M; + } + long res = PorL[n]; + // now we consider A + for (int i = 0; i < n; ++i) { + long t = (PorL[i] * PorL[n - 1 - i]) % M; + res = (res + t) % M; + } + return (int) res; + } + } + + public class UnitTest { + + + } +} From 79eae6ec6115f38188eca3fcef551dc74e4cd86e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 15 Sep 2018 10:11:35 -0700 Subject: [PATCH 407/456] implement_magic_dictionary --- .../MagicDictionary.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/implement_magic_dictionary/MagicDictionary.java diff --git a/src/main/java/implement_magic_dictionary/MagicDictionary.java b/src/main/java/implement_magic_dictionary/MagicDictionary.java new file mode 100644 index 0000000..adb6ee8 --- /dev/null +++ b/src/main/java/implement_magic_dictionary/MagicDictionary.java @@ -0,0 +1,43 @@ +package implement_magic_dictionary; + +import java.util.HashSet; +import java.util.Set; + +/** + * Created by lxie on 9/15/18. + */ +public class MagicDictionary { + + private Set s = new HashSet<>(); + + /** Build a dictionary through a list of words */ + public void buildDict(String[] dict) { + for (String word : dict) s.add(word); + } + + /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ + boolean search(String word) { + char[] word1 = word.toCharArray(); + for (int i = 0; i < word1.length; ++i) { + char t = word1[i]; + for (char c = 'a'; c <= 'z'; ++c) { + if (c == t) continue; + word1[i] = c; + if (s.contains(new String(word1))) return true; + } + word1[i] = t; + } + return false; + } + + public static void main(String[] args) { + MagicDictionary m = new MagicDictionary(); + String[] dict = {"hello", "leetcode"}; + m.buildDict(dict); + System.out.println(m.search("hello")); + System.out.println(m.search("hhllo")); + System.out.println(m.search("hell")); + System.out.println(m.search("leetcoded")); + } + +} From e47644e8c14de518f9864710b3a9888b4a920563 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 15 Sep 2018 12:52:25 -0700 Subject: [PATCH 408/456] add binary_tree_longest_consecutive_sequence_ii --- ...inaryTreeLongestConsecutiveSequenceII.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java diff --git a/src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java b/src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java new file mode 100644 index 0000000..01e420d --- /dev/null +++ b/src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java @@ -0,0 +1,38 @@ +package binary_tree_longest_consecutive_sequence_ii; + +import common.TreeNode; + +/** + * Created by lxie on 9/15/18. + */ +public class BinaryTreeLongestConsecutiveSequenceII { + + public class Solution { + + public int longestConsecutive(TreeNode root) { + if (root == null) return 0; + int res = helper(root, 1) + helper(root, -1) + 1; + return Math.max(res, Math.max(longestConsecutive(root.left), longestConsecutive(root.right))); + } + + private int helper(TreeNode node, int diff) { + if (node == null) return 0; + int left = 0, right = 0; + if (node.left != null && node.val - node.left.val == diff) { + left = 1 + helper(node.left, diff); + } + if (node.right != null && node.val - node.right.val == diff) { + right = 1 + helper(node.right, diff); + } + return Math.max(left, right); + } + + } + + public class UnitTest { + + + + } + +} From ac5a20f60614b329311c264b50a54bd671fa18bf Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 15 Sep 2018 15:19:19 -0700 Subject: [PATCH 409/456] patching_array --- ...inaryTreeLongestConsecutiveSequenceII.java | 2 +- .../java/patching_array/PatchingArray.java | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/main/java/patching_array/PatchingArray.java diff --git a/src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java b/src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java index 01e420d..0b1d6d6 100644 --- a/src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java +++ b/src/main/java/binary_tree_longest_consecutive_sequence_ii/BinaryTreeLongestConsecutiveSequenceII.java @@ -26,7 +26,7 @@ private int helper(TreeNode node, int diff) { } return Math.max(left, right); } - + } public class UnitTest { diff --git a/src/main/java/patching_array/PatchingArray.java b/src/main/java/patching_array/PatchingArray.java new file mode 100644 index 0000000..85ba98e --- /dev/null +++ b/src/main/java/patching_array/PatchingArray.java @@ -0,0 +1,33 @@ +package patching_array; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Created by lxie on 9/15/18. + */ +public class PatchingArray { + + public class Solution { + + public int minPatches(int[] nums, int n) { + long miss = 1, k = nums.length; + long[] longArray = Arrays.stream(nums).mapToLong(i -> i).toArray(); + List nums1 = Arrays.stream(longArray).boxed().collect(Collectors.toList()) ; + int i = 0; + while (miss <= n) { + if (i >= nums1.size() || nums1.get(i) > miss) { + nums1.add(i, miss); + } + miss += nums1.get(i++); + } + return (int) (nums1.size() - k); + } + } + + public class UnitTest { + + } + +} From ccdd166d1328f190f8e2b38509973db96cd3c92e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 15 Sep 2018 22:30:10 -0700 Subject: [PATCH 410/456] add boundary_of_binary_tree --- .../BoundaryBinaryTree.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/boundary_of_binary_tree/BoundaryBinaryTree.java diff --git a/src/main/java/boundary_of_binary_tree/BoundaryBinaryTree.java b/src/main/java/boundary_of_binary_tree/BoundaryBinaryTree.java new file mode 100644 index 0000000..7bb0519 --- /dev/null +++ b/src/main/java/boundary_of_binary_tree/BoundaryBinaryTree.java @@ -0,0 +1,41 @@ +package boundary_of_binary_tree; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 9/15/18. + */ +public class BoundaryBinaryTree { + + public class Solution { + + public List boundaryOfBinaryTree(TreeNode root) { + List res = new ArrayList<>(); + if (root == null) return res; + helper(root.left, true, false, res); + helper(root.right, false, true, res); + return res; + } + void helper(TreeNode node, boolean leftbd, boolean rightbd, List res) { + if (node == null) return; + if (node.left == null && node.right == null) { + res.add(node.val); + return; + } + if (leftbd) res.add(node.val); + helper(node.left, leftbd && node.left != null, rightbd && node.right == null, res); + helper(node.right, leftbd && node.left == null, rightbd && node.right != null, res); + if (rightbd) res.add(node.val); + } + } + + public class UnitTest { + + + } + + +} From 665ce71bd35ee4ddc02a36f4637bd2de77ca52a2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 16 Sep 2018 22:53:59 -0700 Subject: [PATCH 411/456] add output_contest_matches --- .../OutputContestMatches.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/output_contest_matches/OutputContestMatches.java diff --git a/src/main/java/output_contest_matches/OutputContestMatches.java b/src/main/java/output_contest_matches/OutputContestMatches.java new file mode 100644 index 0000000..b14c8e0 --- /dev/null +++ b/src/main/java/output_contest_matches/OutputContestMatches.java @@ -0,0 +1,34 @@ +package output_contest_matches; + +import java.util.Arrays; + +/** + * Created by lxie on 9/16/18. + */ +public class OutputContestMatches { + + public static class Solution { + + public String findContestMatch(int n) { + String[] v = new String[n+1]; Arrays.fill(v, ""); + for (int i = 1; i <= n; ++i) v[i-1] = Integer.toString(i); + helper(n, v); + return v[0]; + } + void helper(int n, String[] v) { + if (n == 1) return; + for (int i = 0; i < n; ++i) { + v[i] = "(" + v[i] + "," + v[n - i - 1] + ")"; + } + helper(n / 2, v); + } + + } + + public static void main(String[] args) { + Solution s = new Solution(); + String res = s.findContestMatch(8); + System.out.println(res); + + } +} From 810914cbbd084ed2f5ffaf37d51670d4ad4efc8f Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 16 Sep 2018 23:43:50 -0700 Subject: [PATCH 412/456] add kth_smallest_in_multi_table --- .../KthSmallestInMultiTable.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/kth_smallest_in_multi_table/KthSmallestInMultiTable.java diff --git a/src/main/java/kth_smallest_in_multi_table/KthSmallestInMultiTable.java b/src/main/java/kth_smallest_in_multi_table/KthSmallestInMultiTable.java new file mode 100644 index 0000000..7fd482a --- /dev/null +++ b/src/main/java/kth_smallest_in_multi_table/KthSmallestInMultiTable.java @@ -0,0 +1,33 @@ +package kth_smallest_in_multi_table; + +/** + * Created by lxie on 9/16/18. + */ +public class KthSmallestInMultiTable { + + public class Solution { + + public int findKthNumber(int m, int n, int k) { + int left = 1, right = m * n; + while (left < right) { + int mid = left + (right - left) / 2, cnt = 0, i = m, j = 1; + while (i >= 1 && j <= n) { + if (i * j <= mid) { + cnt += i; + ++j; + } else { + --i; + } + } + if (cnt < k) left = mid + 1; + else right = mid; + } + return right; + } + } + + public class UnitTest { + + + } +} From 157fbd34f6c6b1fcf9f0736652411a80260f648e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 17 Sep 2018 00:21:36 -0700 Subject: [PATCH 413/456] add beautiful_arrangement_ii --- .../BeautifulArrangementII.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/beautiful_arrangement_ii/BeautifulArrangementII.java diff --git a/src/main/java/beautiful_arrangement_ii/BeautifulArrangementII.java b/src/main/java/beautiful_arrangement_ii/BeautifulArrangementII.java new file mode 100644 index 0000000..4656643 --- /dev/null +++ b/src/main/java/beautiful_arrangement_ii/BeautifulArrangementII.java @@ -0,0 +1,27 @@ +package beautiful_arrangement_ii; + +/** + * Created by lxie on 9/17/18. + */ +public class BeautifulArrangementII { + + public class Solution { + + public int[] constructArray(int n, int k) { + int[] res = new int[n]; + int i = 1, j = n, t = 0; + while (i <= j) { + if (k > 1) res[t++] = (k-- % 2 != 0? i++ : j--); + else res[t++] = (i++); + } + return res; + } + + + } + + public class UnitTest { + + + } +} From 760cac4b3bb98e80e5449e37fc5c074dcc851e3a Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 17 Sep 2018 07:58:43 -0700 Subject: [PATCH 414/456] add lonely_pixel_ii --- .../java/lonely_pixel_ii/LonelyPixelII.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/lonely_pixel_ii/LonelyPixelII.java diff --git a/src/main/java/lonely_pixel_ii/LonelyPixelII.java b/src/main/java/lonely_pixel_ii/LonelyPixelII.java new file mode 100644 index 0000000..2217f10 --- /dev/null +++ b/src/main/java/lonely_pixel_ii/LonelyPixelII.java @@ -0,0 +1,49 @@ +package lonely_pixel_ii; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 9/17/18. + */ +public class LonelyPixelII { + + public class Solution { + + public int findBlackPixel(char[][] picture, int N) { + if (picture.length != 0 || picture[0].length != 0) return 0; + int m = picture.length, n = picture[0].length, res = 0; + int[] colCnt = new int[n]; + Map u = new HashMap<>(); + for (int i = 0; i < m; ++i) { + int cnt = 0; + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B') { + ++colCnt[j]; + ++cnt; + } + } + if (cnt == N) { + String line = new String(picture[i]); + if (u.containsKey(line)) { + u.put(line, u.get(line)+1); + } else { + u.put(line, 1); + } + } + } + for (Map.Entry a : u.entrySet()) { + if (a.getValue() != N) continue; + for (int i = 0; i < n; ++i) { + res += (a.getKey().charAt(i) == 'B' && colCnt[i] == N) ? N : 0; + } + } + return res; + } + + } + + public class UnitTest { + + } +} From c184d8c757686dea6de6acd56a19bb422e25664e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 17 Sep 2018 10:23:10 -0700 Subject: [PATCH 415/456] add lonely_pixel --- src/main/java/lonely_pixel/LonelyPixel.java | 42 +++++++++++++++++++ .../java/lonely_pixel_ii/LonelyPixelII.java | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/main/java/lonely_pixel/LonelyPixel.java diff --git a/src/main/java/lonely_pixel/LonelyPixel.java b/src/main/java/lonely_pixel/LonelyPixel.java new file mode 100644 index 0000000..ab84604 --- /dev/null +++ b/src/main/java/lonely_pixel/LonelyPixel.java @@ -0,0 +1,42 @@ +package lonely_pixel; + +/** + * Created by lxie on 9/17/18. + */ +public class LonelyPixel { + + public class Solution { + + public int findLonelyPixel(char[][] picture) { + if (picture.length == 0 || picture[0].length == 0) return 0; + int m = picture.length, n = picture[0].length, res = 0; + int[] rowCnt = new int[m]; + int[] colCnt = new int[n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B') { + ++rowCnt[i]; + ++colCnt[j]; + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (picture[i][j] == 'B') { + if (rowCnt[i] == 1 && colCnt[j] == 1) { + ++res; + } + } + } + } + return res; + } + + } + + public class UnitTest { + + + } + +} diff --git a/src/main/java/lonely_pixel_ii/LonelyPixelII.java b/src/main/java/lonely_pixel_ii/LonelyPixelII.java index 2217f10..f0d73c2 100644 --- a/src/main/java/lonely_pixel_ii/LonelyPixelII.java +++ b/src/main/java/lonely_pixel_ii/LonelyPixelII.java @@ -44,6 +44,6 @@ public int findBlackPixel(char[][] picture, int N) { } public class UnitTest { - + } } From f6ad4b6ca086acae86877e74a0bf03bf9085f403 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 18 Sep 2018 09:34:08 -0700 Subject: [PATCH 416/456] add split_array_into_consecutive_subsequences --- src/main/java/lonely_pixel/LonelyPixel.java | 2 +- .../SplitArray2ConseqSubseq.java | 51 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/main/java/split_array_into_consecutive_subsequences/SplitArray2ConseqSubseq.java diff --git a/src/main/java/lonely_pixel/LonelyPixel.java b/src/main/java/lonely_pixel/LonelyPixel.java index ab84604..2f8ac83 100644 --- a/src/main/java/lonely_pixel/LonelyPixel.java +++ b/src/main/java/lonely_pixel/LonelyPixel.java @@ -31,7 +31,7 @@ public int findLonelyPixel(char[][] picture) { } return res; } - + } public class UnitTest { diff --git a/src/main/java/split_array_into_consecutive_subsequences/SplitArray2ConseqSubseq.java b/src/main/java/split_array_into_consecutive_subsequences/SplitArray2ConseqSubseq.java new file mode 100644 index 0000000..2d55754 --- /dev/null +++ b/src/main/java/split_array_into_consecutive_subsequences/SplitArray2ConseqSubseq.java @@ -0,0 +1,51 @@ +package split_array_into_consecutive_subsequences; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 9/18/18. + */ +public class SplitArray2ConseqSubseq { + + public boolean isPossible(int[] nums) { + Map freq = new HashMap<>(); + Map need = new HashMap<>(); + for (int num : nums) { + if (freq.containsKey(num)) freq.put(num, freq.get(num) + 1); + else + freq.put(num, 1); + } + for (int num : nums) { + if (freq.containsKey(num) && freq.get(num) == 0) continue; + else if (need.containsKey(num) && need.get(num) > 0) { + need.put(num, need.get(num) - 1); + if (need.containsKey(num+1)) + need.put(num+1, need.get(num+1) + 1); + else + need.put(num+1, 1); + } else if (freq.containsKey(num+1) && freq.get(num + 1) > 0 && + freq.containsKey(num+2) && freq.get(num + 2) > 0) { + freq.put(num+1, freq.get(num + 1) - 1); + freq.put(num+2, freq.get(num + 2) - 1); + if (need.containsKey(num+3)) + need.put(num+3, need.get(num+3) + 1); + else + need.put(num+3, 1); + } else return false; + freq.put(num, freq.get(num) - 1); + } + return true; + } + + public static void main(String[] args) { + SplitArray2ConseqSubseq s = new SplitArray2ConseqSubseq(); + int[] input = {1,2,3,3,4,4,5,5}; + boolean res = s.isPossible(input); + System.out.println(res); + } + + + + +} From b4654473fcec2916dfd4e95c8e230cbabc3d4455 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 18 Sep 2018 23:19:41 -0700 Subject: [PATCH 417/456] add word_abbreviation --- .../word_abbreviation/WordAbbreviation.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/word_abbreviation/WordAbbreviation.java diff --git a/src/main/java/word_abbreviation/WordAbbreviation.java b/src/main/java/word_abbreviation/WordAbbreviation.java new file mode 100644 index 0000000..1c9a68e --- /dev/null +++ b/src/main/java/word_abbreviation/WordAbbreviation.java @@ -0,0 +1,46 @@ +package word_abbreviation; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by lxie on 9/18/18. + */ +public class WordAbbreviation { + + public String[] wordsAbbreviation(String[] dict) { + int n = dict.length; + String[] res = new String[n]; + int[] pre = new int[n]; Arrays.fill(pre, 1); + for (int i = 0; i < n; ++i) { + res[i] = abbreviate(dict[i], pre[i]); + } + for (int i = 0; i < n; ++i) { + while (true) { + Set s = new HashSet<>(); + for (int j = i + 1; j < n; ++j) { + if (res[j].equals(res[i])) s.add(j); + } + if (s.isEmpty()) break; + s.add(i); + for (int a : s) { + res[a] = abbreviate(dict[a], ++pre[a]); + } + } + } + return res; + } + + private String abbreviate(String s, int k) { + return (k >= s.length() - 2) ? s : s.substring(0, k) + Integer.toString(s.length() - k - 1) + + s.charAt(s.length()-1); + } + + + public static void main(String[] args) { + WordAbbreviation w = new WordAbbreviation(); + String[] dict = {"like", "god", "internal", "me", "internet", "interval", "intension", "face", "intrusion"}; + System.out.println(Arrays.toString(w.wordsAbbreviation(dict))); + } +} From 7c174a8483be8840375f2339a934f89a65017edc Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 20 Sep 2018 07:48:26 -0700 Subject: [PATCH 418/456] add find_k_closest_elements --- .../FindKClosestElements.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/find_k_closest_elements/FindKClosestElements.java diff --git a/src/main/java/find_k_closest_elements/FindKClosestElements.java b/src/main/java/find_k_closest_elements/FindKClosestElements.java new file mode 100644 index 0000000..5e8350e --- /dev/null +++ b/src/main/java/find_k_closest_elements/FindKClosestElements.java @@ -0,0 +1,32 @@ +package find_k_closest_elements; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by lxie on 9/20/18. + */ +public class FindKClosestElements { + + public class Solution { + + public List findClosestElements(int[] arr, int k, int x) { + int left = 0, right = arr.length - k; + List res = new ArrayList<>(); + while (left < right) { + int mid = left + (right - left) / 2; + if (x - arr[mid] > arr[mid + k] - x) left = mid + 1; + else right = mid; + } + for(int i = left; i<= left+k; ++i) res.add(arr[i]); + return res; + } + } + + public class UnitTest { + + + } + + +} From 6985f3529d1d7de739cfbb64b6774b19db8fcfab Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 20 Sep 2018 14:12:23 -0700 Subject: [PATCH 419/456] add longest_uncommon_subsequence_ii --- .../LongestUncommonSubsequence.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/longest_uncommon_subsequence_ii/LongestUncommonSubsequence.java diff --git a/src/main/java/longest_uncommon_subsequence_ii/LongestUncommonSubsequence.java b/src/main/java/longest_uncommon_subsequence_ii/LongestUncommonSubsequence.java new file mode 100644 index 0000000..7c22714 --- /dev/null +++ b/src/main/java/longest_uncommon_subsequence_ii/LongestUncommonSubsequence.java @@ -0,0 +1,49 @@ +package longest_uncommon_subsequence_ii; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by lxie on 9/20/18. + */ +public class LongestUncommonSubsequence { + + public int findLUSlength(String[] strs) { + int n = strs.length; + Set s = new HashSet<>(); + Arrays.sort(strs, new Comparator() { + @Override + public int compare(String a, String b) { + if (a.length() == b.length()) return b.compareTo(a); + return b.length() - a.length(); + } + }); + for (int i = 0; i < n; ++i) { + if (i == n - 1 || strs[i] != strs[i + 1]) { + boolean found = true; + for (String a : s) { // compare to longer ones + int j = 0; + for (char c : a.toCharArray()) { + if (c == strs[i].charAt(j)) ++j; + if (j == strs[i].length()) break; + } + if (j == strs[i].length()) { + found = false; + break; + } + } + if (found) return strs[i].length(); + } + s.add(strs[i]); + } + return -1; + } + + public static void main(String[] args) { + LongestUncommonSubsequence s = new LongestUncommonSubsequence(); + String[] input = {"aba", "cdc", "eae", "whatsapp"}; + System.out.println(s.findLUSlength(input)); + } +} From 9b4d2933617162228407e8be30fbc8ce4bed146e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 20 Sep 2018 22:54:25 -0700 Subject: [PATCH 420/456] add freedom_trail --- src/main/java/freedom_trail/FreedomTrail.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/freedom_trail/FreedomTrail.java diff --git a/src/main/java/freedom_trail/FreedomTrail.java b/src/main/java/freedom_trail/FreedomTrail.java new file mode 100644 index 0000000..eebfce3 --- /dev/null +++ b/src/main/java/freedom_trail/FreedomTrail.java @@ -0,0 +1,33 @@ +package freedom_trail; + +/** + * Created by lxie on 9/20/18. + */ +public class FreedomTrail { + + public class Solution { + + public int findRotateSteps(String ring, String key) { + int n = ring.length(), m = key.length(); + int[][] dp = new int[m+1][n]; + for (int i = m - 1; i >= 0; --i) { + for (int j = 0; j < n; ++j) { + dp[i][j] = Integer.MAX_VALUE; + for (int k = 0; k < n; ++k) { + if (ring.charAt(k) == key.charAt(i)) { + int diff = Math.abs(j - k); + int step = Math.min(diff, n - diff); + dp[i][j] = Math.min(dp[i][j], step + dp[i + 1][k]); + } + } + } + } + return dp[0][0] + m; + } + } + + public class UnitTest { + + } + +} From 02f52951e6d8deb62c828fa27f3904e4ddd4eac2 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 21 Sep 2018 08:18:16 -0700 Subject: [PATCH 421/456] add coin_path --- src/main/java/coin_path/CoinPath.java | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/coin_path/CoinPath.java diff --git a/src/main/java/coin_path/CoinPath.java b/src/main/java/coin_path/CoinPath.java new file mode 100644 index 0000000..39f05e6 --- /dev/null +++ b/src/main/java/coin_path/CoinPath.java @@ -0,0 +1,46 @@ +package coin_path; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by lxie on 9/21/18. + */ +public class CoinPath { + + public class Solution { + + public List cheapestJump(int[] A, int B) { + List res = new ArrayList<>(); + if (A[A.length-1] == -1) return res; + int n = A.length; + int[] dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE); + int[] pos = new int[n]; Arrays.fill(dp, -1); + dp[n - 1] = A[n - 1]; + for (int i = n - 2; i >= 0; --i) { + if (A[i] == -1) continue; + for (int j = i + 1; j <= Math.min(i + B, n - 1); ++j) { + if (dp[j] == Integer.MAX_VALUE) continue; + if (A[i] + dp[j] < dp[i]) { + dp[i] = A[i] + dp[j]; + pos[i] = j; + } + } + } + if (dp[0] == Integer.MAX_VALUE) return res; + for (int cur = 0; cur != -1; cur = pos[cur]) { + res.add(cur + 1); + } + return res; + } + } + + public class UnitTest { + + + + } + + +} From 399efadcb3e1b1924164df077f9588b4c6c5f5cd Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 21 Sep 2018 16:08:32 -0700 Subject: [PATCH 422/456] add target_sum --- src/main/java/target_sum/TargetSum.java | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/java/target_sum/TargetSum.java diff --git a/src/main/java/target_sum/TargetSum.java b/src/main/java/target_sum/TargetSum.java new file mode 100644 index 0000000..f1e70b3 --- /dev/null +++ b/src/main/java/target_sum/TargetSum.java @@ -0,0 +1,39 @@ +package target_sum; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by lxie on 9/21/18. + */ +public class TargetSum { + + public class Solution { + + public int findTargetSumWays(int[] nums, int S) { + List> dp = new ArrayList<>(); + for (int i = 0; i< nums.length; ++i) + dp.add(new HashMap<>()); + return helper(nums, S, 0, dp); + } + + private int helper(int[] nums, int sum, int start, List> dp) { + if (start == nums.length) return sum == 0 ? 1 : 0; + if (dp.get(start).containsKey(sum)) return dp.get(start).get(sum); + int cnt1 = helper(nums, sum - nums[start], start + 1, dp); + int cnt2 = helper(nums, sum + nums[start], start + 1, dp); + dp.get(start).put(sum, cnt1 + cnt2); + return cnt1 + cnt2; + } + + } + + public class UnitTest { + + + + } + +} From ab5d112c9e79335d72c287d5ae5325be3ae2024b Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 21 Sep 2018 19:07:46 -0700 Subject: [PATCH 423/456] add reverse_pairs --- src/main/java/reverse_pairs/ReversePairs.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/reverse_pairs/ReversePairs.java diff --git a/src/main/java/reverse_pairs/ReversePairs.java b/src/main/java/reverse_pairs/ReversePairs.java new file mode 100644 index 0000000..21d82b9 --- /dev/null +++ b/src/main/java/reverse_pairs/ReversePairs.java @@ -0,0 +1,34 @@ +package reverse_pairs; + +import java.util.Arrays; + +/** + * Created by lxie on 9/21/18. + */ +public class ReversePairs { + + public class Solution { + + public int reversePairs(int[] nums) { + return mergeSort(nums, 0, nums.length - 1); + } + + private int mergeSort(int[] nums, int left, int right) { + if (left >= right) return 0; + int mid = left + (right - left) / 2; + int res = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right); + for (int i = left, j = mid + 1; i <= mid; ++i) { + while (j <= right && nums[i] / 2.0 > nums[j]) ++j; + res += j - (mid + 1); + } + Arrays.sort(nums, left, right + 1); + return res; + } + } + + public class UnitTest { + + + + } +} From 62ccbde7255428cc0ae1aa975c8ef822242449ba Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 22 Sep 2018 19:34:14 -0700 Subject: [PATCH 424/456] add max_avg_subarray_ii --- .../max_avg_subarray_ii/MaxAvgSubarrayII.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/max_avg_subarray_ii/MaxAvgSubarrayII.java diff --git a/src/main/java/max_avg_subarray_ii/MaxAvgSubarrayII.java b/src/main/java/max_avg_subarray_ii/MaxAvgSubarrayII.java new file mode 100644 index 0000000..5597086 --- /dev/null +++ b/src/main/java/max_avg_subarray_ii/MaxAvgSubarrayII.java @@ -0,0 +1,41 @@ +package max_avg_subarray_ii; + +import com.google.common.primitives.Doubles; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Created by lxie on 9/22/18. + */ +public class MaxAvgSubarrayII { + + public double findMaxAverage(int[] nums, int k) { + List numsd = Doubles.asList(Arrays.stream(nums).asDoubleStream().toArray()); + double left = Collections.min(numsd); + double right = Collections.max(numsd); + while (right - left > 1e-5) { + double minSum = 0, sum = 0, preSum = 0, mid = left + (right - left) / 2; + boolean check = false; + for (int i = 0; i < nums.length; ++i) { + sum += nums[i] - mid; + if (i >= k) { + preSum += nums[i - k] - mid; + minSum = Math.min(minSum, preSum); + } + if (i >= k - 1 && sum > minSum) {check = true; break;} + } + if (check) left = mid; + else right = mid; + } + return left; + } + + public static void main(String[] args) { + MaxAvgSubarrayII m = new MaxAvgSubarrayII(); + int[] input = {1,12,-5,-6,50,3}; + System.out.println(m.findMaxAverage(input, 4)); + } + +} From 1c9ae38aac69917f34f1fbc3e72c82b299cd317d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 22 Sep 2018 22:27:01 -0700 Subject: [PATCH 425/456] add max_consecutive_ones_ii --- .../MaxConsecutiveOnes.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/max_consecutive_ones_ii/MaxConsecutiveOnes.java diff --git a/src/main/java/max_consecutive_ones_ii/MaxConsecutiveOnes.java b/src/main/java/max_consecutive_ones_ii/MaxConsecutiveOnes.java new file mode 100644 index 0000000..b574d77 --- /dev/null +++ b/src/main/java/max_consecutive_ones_ii/MaxConsecutiveOnes.java @@ -0,0 +1,32 @@ +package max_consecutive_ones_ii; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * Created by lxie on 9/22/18. + */ +public class MaxConsecutiveOnes { + + public class Solution { + + public int findMaxConsecutiveOnes(int[] nums) { + int res = 0, left = 0, k = 1; + Queue q = new LinkedList<>(); + for (int right = 0; right < nums.length; ++right) { + if (nums[right] == 0) q.add(right); + if (q.size() > k) { + left = q.peek() + 1; q.poll(); + } + res = Math.max(res, right - left + 1); + } + return res; + } + } + + public class UnitTest { + + + + } +} From d70ef281d651c81ac4a2ca0cfddfbc30fd657809 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 24 Sep 2018 01:16:17 -0700 Subject: [PATCH 426/456] add max_size_subarray_sum_equals_k --- .../MaxSizeSubarraySumK.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/main/java/max_size_subarray_sum_equals_k/MaxSizeSubarraySumK.java diff --git a/src/main/java/max_size_subarray_sum_equals_k/MaxSizeSubarraySumK.java b/src/main/java/max_size_subarray_sum_equals_k/MaxSizeSubarraySumK.java new file mode 100644 index 0000000..582b564 --- /dev/null +++ b/src/main/java/max_size_subarray_sum_equals_k/MaxSizeSubarraySumK.java @@ -0,0 +1,32 @@ +package max_size_subarray_sum_equals_k; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 9/24/18. + */ +public class MaxSizeSubarraySumK { + + public class Solution { + + public int maxSubArrayLen(int[] nums, int k) { + int sum = 0, res = 0; + Map m = new HashMap<>(); + for (int i = 0; i < nums.length; ++i) { + sum += nums[i]; + if (sum == k) res = i + 1; + else if (m.containsKey(sum - k)) res = Math.max(res, i - m.get(sum - k)); + if (!m.containsKey(sum)) m.put(sum, i); // records earliest idx only + } + return res; + } + } + + public class UnitTest { + + + + } + +} From 56760ac130b0067cad158c0a063f32d621b1d187 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 24 Sep 2018 10:30:27 -0700 Subject: [PATCH 427/456] add task_scheduler --- .../java/task_scheduler/TaskScheduler.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/main/java/task_scheduler/TaskScheduler.java diff --git a/src/main/java/task_scheduler/TaskScheduler.java b/src/main/java/task_scheduler/TaskScheduler.java new file mode 100644 index 0000000..f056cf3 --- /dev/null +++ b/src/main/java/task_scheduler/TaskScheduler.java @@ -0,0 +1,47 @@ +package task_scheduler; + +import java.util.*; + +/** + * Created by lxie on 9/24/18. + */ +public class TaskScheduler { + + public class Solution { + + public int leastInterval(char[] tasks, int n) { + int res = 0, cycle = n + 1; + Map m = new HashMap<>(); + PriorityQueue q = new PriorityQueue<>(100, Collections.reverseOrder()); + for (char c : tasks) { + if (m.containsKey(c)) + m.put(c, m.get(c)+1); + else + m.put(c, 1); + } + for (Map.Entry a : m.entrySet()) + q.add(a.getValue()); + while (!q.isEmpty()) { + int cnt = 0; + List t = new ArrayList<>(); + for (int i = 0; i < cycle; ++i) { + if (!q.isEmpty()) { + t.add(q.peek()); q.poll(); + ++cnt; + } + } + for (int d : t) { + if (--d > 0) q.add(d); + } + res += q.isEmpty() ? cnt : cycle; + } + return res; + } + } + + public class UnitTest { + + + } + +} From 401fb4a0fd828dcc6c09ccf83385f679b3d725db Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 26 Sep 2018 09:52:32 -0700 Subject: [PATCH 428/456] add exclusive_time_of_functions --- .../ExclusiveTimeOfFunctions.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/exclusive_time_of_functions/ExclusiveTimeOfFunctions.java diff --git a/src/main/java/exclusive_time_of_functions/ExclusiveTimeOfFunctions.java b/src/main/java/exclusive_time_of_functions/ExclusiveTimeOfFunctions.java new file mode 100644 index 0000000..37ab9fd --- /dev/null +++ b/src/main/java/exclusive_time_of_functions/ExclusiveTimeOfFunctions.java @@ -0,0 +1,45 @@ +package exclusive_time_of_functions; + +import java.util.List; +import java.util.Stack; + +/** + * Created by lxie on 9/26/18. + */ +public class ExclusiveTimeOfFunctions { + + public class Solution { + + public int[] exclusiveTime(int n, List logs) { + int[] res = new int[n]; + Stack st = new Stack<>(); + int preTime = 0; + for (String log : logs) { + String[] params = log.split(":"); + int idx = Integer.parseInt(params[0]); + String type = params[1]; + int time = Integer.parseInt(params[2]); + if (!st.empty()) { + res[st.peek()] += time - preTime; + } + preTime = time; + if (type.equals("start")) st.push(idx); + else { + int t = st.peek(); st.pop(); + ++res[t]; // add 1s for ended task + ++preTime; + } + } + return res; + } + + } + + public class UnitTest { + + + + } + + +} From 8cbb273dac1ca9b6e30d776118bc640b0cdf550d Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 26 Sep 2018 19:33:29 -0700 Subject: [PATCH 429/456] modify sort_colors --- src/main/java/sort_colors/SortColors.java | 24 +++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/java/sort_colors/SortColors.java b/src/main/java/sort_colors/SortColors.java index f78b186..d99d8de 100644 --- a/src/main/java/sort_colors/SortColors.java +++ b/src/main/java/sort_colors/SortColors.java @@ -4,19 +4,23 @@ public class SortColors { public class Solution { public void sortColors(int[] A) { - int zero = -1; - int one = -1; - for (int i = 0; i < A.length; i++) { + int red = 0, blue = A.length - 1; + for (int i = 0; i <= blue; ++i) { if (A[i] == 0) { - A[i] = A[++zero]; - A[zero] = 0; - one = Math.max(zero, one); - } - if (A[i] == 1) { - A[i] = A[++one]; - A[one] = 1; + int tmp = A[red]; + A[red] = A[i]; + A[i] = tmp; + red++; + //swap(A[i], A[red++]); + } else if (A[i] == 2) { + int tmp = A[i]; + A[i] = A[blue]; + A[blue] = tmp; + i--; blue--; + //swap(A[i--], A[blue--]); } } + } } From 6bcb0412f1af9aef80c9fa0ff58c87bd18a3fae7 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 27 Sep 2018 09:02:15 -0700 Subject: [PATCH 430/456] add maximum_swap --- src/main/java/maximum_swap/MaximumSwap.java | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/maximum_swap/MaximumSwap.java diff --git a/src/main/java/maximum_swap/MaximumSwap.java b/src/main/java/maximum_swap/MaximumSwap.java new file mode 100644 index 0000000..be7d30e --- /dev/null +++ b/src/main/java/maximum_swap/MaximumSwap.java @@ -0,0 +1,37 @@ +package maximum_swap; + +/** + * Created by lxie on 9/27/18. + */ +public class MaximumSwap { + + public class Solution { + + public int maximumSwap(int num) { + char[] res = Integer.toString(num).toCharArray(); + char[] back = res.clone(); + for (int i = back.length - 2; i >= 0; --i) { + back[i] = back[i] < back[i + 1] ? back[i + 1] : back[i]; + } + for (int i = 0; i < res.length; ++i) { + if (res[i] == back[i]) continue; + for (int j = res.length - 1; j > i; --j) { + if (res[j] == back[i]) { + char tmp = res[j]; + res[j] = res[i]; + res[i] = tmp; + return Integer.parseInt(new String(res)); + } + } + } + return num; + } + } + + public class UnitTest { + + + } + + +} From 6ba7fe66d2488c3823905152a01eea78515c1f83 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Thu, 27 Sep 2018 09:26:55 -0700 Subject: [PATCH 431/456] add kth_largest_in_array --- .../KthLargestInArray.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/java/kth_largest_in_array/KthLargestInArray.java diff --git a/src/main/java/kth_largest_in_array/KthLargestInArray.java b/src/main/java/kth_largest_in_array/KthLargestInArray.java new file mode 100644 index 0000000..52acbe6 --- /dev/null +++ b/src/main/java/kth_largest_in_array/KthLargestInArray.java @@ -0,0 +1,48 @@ +package kth_largest_in_array; + +/** + * Created by lxie on 9/27/18. + */ +public class KthLargestInArray { + + public class Solution { + + public int findKthLargest(int[] nums, int k) { + int left = 0, right = nums.length - 1; + while (true) { + int pos = partition(nums, left, right); + if (pos == k - 1) return nums[pos]; + else if (pos > k - 1) right = pos - 1; + else left = pos + 1; + } + } + + private int partition(int[] nums, int left, int right) { + int pivot = nums[left], l = left + 1, r = right; + while (l <= r) { + if (nums[l] < pivot && nums[r] > pivot) { + swap(nums, l++, r--); + } + if (nums[l] >= pivot) ++l; + if (nums[r] <= pivot) --r; + } + swap(nums, left, r); + return r; + } + + private void swap(int[] a, int i, int j) { + int tmp = a[i]; + a[i] = a[j]; + a[j] = tmp; + } + + + } + + public class UnitTest { + + + + } + +} From b47741c6a929e2df8c6bd849a5d4c2595759c017 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 28 Sep 2018 07:44:35 -0700 Subject: [PATCH 432/456] add total_hamming_distance --- .../TotalHammingDistance.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/total_hamming_distance/TotalHammingDistance.java diff --git a/src/main/java/total_hamming_distance/TotalHammingDistance.java b/src/main/java/total_hamming_distance/TotalHammingDistance.java new file mode 100644 index 0000000..4019517 --- /dev/null +++ b/src/main/java/total_hamming_distance/TotalHammingDistance.java @@ -0,0 +1,30 @@ +package total_hamming_distance; + +/** + * Created by lxie on 9/28/18. + */ +public class TotalHammingDistance { + + public class Solution { + + public int totalHammingDistance(int[] nums) { + int res = 0, n = nums.length; + for (int i = 0; i < 32; ++i) { + int cnt = 0; + for (int num : nums) { + if ((num & (1 << i)) == 1) ++cnt; + } + res += cnt * (n - cnt); + } + return res; + } + } + + public class UnitTest { + + + + } + + +} From 66dd3ccab4f1d47a8aeab9cbd62b7c3da35242ef Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 28 Sep 2018 08:34:33 -0700 Subject: [PATCH 433/456] add valid_palindrome_ii --- .../ValidPalindromeII.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/valid_palindrome_ii/ValidPalindromeII.java diff --git a/src/main/java/valid_palindrome_ii/ValidPalindromeII.java b/src/main/java/valid_palindrome_ii/ValidPalindromeII.java new file mode 100644 index 0000000..c99d721 --- /dev/null +++ b/src/main/java/valid_palindrome_ii/ValidPalindromeII.java @@ -0,0 +1,41 @@ +package valid_palindrome_ii; + +/** + * Created by lxie on 9/28/18. + */ +public class ValidPalindromeII { + + public class Solution { + + public boolean validPalindrome(String s) { + int left = 0, right = s.length() - 1; + while (left < right) { + if (s.charAt(left) == s.charAt(right)) { + ++left; --right; + } else { + int l = left, r = right - 1; + while (l < r) { + if (s.charAt(l) != s.charAt(r)) break; + ++l; --r; + if (l >= r) return true; + } + ++left; + while (left < right) { + if (s.charAt(left) != s.charAt(right)) return false; + ++left; --right; + } + } + } + return true; + } + + + } + + public class UnitTest { + + + } + + +} From 9d7f7440d0d1bdfddfb785873b39faea446375fb Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Fri, 28 Sep 2018 09:10:55 -0700 Subject: [PATCH 434/456] add add valid_palindrome_ii --- src/main/java/anagrams/Anagrams.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/anagrams/Anagrams.java b/src/main/java/anagrams/Anagrams.java index 3701d25..f81e022 100644 --- a/src/main/java/anagrams/Anagrams.java +++ b/src/main/java/anagrams/Anagrams.java @@ -10,7 +10,7 @@ public class Anagrams { public class Solution { - public ArrayList anagrams(String[] strs) { + public List> groupAnagrams(String[] strs) { Map> dict = new HashMap>(); for (String str : strs) { char[] cs = str.toCharArray(); @@ -23,11 +23,9 @@ public ArrayList anagrams(String[] strs) { } l.add(str); } - ArrayList ans = new ArrayList(); + List> ans = new ArrayList<>(); for (Entry> e : dict.entrySet()) { - if (e.getValue().size() > 1) { - ans.addAll(e.getValue()); - } + ans.add(e.getValue()); } return ans; } From abad0b40eeafc608026103cf0e85fe0f39819083 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 29 Sep 2018 09:43:29 -0700 Subject: [PATCH 435/456] add minimum_size_subarray_sum --- .../MinSizeSubarraySum.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/minimum_size_subarray_sum/MinSizeSubarraySum.java diff --git a/src/main/java/minimum_size_subarray_sum/MinSizeSubarraySum.java b/src/main/java/minimum_size_subarray_sum/MinSizeSubarraySum.java new file mode 100644 index 0000000..7d14d14 --- /dev/null +++ b/src/main/java/minimum_size_subarray_sum/MinSizeSubarraySum.java @@ -0,0 +1,27 @@ +package minimum_size_subarray_sum; + +/** + * Created by lxie on 9/29/18. + */ +public class MinSizeSubarraySum { + + public class Solution { + + public int minSubArrayLen(int s, int[] nums) { + int res = Integer.MAX_VALUE, left = 0, sum = 0; + for (int i = 0; i < nums.length; ++i) { + sum += nums[i]; + while (left <= i && sum >= s) { + res = Math.min(res, i - left + 1); + sum -= nums[left++]; + } + } + return res == Integer.MAX_VALUE ? 0 : res; + } + } + + public class UnitTest { + + + } +} From 6b05e627eaa663a6d966e2d1b0ea45b96fd3f279 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 29 Sep 2018 17:34:09 -0700 Subject: [PATCH 436/456] add decode_ways_ii --- .../java/decode_ways_ii/DecodeWaysII.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/decode_ways_ii/DecodeWaysII.java diff --git a/src/main/java/decode_ways_ii/DecodeWaysII.java b/src/main/java/decode_ways_ii/DecodeWaysII.java new file mode 100644 index 0000000..3ae8f7b --- /dev/null +++ b/src/main/java/decode_ways_ii/DecodeWaysII.java @@ -0,0 +1,35 @@ +package decode_ways_ii; + +/** + * Created by lxie on 9/29/18. + */ +public class DecodeWaysII { + + public class Solution { + + public int numDecodings(String s) { + long e0 = 1, e1 = 0, e2 = 0, f0 = 0; + double M = 1e9 + 7; + for (char c : s.toCharArray()) { + if (c == '*') { + f0 = 9 * e0 + 9 * e1 + 6 * e2; + e1 = e0; + e2 = e0; + } else { + f0 = (c > '0'? 1 : 0) * e0 + e1 + (c <= '6'? 1 : 0) * e2; + e1 = (c == '1'? 1 : 0) * e0; + e2 = (c == '2'? 1: 0) * e0; + } + e0 = f0 % (long)M; + } + return (int) e0; + } + } + + public class UnitTest { + + + } + + +} From ad7cd2600b76bae14d90f380e4379e12edd86d4e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 30 Sep 2018 00:01:19 -0700 Subject: [PATCH 437/456] add continuous_subarray_sum --- .../ContinuousSubarraySum.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/main/java/continuous_subarray_sum/ContinuousSubarraySum.java diff --git a/src/main/java/continuous_subarray_sum/ContinuousSubarraySum.java b/src/main/java/continuous_subarray_sum/ContinuousSubarraySum.java new file mode 100644 index 0000000..f35c7ca --- /dev/null +++ b/src/main/java/continuous_subarray_sum/ContinuousSubarraySum.java @@ -0,0 +1,34 @@ +package continuous_subarray_sum; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 9/29/18. + */ +public class ContinuousSubarraySum { + + public class Solution { + + public boolean checkSubarraySum(int[] nums, int k) { + int n = nums.length, sum = 0; + Map m = new HashMap<>(); + m.put(0, -1); + for (int i = 0; i < n; ++i) { + sum += nums[i]; + int t = (k == 0) ? sum : (sum % k); + if (m.containsKey(t)) { + if (i - m.get(t) > 1) return true; + } else m.put(t, i); + } + return false; + } + + } + + public class UnitTest { + + + } + +} From 1bc69783e78cee65348aaa4232eb766f031d5aef Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 30 Sep 2018 09:51:49 -0700 Subject: [PATCH 438/456] add increasing_triplet_subsequence --- .../IncreasingTripletSubsequence.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/main/java/increasing_triplet_subsequence/IncreasingTripletSubsequence.java diff --git a/src/main/java/increasing_triplet_subsequence/IncreasingTripletSubsequence.java b/src/main/java/increasing_triplet_subsequence/IncreasingTripletSubsequence.java new file mode 100644 index 0000000..8458e53 --- /dev/null +++ b/src/main/java/increasing_triplet_subsequence/IncreasingTripletSubsequence.java @@ -0,0 +1,26 @@ +package increasing_triplet_subsequence; + +/** + * Created by lxie on 9/30/18. + */ +public class IncreasingTripletSubsequence { + + public class Solution { + + boolean increasingTriplet(int[] nums) { + int m1 = Integer.MAX_VALUE, m2 = Integer.MAX_VALUE; + for (int a : nums) { + if (m1 >= a) m1 = a; // m1 leaves INT_MAX ealier than m2 + else if (m2 >= a) m2 = a; + else return true; + } + return false; + } + } + + public class UnitTest { + + + } + +} From 212ea9316004d0cda4a5feb31e2c68ecb9da0326 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 30 Sep 2018 22:18:09 -0700 Subject: [PATCH 439/456] add palindromic_substring --- .../PalindromicSubstring.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/palindromic_substring/PalindromicSubstring.java diff --git a/src/main/java/palindromic_substring/PalindromicSubstring.java b/src/main/java/palindromic_substring/PalindromicSubstring.java new file mode 100644 index 0000000..2d43c4a --- /dev/null +++ b/src/main/java/palindromic_substring/PalindromicSubstring.java @@ -0,0 +1,27 @@ +package palindromic_substring; + +/** + * Created by lxie on 9/30/18. + */ +public class PalindromicSubstring { + + public class Solution { + + public int countSubstrings(String s) { + int n = s.length(), res = 0; + boolean[][] dp = new boolean[n][n]; + for (int i = n - 1; i >= 0; --i) { + for (int j = i; j < n; ++j) { + dp[i][j] = (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1]); + if (dp[i][j]) ++res; + } + } + return res; + } + } + + public class UnitTest { + + } + +} From 41b3c4e8a37e4930347428a690d2acd65403ea37 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 30 Sep 2018 22:21:42 -0700 Subject: [PATCH 440/456] add palindromic_substring --- src/main/java/palindromic_substring/PalindromicSubstring.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/palindromic_substring/PalindromicSubstring.java b/src/main/java/palindromic_substring/PalindromicSubstring.java index 2d43c4a..dd25bce 100644 --- a/src/main/java/palindromic_substring/PalindromicSubstring.java +++ b/src/main/java/palindromic_substring/PalindromicSubstring.java @@ -12,7 +12,7 @@ public int countSubstrings(String s) { boolean[][] dp = new boolean[n][n]; for (int i = n - 1; i >= 0; --i) { for (int j = i; j < n; ++j) { - dp[i][j] = (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1]); + dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1]); if (dp[i][j]) ++res; } } @@ -21,7 +21,7 @@ public int countSubstrings(String s) { } public class UnitTest { - + } } From 38b8e3cc396e0178097e363e2ba94ee666b2bd44 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 1 Oct 2018 09:46:48 -0700 Subject: [PATCH 441/456] add brick_wall --- src/main/java/brick_wall/BrickWall.java | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/brick_wall/BrickWall.java diff --git a/src/main/java/brick_wall/BrickWall.java b/src/main/java/brick_wall/BrickWall.java new file mode 100644 index 0000000..e2cf109 --- /dev/null +++ b/src/main/java/brick_wall/BrickWall.java @@ -0,0 +1,37 @@ +package brick_wall; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 10/1/18. + */ +public class BrickWall { + + public class Solution { + + public int leastBricks(int[][] wall) { + int mx = 0; + Map m = new HashMap<>(); + for (int[] a : wall) { + int sum = 0; + for (int i = 0; i < a.length - 1; ++i) { + sum += a[i]; + if (m.containsKey(sum)) + m.put(sum, m.get(sum)+1); + else + m.put(sum, 1); + mx = Math.max(mx, m.get(sum)); + } + } + return wall.length - mx; + } + } + + public class UnitTest { + + + + } + +} From 5fea928314ffdd0af4aa6fc4b8a587f85b86641e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sat, 6 Oct 2018 10:18:22 -0700 Subject: [PATCH 442/456] modify brick_wall --- src/main/java/brick_wall/BrickWall.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/brick_wall/BrickWall.java b/src/main/java/brick_wall/BrickWall.java index e2cf109..976c434 100644 --- a/src/main/java/brick_wall/BrickWall.java +++ b/src/main/java/brick_wall/BrickWall.java @@ -1,6 +1,7 @@ package brick_wall; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -10,13 +11,13 @@ public class BrickWall { public class Solution { - public int leastBricks(int[][] wall) { + public int leastBricks(List> wall) { int mx = 0; Map m = new HashMap<>(); - for (int[] a : wall) { + for (List a : wall) { int sum = 0; - for (int i = 0; i < a.length - 1; ++i) { - sum += a[i]; + for (int i = 0; i < a.size() - 1; ++i) { + sum += a.get(i); if (m.containsKey(sum)) m.put(sum, m.get(sum)+1); else @@ -24,7 +25,7 @@ public int leastBricks(int[][] wall) { mx = Math.max(mx, m.get(sum)); } } - return wall.length - mx; + return wall.size() - mx; } } From 2d9c6c2a0c9e9323c41782f055c0579acb6e1eba Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Sun, 7 Oct 2018 17:32:58 -0700 Subject: [PATCH 443/456] add contiguous_array --- .../contiguous_array/ContiguousArray.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/main/java/contiguous_array/ContiguousArray.java diff --git a/src/main/java/contiguous_array/ContiguousArray.java b/src/main/java/contiguous_array/ContiguousArray.java new file mode 100644 index 0000000..96b507a --- /dev/null +++ b/src/main/java/contiguous_array/ContiguousArray.java @@ -0,0 +1,33 @@ +package contiguous_array; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by lxie on 10/7/18. + */ +public class ContiguousArray { + + public class Solution { + + int findMaxLength(int[] nums) { + int res = 0, n = nums.length, sum = 0; + Map m = new HashMap<>(); + m.put(0, -1); + for (int i = 0; i < n; ++i) { + sum += (nums[i] == 1) ? 1 : -1; + if (m.containsKey(sum)) { + res = Math.max(res, i - m.get(sum)); + } else { + m.put(sum, i); + } + } + return res; + } + } + + public class UnitTest { + + } + +} From 1c2f904d95c64b03ee31a2a0829b3879fbe94577 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Mon, 8 Oct 2018 08:59:26 -0700 Subject: [PATCH 444/456] add average_of_levels_binary_tree --- .../AvgLevelsBTree.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/average_of_levels_btree/AvgLevelsBTree.java diff --git a/src/main/java/average_of_levels_btree/AvgLevelsBTree.java b/src/main/java/average_of_levels_btree/AvgLevelsBTree.java new file mode 100644 index 0000000..37fb62b --- /dev/null +++ b/src/main/java/average_of_levels_btree/AvgLevelsBTree.java @@ -0,0 +1,42 @@ +package average_of_levels_btree; + +import common.TreeNode; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +/** + * Created by lxie on 10/8/18. + */ +public class AvgLevelsBTree { + + public class Solution { + + List averageOfLevels(TreeNode root) { + List res = new ArrayList<>(); + if (root == null) return res; + Queue q = new LinkedList<>(); q.add(root); + while (!q.isEmpty()) { + int n = q.size(); + double sum = 0; + for (int i = 0; i < n; ++i) { + TreeNode t = q.peek(); q.poll(); + sum += t.val; + if (t.left != null) q.add(t.left); + if (t.right != null) q.add(t.right); + } + res.add(sum / n); + } + return res; + } + + } + + public class UnitTest { + + + } + +} From ebf8623cfec76e42974b37745c472eaf59096747 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 9 Oct 2018 09:50:57 -0700 Subject: [PATCH 445/456] add two_sum_iv --- .../AvgLevelsBTree.java | 2 +- .../SearchAutoComplete.java | 2 +- src/main/java/two_sum_iv/TwoSumIV.java | 35 +++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 src/main/java/two_sum_iv/TwoSumIV.java diff --git a/src/main/java/average_of_levels_btree/AvgLevelsBTree.java b/src/main/java/average_of_levels_btree/AvgLevelsBTree.java index 37fb62b..1af0375 100644 --- a/src/main/java/average_of_levels_btree/AvgLevelsBTree.java +++ b/src/main/java/average_of_levels_btree/AvgLevelsBTree.java @@ -31,7 +31,7 @@ List averageOfLevels(TreeNode root) { } return res; } - + } public class UnitTest { diff --git a/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java b/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java index e8e1e06..281ada7 100644 --- a/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java +++ b/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java @@ -36,7 +36,7 @@ public List input(char c) { @Override public int compare(Pair o1, Pair o2) { if (o1.getValue() != o2.getValue()) - return o1.getValue() - o1.getValue(); + return o2.getValue() - o1.getValue(); // max heap else return o1.getKey().compareTo(o2.getKey()); }}); diff --git a/src/main/java/two_sum_iv/TwoSumIV.java b/src/main/java/two_sum_iv/TwoSumIV.java new file mode 100644 index 0000000..1e33b0c --- /dev/null +++ b/src/main/java/two_sum_iv/TwoSumIV.java @@ -0,0 +1,35 @@ +package two_sum_iv; + +import common.TreeNode; + +import java.util.HashSet; +import java.util.Set; + +/** + * Created by lxie on 10/9/18. + */ +public class TwoSumIV { + + public class Solution { + + public boolean findTarget(TreeNode root, int k) { + if (root == null) return false; + Set s = new HashSet<>(); + return helper(root, k, s); + } + + private boolean helper(TreeNode node, int k, Set s) { + if (node == null) return false; + if (s.contains(k - node.val)) return true; + s.add(node.val); + return helper(node.left, k, s) || helper(node.right, k, s); + } + + } + + public class UnitTest { + + + } + +} From 6083dcdf3660c2b59f2e97107d60e401ea4ab82e Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Tue, 9 Oct 2018 10:09:11 -0700 Subject: [PATCH 446/456] add number_of_longest_increasing_subsequence --- .../NumberOfLIS.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/number_of_longest_increasing_subsequence/NumberOfLIS.java diff --git a/src/main/java/number_of_longest_increasing_subsequence/NumberOfLIS.java b/src/main/java/number_of_longest_increasing_subsequence/NumberOfLIS.java new file mode 100644 index 0000000..4186466 --- /dev/null +++ b/src/main/java/number_of_longest_increasing_subsequence/NumberOfLIS.java @@ -0,0 +1,42 @@ +package number_of_longest_increasing_subsequence; + +import java.util.Arrays; + +/** + * Created by lxie on 10/9/18. + */ +public class NumberOfLIS { + + public class Solution { + + public int findNumberOfLIS(int[] nums) { + int res = 0, mx = 0, n = nums.length; + int[] len = new int[n]; Arrays.fill(len, 1); + int[] cnt = new int[n]; Arrays.fill(cnt, 1); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[i] <= nums[j]) continue; + if (len[i] == len[j] + 1) cnt[i] += cnt[j]; + else if (len[i] < len[j] + 1) { + len[i] = len[j] + 1; + cnt[i] = cnt[j]; + } + } + if (mx == len[i]) res += cnt[i]; + else if (mx < len[i]) { + mx = len[i]; + res = cnt[i]; + } + } + return res; + } + + } + + public class UnitTest { + + + + } + +} From 7dcce54d74a6e0893c03dd2aa1657c9b7e960dee Mon Sep 17 00:00:00 2001 From: leonxie Date: Thu, 28 Mar 2019 15:02:37 +0800 Subject: [PATCH 447/456] add support for google guava lib --- build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/build.gradle b/build.gradle index 1612599..cbe7090 100644 --- a/build.gradle +++ b/build.gradle @@ -25,6 +25,7 @@ repositories { dependencies { compile 'junit:junit:4.10' + compile group: 'com.google.guava', name: 'guava', version: '23.5-jre' } sourceSets.test.java.srcDir 'src/main/java' From 6d85a591dc82100dc14683965df83744fec1770c Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 27 Jan 2021 00:06:12 -0800 Subject: [PATCH 448/456] concurrent_hash_table --- .../ConcurrentHashTable.java | 30 +++ .../MyConcurrentHashTable.java | 211 ++++++++++++++++ .../MyConcurrentHashTableUnitTest.java | 235 ++++++++++++++++++ src/main/java/readme | 52 ++++ 4 files changed, 528 insertions(+) create mode 100644 src/main/java/concurrent_hash_table/ConcurrentHashTable.java create mode 100644 src/main/java/concurrent_hash_table/MyConcurrentHashTable.java create mode 100644 src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java create mode 100644 src/main/java/readme diff --git a/src/main/java/concurrent_hash_table/ConcurrentHashTable.java b/src/main/java/concurrent_hash_table/ConcurrentHashTable.java new file mode 100644 index 0000000..eeed8f2 --- /dev/null +++ b/src/main/java/concurrent_hash_table/ConcurrentHashTable.java @@ -0,0 +1,30 @@ +package concurrent_hash_table; + +public interface ConcurrentHashTable +{ + /* + * Concurrency setting, i.e., number of locks. + */ + public void setConcurrency(int numLocks); + + /* + * Get the value by key + * + */ + public V get(K key); + + /* + * Put the item to the hash table + */ + public void put(K key, V value); + + /* + * Remove an item from the hash table + */ + public void remove(K key); + + /* + * Get current total number of entries + */ + public int getTotal(); +} diff --git a/src/main/java/concurrent_hash_table/MyConcurrentHashTable.java b/src/main/java/concurrent_hash_table/MyConcurrentHashTable.java new file mode 100644 index 0000000..e3c4a8e --- /dev/null +++ b/src/main/java/concurrent_hash_table/MyConcurrentHashTable.java @@ -0,0 +1,211 @@ +package concurrent_hash_table; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.concurrent.locks.ReentrantLock; + +/** + * @author l.xie@salesforce.com + * @version $Revision$ + */ +public class MyConcurrentHashTable implements ConcurrentHashTable { + /** + * Total number of buckets. This is the concurrency setting. + */ + private static int _numBuckets = 1000; //default concurrency + /** + * Array list to store the hash buckets. We use an ArrayList instead of an array so that we can + * use generics. We explicitly use ArrayList (instead of List) because this needs to support + * efficient index based access. Similarly, we use LinkedList for the buckets, since they must + * support efficient insert and delete. + *

+ * Alternatively we could use "Node[] _buckets = new Node(_numBuckets);", but that + * requires an unchecked cast for the return value in "get". Note that you cannot create + * Node[] _buckets = new Node[_numBuckets] - that will not compile (generics error). + */ + private final ArrayList> _buckets = new ArrayList>(_numBuckets); + + /** + * Array of ReentrantLocks used to guard the hashtable buckets (LinkedLists) from concurrent + * access. The lock array is the same size as the bucket array, but that is not strictly necessary. + * Using fewer locks would simply mean more than one bucket is guarded by each lock + *

+ * We could allow a concurrency factor to be passed to the constructor and and calculate + * an appropriate number of locks from that, but do not do that here for simplicity sake. + */ + private final ArrayList _bucketLocks = new ArrayList(_numBuckets); + + /** + * Create a new, empty hashtable. + */ + public MyConcurrentHashTable(int concurrency) { + // Initialize the buckets and locks. + // We must initialize the _buckets or else _buckets.size() is zero and we get + // OutOfBoundsExceptions. If we used an array instead of ArrayList then we would not have to + // initialize _buckets (since arrays elements automatically initialize to null). + setConcurrency(concurrency); + for (int i = 0; i < _numBuckets; i++) { + _bucketLocks.add(new ReentrantLock()); + _buckets.add(null); + } + } + + @Override + public void setConcurrency(int numLocks) { + _numBuckets = numLocks; + } + + /** + * Return the value associated with the given key. If the key does not exist then return null. + * + * @param key key to lookup + * @return value associated with key; null if none exists + * @throws NullPointerException if key is null + */ + @Override + public V get(K key) { + try { + // Lock and get the bucket for this key + LinkedList bucket = lockAndReturnBucket(key); + + // Iterate through the bucket looking for the key. If we find it, return the value. + for (Node node : bucket) { + if (node.key.equals(key)) { + return node.value; + } + } + + // We did not find the key. Return null. + return null; + } finally { + // Unlock the bucket + unlockBucket(key); + } + } + + /** + * Add the key-value pair to the hashtable. If the key already exists, it's value will be + * overwritten. Key and value must be non-null. + * + * @param key the key + * @param value the value + * @throws NullPointerException if key or value are null + */ + @Override + public void put(K key, V value) { + try { + // Lock and get the bucket for this key + LinkedList bucket = lockAndReturnBucket(key); + + // Iterate through the bucket looking for the key. If we find it then replace the value and return. + for (Node node : bucket) { + if (node.key.equals(key)) { + node.value = value; + return; + } + } + + // We did not find the key already in the bucket. Add it and return. + bucket.add(new Node(key, value)); + } finally { + // Unlock the bucket + unlockBucket(key); + } + } + + /** + * Obtain a lock on the bucket for the given key, then return the bucket. All calls + * to this method must be followed by a call to {@see #unlockBucket(K)} in a + * {@code finally} block. + * + * @param key the desired bucket's key + */ + private LinkedList lockAndReturnBucket(K key) { + // Calculate the hash code for the key, then convert that to the index within the + // buckets List. + int hashCode = key.hashCode(); + int bucketIndex = Math.abs(hashCode % _numBuckets); + + _bucketLocks.get(bucketIndex).lock(); + + // Find the LinkedList in the buckets array. If we haven't initialized that bucket yet + // then create a new LinkedList and put it at the correct spot in the list. + LinkedList bucket = _buckets.get(bucketIndex); + if (bucket == null) { + bucket = new LinkedList(); + _buckets.set(bucketIndex, bucket); + } + + // Return the LinkedList bucket + return bucket; + } + + /** + * Unlock a bucket that was previously locked with a call to {@see #lockAndReturnBucket(K)}. + * + * @param key the bucket's key + */ + private void unlockBucket(K key) { + // Calculate the hash code for the key, then convert that to the index within the + // buckets List. + int hashCode = key.hashCode(); + int bucketIndex = Math.abs(hashCode % _numBuckets); + + _bucketLocks.get(bucketIndex).unlock(); + } + + /** + * Inner class to represent a key-value pair in the LinkedList "buckets". + */ + public class Node { + K key; + V value; + + private Node(K key, V value) { + this.key = key; + this.value = value; + } + } + + // The remove method, which is not included in the interface, is shown below. The candidate does not need to write this method. I am adding it because I already have it written, and we may decide to add it to the interface in the future. + /** + * Remove the given key (and its associated value) from this Hashtable. + * + * @param key key to lookup + * @throws NullPointerException if key is null + */ + @Override + public void remove(K key) { + try { + // Lock and get the bucket for this key + LinkedList bucket = lockAndReturnBucket(key); + + // Iterate over the bucket looking for the key. If we find it, remove it from the bucket. + // Notice that we use an explicit iterator so that we may call ".remove" on the iterator and + // remove the item. + Iterator bucketIterator = bucket.iterator(); + while (bucketIterator.hasNext()) { + Node node = bucketIterator.next(); + if (node.key.equals(key)) { + bucketIterator.remove(); + return; + } + } + } finally { + // Unlock the bucket + unlockBucket(key); + } + } + + @Override + public int getTotal() { + int total = 0; + System.out.println("stats in hash table"); + for (int i=0; i<_buckets.size(); ++i) { + System.out.println(i + " : " + _buckets.get(i).size()); + total += _buckets.get(i).size(); + } + return total; + } +} diff --git a/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java b/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java new file mode 100644 index 0000000..f3aafb7 --- /dev/null +++ b/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java @@ -0,0 +1,235 @@ +package concurrent_hash_table; + +import org.junit.Assert; +import org.junit.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class MyConcurrentHashTableUnitTest { + private static final int MAX_ENTRIES = 1000000; + private static final int NUM_THREADS = 100; + private static MyConcurrentHashTable table; + private static Map result= new HashMap<>(); + + public MyConcurrentHashTableUnitTest() { + } + + @Test + public void testPut(){ // single thread puts + table = new MyConcurrentHashTable(1000); + for (int i = 0; i < MAX_ENTRIES; i++) { + int randomNum = ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE); + String randomString = generateRandomString(50); + table.put(randomNum, randomString); + result.put(randomNum, randomString); + System.out.println("<" + randomNum + ", " + randomString + ">"); + } + Assert.assertEquals(result.size(), table.getTotal()); + } + + @Test + public void testGet(){ // single thread puts/gets + int hit_count = 0; + testPut(); + for (Map.Entry entry: result.entrySet()) { + String value = (String) table.get(entry.getKey()); + if (value != null && value.equals(entry.getValue())) { + hit_count++; + } + System.out.println("<" + entry.getKey() + "-> " + value + ">"); + } + Assert.assertEquals(result.size(), hit_count); + table.getTotal(); + } + + @Test + public void testRemove() { // single thread remove + testPut(); + for (Map.Entry entry : result.entrySet()) { + table.remove(entry.getKey()); + } + Assert.assertEquals(0, table.getTotal()); + } + + @Test + public void testPutFewBuckets(){ // test multi-thread puts on single bucket + table = new MyConcurrentHashTable(200); + long latency = multiputTest(); + assert(latency > 40000); + } + + @Test + public void testPutMultiBuckets(){ // test multi-thread puts on multi buckets + table = new MyConcurrentHashTable(1000); + long latency = multiputTest(); + assert(latency < 20000); + } + + @Test + public void testPutMultiMoreBuckets(){ // test multi-thread puts on multi buckets + table = new MyConcurrentHashTable(5000); + long latency = multiputTest(); + assert(latency < 15000); + } + + @Test + public void testPutMultiMostBuckets(){ // test multi-thread puts on multi buckets + table = new MyConcurrentHashTable(10000); + long latency = multiputTest(); + assert(latency < 13000); + } + + @Test + public void testPutAndGetMultiBuckets(){ // test multi-thread puts on multi buckets + table = new MyConcurrentHashTable(10000); + long latency = multiputAndGetTest(); + assert(latency < 30000); + } + + private long multiputTest() { + Instant start = Instant.now(); + List threads = new ArrayList<>(); + for (int i=0; i threads = new ArrayList<>(); + for (int i=0; i"); + } + } catch (Exception e) { + // Throwing an exception + System.out.println("Exception is caught"); + } + } +} + +// Multi Gets thread creation by extending +// the Thread class +class MultithreadGet extends Thread { + int threadId = 0; + int batchSize = 0; + MyConcurrentHashTable table; + + public MultithreadGet(MyConcurrentHashTable table, int batchSize, int id) { + this.threadId = id; + this.batchSize = batchSize; + this.table = table; + } + + public void run() { + try { + // Displaying the thread that is running + System.out.println("Thread " + threadId + " is running"); + for (int i = 0; i < batchSize; i++) { + int randomNum = ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE); + //String randomString = MyConcurrentHashTableUnitTest.generateRandomString(50); + String value = (String) table.get(randomNum); + //keys.add(randomNum); + System.out.println("<" + randomNum + "-> " + value + ">"); + } + } catch (Exception e) { + // Throwing an exception + System.out.println("Exception is caught"); + } + } +} \ No newline at end of file diff --git a/src/main/java/readme b/src/main/java/readme new file mode 100644 index 0000000..b60ce89 --- /dev/null +++ b/src/main/java/readme @@ -0,0 +1,52 @@ +Implement a concurrent hash table + +We need to implement a concurrent hash table. This implementation should not use any of the existing HashMap library in Java. It should implement a hash table from scratch (given the interface). + +We need to implement the following methods for the hash table + +Get, Put, Remove + +And, we need to design our approach to achieve the maximum concurrency and scalability while doing these operations. This means that, we should not block other operations if they are not operating on the same entry. This also means that, we should save system resource (e.g., locks, semaphores) in order to be scalable. + + +Output: A JAVA class implementation of the concurrent hash table. An analysis on why you choose the approach and how do you optimize the concurrency and achieve scalability. + + +Tests: write a test class to verify the implementation. The test should include: + +1. single thread hash-table operations +2. multiple threads hash-table operations - on different record(s) +3. multiple threads hash-table operations - on same record(s) +4. different settings/configs for the hash table +5. exception handlings + + +Interface to implement +/* + * Concurrent hash table implementation. + * Expected to be used in a multi-threading env + */ +public interface ConcurrentHashTable +{ + /* + * Concurrency setting, i.e., number of locks. + */ + public void init(int numLocks); + + /* + * Get the value by key + * + */ + public V get(K key); + + /* + * Put the item to the hash table + */ + public void put(K key, V value); + + /* + * Remove an item from the hash table + */ + public void remove(K key); +} + From 8ebf363447526cb7bf73b126f95a6f7b91f0c046 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 27 Jan 2021 00:09:22 -0800 Subject: [PATCH 449/456] move readme --- src/main/java/concurrent_hash_table/readme | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/concurrent_hash_table/readme diff --git a/src/main/java/concurrent_hash_table/readme b/src/main/java/concurrent_hash_table/readme new file mode 100644 index 0000000..b60ce89 --- /dev/null +++ b/src/main/java/concurrent_hash_table/readme @@ -0,0 +1,52 @@ +Implement a concurrent hash table + +We need to implement a concurrent hash table. This implementation should not use any of the existing HashMap library in Java. It should implement a hash table from scratch (given the interface). + +We need to implement the following methods for the hash table + +Get, Put, Remove + +And, we need to design our approach to achieve the maximum concurrency and scalability while doing these operations. This means that, we should not block other operations if they are not operating on the same entry. This also means that, we should save system resource (e.g., locks, semaphores) in order to be scalable. + + +Output: A JAVA class implementation of the concurrent hash table. An analysis on why you choose the approach and how do you optimize the concurrency and achieve scalability. + + +Tests: write a test class to verify the implementation. The test should include: + +1. single thread hash-table operations +2. multiple threads hash-table operations - on different record(s) +3. multiple threads hash-table operations - on same record(s) +4. different settings/configs for the hash table +5. exception handlings + + +Interface to implement +/* + * Concurrent hash table implementation. + * Expected to be used in a multi-threading env + */ +public interface ConcurrentHashTable +{ + /* + * Concurrency setting, i.e., number of locks. + */ + public void init(int numLocks); + + /* + * Get the value by key + * + */ + public V get(K key); + + /* + * Put the item to the hash table + */ + public void put(K key, V value); + + /* + * Remove an item from the hash table + */ + public void remove(K key); +} + From 199561f73ff69db32ce2dbd171715a04b00c50a8 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 27 Jan 2021 00:13:43 -0800 Subject: [PATCH 450/456] change test name for concurrent hash table --- .../MyConcurrentHashTableUnitTest.java | 10 ++-- src/main/java/readme | 52 ------------------- 2 files changed, 5 insertions(+), 57 deletions(-) delete mode 100644 src/main/java/readme diff --git a/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java b/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java index f3aafb7..b0118ba 100644 --- a/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java +++ b/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java @@ -55,35 +55,35 @@ public void testRemove() { // single thread remove } @Test - public void testPutFewBuckets(){ // test multi-thread puts on single bucket + public void testMultiPutLowBuckets(){ // test multi-thread puts on single bucket table = new MyConcurrentHashTable(200); long latency = multiputTest(); assert(latency > 40000); } @Test - public void testPutMultiBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutDefaultBuckets(){ // test multi-thread puts on multi buckets table = new MyConcurrentHashTable(1000); long latency = multiputTest(); assert(latency < 20000); } @Test - public void testPutMultiMoreBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutMoreBuckets(){ // test multi-thread puts on multi buckets table = new MyConcurrentHashTable(5000); long latency = multiputTest(); assert(latency < 15000); } @Test - public void testPutMultiMostBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutMaxBuckets(){ // test multi-thread puts on multi buckets table = new MyConcurrentHashTable(10000); long latency = multiputTest(); assert(latency < 13000); } @Test - public void testPutAndGetMultiBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutAndGetDefaultBuckets(){ // test multi-thread puts on multi buckets table = new MyConcurrentHashTable(10000); long latency = multiputAndGetTest(); assert(latency < 30000); diff --git a/src/main/java/readme b/src/main/java/readme deleted file mode 100644 index b60ce89..0000000 --- a/src/main/java/readme +++ /dev/null @@ -1,52 +0,0 @@ -Implement a concurrent hash table - -We need to implement a concurrent hash table. This implementation should not use any of the existing HashMap library in Java. It should implement a hash table from scratch (given the interface). - -We need to implement the following methods for the hash table - -Get, Put, Remove - -And, we need to design our approach to achieve the maximum concurrency and scalability while doing these operations. This means that, we should not block other operations if they are not operating on the same entry. This also means that, we should save system resource (e.g., locks, semaphores) in order to be scalable. - - -Output: A JAVA class implementation of the concurrent hash table. An analysis on why you choose the approach and how do you optimize the concurrency and achieve scalability. - - -Tests: write a test class to verify the implementation. The test should include: - -1. single thread hash-table operations -2. multiple threads hash-table operations - on different record(s) -3. multiple threads hash-table operations - on same record(s) -4. different settings/configs for the hash table -5. exception handlings - - -Interface to implement -/* - * Concurrent hash table implementation. - * Expected to be used in a multi-threading env - */ -public interface ConcurrentHashTable -{ - /* - * Concurrency setting, i.e., number of locks. - */ - public void init(int numLocks); - - /* - * Get the value by key - * - */ - public V get(K key); - - /* - * Put the item to the hash table - */ - public void put(K key, V value); - - /* - * Remove an item from the hash table - */ - public void remove(K key); -} - From f07e71228559b146962d15f1705dbb3a348c5747 Mon Sep 17 00:00:00 2001 From: Leon Tse Date: Wed, 27 Jan 2021 00:15:46 -0800 Subject: [PATCH 451/456] change test name for concurrent hash table --- .../MyConcurrentHashTableUnitTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java b/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java index b0118ba..4217552 100644 --- a/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java +++ b/src/main/java/concurrent_hash_table/MyConcurrentHashTableUnitTest.java @@ -55,35 +55,35 @@ public void testRemove() { // single thread remove } @Test - public void testMultiPutLowBuckets(){ // test multi-thread puts on single bucket + public void testMultiPutLowBuckets(){ // test multi-thread puts on low buckets table = new MyConcurrentHashTable(200); long latency = multiputTest(); assert(latency > 40000); } @Test - public void testMultiPutDefaultBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutDefaultBuckets(){ // test multi-thread puts on default buckets table = new MyConcurrentHashTable(1000); long latency = multiputTest(); assert(latency < 20000); } @Test - public void testMultiPutMoreBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutMoreBuckets(){ // test multi-thread puts on more buckets table = new MyConcurrentHashTable(5000); long latency = multiputTest(); assert(latency < 15000); } @Test - public void testMultiPutMaxBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutMaxBuckets(){ // test multi-thread puts on max buckets table = new MyConcurrentHashTable(10000); long latency = multiputTest(); assert(latency < 13000); } @Test - public void testMultiPutAndGetDefaultBuckets(){ // test multi-thread puts on multi buckets + public void testMultiPutAndGetDefaultBuckets(){ // test multi-thread puts and gets on default buckets table = new MyConcurrentHashTable(10000); long latency = multiputAndGetTest(); assert(latency < 30000); From f74e7030dbe05a69a233b38570969211d82a5506 Mon Sep 17 00:00:00 2001 From: Liang Xie Date: Fri, 1 Apr 2022 02:21:46 -0700 Subject: [PATCH 452/456] version upgrade --- build.gradle | 6 +++--- gradle/wrapper/gradle-wrapper.properties | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index cbe7090..c7b56ad 100644 --- a/build.gradle +++ b/build.gradle @@ -2,8 +2,8 @@ apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' -sourceCompatibility = JavaVersion.VERSION_1_6 -targetCompatibility = JavaVersion.VERSION_1_6 +sourceCompatibility = JavaVersion.VERSION_1_8 +targetCompatibility = JavaVersion.VERSION_1_8 [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' @@ -31,7 +31,7 @@ dependencies { sourceSets.test.java.srcDir 'src/main/java' task wrapper(type: Wrapper) { - gradleVersion = '1.8' + gradleVersion = '4.8.1' } task(question) << { diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 71233fc..2336ccd 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-1.8-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip From b76f60fa537ef5271458910a4d9cde4e431e239f Mon Sep 17 00:00:00 2001 From: Liang Xie Date: Sun, 31 Jul 2022 20:50:04 -0700 Subject: [PATCH 453/456] add some tests --- .../FindLeavesOfBinaryTree.java | 20 ++++++++++--------- .../LongestSubstringKRepeatingChars.java | 2 +- src/main/java/sqrt_x/SqrtX.java | 4 ++-- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java b/src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java index 2040500..4600798 100644 --- a/src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java +++ b/src/main/java/find_leaves_of_binary_tree/FindLeavesOfBinaryTree.java @@ -1,20 +1,14 @@ package find_leaves_of_binary_tree; import java.util.ArrayList; +import common.TreeNode; /** * Created by lxie on 9/9/17. */ public class FindLeavesOfBinaryTree { - public class TreeNode { - int val; - TreeNode left; - TreeNode right; - TreeNode(int x) { val = x; } - } - - class Solution { + public static class Solution { public ArrayList> findLeaves(TreeNode root){ ArrayList> res = new ArrayList>(); helper(root, res); @@ -34,7 +28,15 @@ private int helper(TreeNode root, ArrayList> res) { public static void main(String[] args) { System.out.println("this is for test"); - } + Solution sol = new Solution(); + TreeNode root = new TreeNode(10); + root.left = new TreeNode(5); root.right = new TreeNode(15); + root.left.left = new TreeNode(1); root.left.right = new TreeNode(8); + root.right.right = new TreeNode(7); + + ArrayList> result = sol.findLeaves(root); + System.out.print(result); + } } diff --git a/src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java b/src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java index 3f426e3..cce1e67 100644 --- a/src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java +++ b/src/main/java/longest_substring_k_repeating_chars/LongestSubstringKRepeatingChars.java @@ -35,7 +35,7 @@ public int longestSubstring(String s, int k) { public static void main(String[] args) { Solution sol = new Solution(); - System.out.println("result = " + sol.longestSubstring("a", 1)); + System.out.println("result = " + sol.longestSubstring("ababbc", 2)); } } diff --git a/src/main/java/sqrt_x/SqrtX.java b/src/main/java/sqrt_x/SqrtX.java index 82accb1..256a1fe 100644 --- a/src/main/java/sqrt_x/SqrtX.java +++ b/src/main/java/sqrt_x/SqrtX.java @@ -7,8 +7,8 @@ public class Solution { public int SqrtX(int x) { long left = 0, right = (x / 2) + 1; while (left <= right) { - long mid = (left + right) / 2; - long sq = mid * mid; + long mid = (left + right) / 2; + long sq = mid * mid; if (sq == x) return (int) mid; else if (sq < x) left = mid + 1; else right = mid - 1; From eb33b8bfbef2568b3e77da38492ac34656da0799 Mon Sep 17 00:00:00 2001 From: Liang Xie Date: Sat, 18 Nov 2023 01:39:35 -0800 Subject: [PATCH 454/456] remove javafx.Pair --- src/main/java/LFU_cache/LFUCache.java | 10 +++++----- src/main/java/common/Pair.java | 13 +++++++++++++ .../SearchAutoComplete.java | 8 ++++---- .../MinUniqueWordAbbrev.java | 15 ++++++++------- .../RearrangeStringKDistance.java | 12 ++++++------ src/main/java/relative_ranks/RelativeRanks.java | 13 +++++++------ .../sentence_similarity/SentenceSimilarity.java | 14 +++++++------- .../SortCharsByFrequency.java | 12 ++++++------ .../trapping_rain_water_II/TrapRainWaterII.java | 15 ++++++++------- 9 files changed, 64 insertions(+), 48 deletions(-) create mode 100644 src/main/java/common/Pair.java diff --git a/src/main/java/LFU_cache/LFUCache.java b/src/main/java/LFU_cache/LFUCache.java index af9ead0..62d8e69 100644 --- a/src/main/java/LFU_cache/LFUCache.java +++ b/src/main/java/LFU_cache/LFUCache.java @@ -1,6 +1,6 @@ package LFU_cache; -import javafx.util.Pair; +import common.Pair; import java.util.ArrayList; import java.util.HashMap; @@ -13,7 +13,7 @@ public class LFUCache { private int cap, minFreq; - private Map> m = new HashMap<>(); // key - value, freq + private Map> m = new HashMap<>(); // key - value, freq private Map> freq = new HashMap<>(); // freq - keys private Map iter = new HashMap<>(); // key - key_pos in freq @@ -24,7 +24,7 @@ public LFUCache(int capacity) { public int get(int key) { if (!m.containsKey(key)) return -1; freq.get(m.get(key).getValue()).remove((int)iter.get(key)); - m.put(key, new Pair(m.get(key).getKey(), m.get(key).getValue()+1)); + m.put(key, Pair.of(m.get(key).getKey(), m.get(key).getValue()+1)); if (!freq.containsKey(m.get(key).getValue())) freq.put(m.get(key).getValue(), new ArrayList<>()); freq.get(m.get(key).getValue()).add(key); @@ -36,7 +36,7 @@ public int get(int key) { public void put(int key, int value) { if (cap <= 0) return; if (get(key) != -1) { - m.put(key, new Pair(value, 1)); + m.put(key, Pair.of(value, 1)); return; } if (m.size() >= cap) { @@ -44,7 +44,7 @@ public void put(int key, int value) { iter.remove(freq.get(minFreq).get(0)); freq.get(minFreq).remove(0); } - m.put(key, new Pair(value, 1)); + m.put(key, Pair.of(value, 1)); if (!freq.containsKey(1)) freq.put(1, new ArrayList<>()); freq.get(1).add(key); iter.put(key, freq.get(1).size() - 1); diff --git a/src/main/java/common/Pair.java b/src/main/java/common/Pair.java new file mode 100644 index 0000000..d63f0d5 --- /dev/null +++ b/src/main/java/common/Pair.java @@ -0,0 +1,13 @@ +package common; + +import java.util.AbstractMap; +import java.util.Map; + +public class Pair { + + // Return a map entry (key-value pair) from the specified values + public static Map.Entry of(T first, U second) { + return new AbstractMap.SimpleEntry<>(first, second); + } + +} \ No newline at end of file diff --git a/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java b/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java index 281ada7..01ff3ec 100644 --- a/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java +++ b/src/main/java/design_search_autocomplete_system/SearchAutoComplete.java @@ -1,6 +1,6 @@ package design_search_autocomplete_system; -import javafx.util.Pair; +import common.Pair; import java.util.*; @@ -32,9 +32,9 @@ public List input(char c) { return null; } data += c; - PriorityQueue> q = new PriorityQueue<>(50, new Comparator>() { + PriorityQueue> q = new PriorityQueue<>(50, new Comparator>() { @Override - public int compare(Pair o1, Pair o2) { + public int compare(Map.Entry o1, Map.Entry o2) { if (o1.getValue() != o2.getValue()) return o2.getValue() - o1.getValue(); // max heap else @@ -50,7 +50,7 @@ public int compare(Pair o1, Pair o2) { } } if (matched) { - q.add(new Pair(f.getKey(), f.getValue())); + q.add(Pair.of(f.getKey(), f.getValue())); if (q.size() > 3) q.poll(); } } diff --git a/src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java b/src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java index da8fb60..e74c569 100644 --- a/src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java +++ b/src/main/java/min_unique_word_abbrev/MinUniqueWordAbbrev.java @@ -1,8 +1,9 @@ package min_unique_word_abbrev; -import javafx.util.Pair; +import common.Pair; import java.util.Comparator; +import java.util.Map; import java.util.PriorityQueue; /** @@ -14,10 +15,10 @@ public class Solution { public String minAbbreviation(String target, String[] dictionary) { if (dictionary.length == 0) return Integer.toString((int)target.length()); //priority_queue, vector>, greater>> q; - PriorityQueue> q; + PriorityQueue> q; q = generate(target); while (!q.isEmpty()) { - Pair t = q.peek(); q.poll(); + Map.Entry t = q.peek(); q.poll(); boolean no_conflict = true; for (String word : dictionary) { if (valid(word, t.getValue())) { @@ -31,10 +32,10 @@ public String minAbbreviation(String target, String[] dictionary) { } - private PriorityQueue> generate(String target) { - PriorityQueue> res = new PriorityQueue<>(50, new Comparator>() { + private PriorityQueue> generate(String target) { + PriorityQueue> res = new PriorityQueue<>(50, new Comparator>() { @Override - public int compare(Pair o1, Pair o2) { + public int compare(Map.Entry o1, Map.Entry o2) { return o1.getKey() - o2.getKey(); } }); @@ -57,7 +58,7 @@ public int compare(Pair o1, Pair o2) { out += Integer.toString(cnt); ++size; } - res.add(new Pair(size, out)); + res.add(Pair.of(size, out)); } return res; } diff --git a/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java b/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java index e6f3726..a007684 100644 --- a/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java +++ b/src/main/java/rearrange_string_k_distance/RearrangeStringKDistance.java @@ -1,6 +1,6 @@ package rearrange_string_k_distance; -import javafx.util.Pair; +import common.Pair; import java.util.*; @@ -14,27 +14,27 @@ public String RearrangeString(String str, int k) { String res = ""; int len = str.length(); Map m = new HashMap<>(); - PriorityQueue> q = new PriorityQueue<>(); + PriorityQueue> q = new PriorityQueue<>(); for (char a : str.toCharArray()) { if (!m.containsKey(a)) m.put(a, 1); else m.put(a, m.get(a)+1); }; for (Map.Entry entry : m.entrySet()) { - q.add(new Pair(entry.getValue(), entry.getKey())); + q.add(Pair.of(entry.getValue(), entry.getKey())); } while (!q.isEmpty()) { - List> v = new ArrayList<>(); // for temp store + List> v = new ArrayList<>(); // for temp store int cnt = Integer.min(k, len); for (int i = 0; i < cnt; ++i) { if (q.isEmpty()) return ""; - Pair t = q.peek(); q.poll(); // highest count first + Map.Entry t = q.peek(); q.poll(); // highest count first res += t.getValue(); int count = t.getKey(); if (--count > 0) v.add(t); --len; } - for (Pair a : v) q.add(a); + for (Map.Entry a : v) q.add(a); } return res; diff --git a/src/main/java/relative_ranks/RelativeRanks.java b/src/main/java/relative_ranks/RelativeRanks.java index e20acef..6dbda66 100644 --- a/src/main/java/relative_ranks/RelativeRanks.java +++ b/src/main/java/relative_ranks/RelativeRanks.java @@ -1,8 +1,9 @@ package relative_ranks; -import javafx.util.Pair; +import common.Pair; import java.util.Comparator; +import java.util.Map; import java.util.PriorityQueue; /** @@ -15,16 +16,16 @@ public class Solution { public String[] findRelativeRanks(int[] nums) { int n = nums.length, cnt = 1; String[] res = new String[n]; - PriorityQueue> q = - new PriorityQueue>(10, - new Comparator>() { + PriorityQueue> q = + new PriorityQueue>(10, + new Comparator>() { @Override - public int compare(Pair p1, Pair p2) { + public int compare(Map.Entry p1, Map.Entry p2) { return p2.getKey() - p1.getKey(); } }); for (int i = 0; i < n; ++i) { - q.add(new Pair(nums[i], i)); + q.add(Pair.of(nums[i], i)); } for (int i = 0; i < n; ++i) { int idx = q.peek().getValue(); q.poll(); diff --git a/src/main/java/sentence_similarity/SentenceSimilarity.java b/src/main/java/sentence_similarity/SentenceSimilarity.java index 87083fa..d0c7aab 100644 --- a/src/main/java/sentence_similarity/SentenceSimilarity.java +++ b/src/main/java/sentence_similarity/SentenceSimilarity.java @@ -1,6 +1,6 @@ package sentence_similarity; -import javafx.util.Pair; +import common.Pair; import java.util.*; @@ -9,11 +9,11 @@ */ public class SentenceSimilarity { - public boolean areSentencesSimilar(String[] words1, String[] words2, List> pairs) { + public boolean areSentencesSimilar(String[] words1, String[] words2, List> pairs) { if (words1.length != words2.length) return false; Map> m = new HashMap<>(); - for (Pair pair : pairs) { + for (Map.Entry pair : pairs) { //m[pair.first].insert(pair.second); if (!m.containsKey(pair.getKey())) { m.put(pair.getKey(), new HashSet<>(Arrays.asList(pair.getValue()))); @@ -34,10 +34,10 @@ public static void main(String[] args) { SentenceSimilarity ss = new SentenceSimilarity(); String[] words1 = {"great", "acting", "skills"}; String[] words2 = {"fine", "drama", "talent"}; - List> pairs = new ArrayList<>(); - pairs.add(new Pair<>("great", "fine")); - pairs.add(new Pair<>("acting", "drama")); - pairs.add(new Pair<>("skills", "talent")); + List> pairs = new ArrayList<>(); + pairs.add(Pair.of("great", "fine")); + pairs.add(Pair.of("acting", "drama")); + pairs.add(Pair.of("skills", "talent")); System.out.println(ss.areSentencesSimilar(words1, words2, pairs)); diff --git a/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java index 8328790..05e44b1 100644 --- a/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java +++ b/src/main/java/sort_chars_by_frequency/SortCharsByFrequency.java @@ -1,6 +1,6 @@ package sort_chars_by_frequency; -import javafx.util.Pair; +import common.Pair; import java.util.*; @@ -13,10 +13,10 @@ public class SortCharsByFrequency { public String frequencySort(String s) { String res = ""; - PriorityQueue> q = new PriorityQueue<>(100, - new Comparator>() { + PriorityQueue> q = new PriorityQueue<>(100, + new Comparator>() { @Override - public int compare(Pair o1, Pair o2) { + public int compare(Map.Entry o1, Map.Entry o2) { return o2.getKey() - o1.getKey(); } }); @@ -29,9 +29,9 @@ public int compare(Pair o1, Pair o2) { m.put(c, 1); } for (Map.Entry a : m.entrySet()) - q.add(new Pair(a.getValue(), a.getKey())); + q.add(Pair.of(a.getValue(), a.getKey())); while (!q.isEmpty()) { - Pair t = q.peek(); q.poll(); + Map.Entry t = q.peek(); q.poll(); for (int i=0; i> q = new PriorityQueue<>(100, comparator); + PriorityQueue> q = new PriorityQueue<>(100, comparator);; boolean[][] visited = new boolean[m][n]; int[][] dir = {{0,-1},{-1,0},{0,1},{1,0}}; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { - q.offer(new Pair(heightMap[i][j], i * n + j)); + q.offer(Pair.of(heightMap[i][j], i * n + j)); visited[i][j] = true; } } } while (!q.isEmpty()) { - Pair t = q.poll(); + Map.Entry t = q.poll(); int h = t.getKey(), r = t.getValue() / n, c = t.getValue() % n; mx = Math.max(mx, h); for (int i = 0; i < dir.length; ++i) { @@ -35,16 +36,16 @@ public int trapRainWater(int[][] heightMap) { if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue; visited[x][y] = true; if (heightMap[x][y] < mx) res += mx - heightMap[x][y]; // LC 42 - q.offer(new Pair(heightMap[x][y], x * n + y)); + q.offer(Pair.of(heightMap[x][y], x * n + y)); } } return res; } - class PairComparator implements Comparator> { + class PairComparator implements Comparator> { @Override - public int compare(Pair p1, Pair p2) { + public int compare(Map.Entry p1, Map.Entry p2) { return p1.getKey() - p2.getKey(); } } From 720b12c8455d39965516a61f603b6ccf64b84884 Mon Sep 17 00:00:00 2001 From: Liang Xie Date: Tue, 5 Nov 2024 15:15:24 -0800 Subject: [PATCH 455/456] change reverse_k_group --- .../ReverseNodesinkGroup.java | 68 +++++++++---------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java b/src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java index 8585bd8..900e8e6 100644 --- a/src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java +++ b/src/main/java/reverse_nodes_in_kgroup/ReverseNodesinkGroup.java @@ -4,47 +4,47 @@ public class ReverseNodesinkGroup { - public class Solution { - private ListNode reverseGroup(ListNode start, ListNode end) { - ListNode prefix = start.next; - ListNode p = prefix.next; - while (p != end) { - ListNode temp = p.next; - p.next = prefix; - prefix = p; - p = temp; + public static class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + ListNode cur = head; + for (int i = 0; i < k; ++i) { + if (cur == null) return head; + cur = cur.next; } - ListNode temp = start.next; - start.next = prefix; - temp.next = end; - return temp; + ListNode new_head = reverse(head, cur); + head.next = reverseKGroup(cur, k); + return new_head; } - public ListNode reverseKGroup(ListNode head, int k) { - if (k == 0) { - return head; - } - ListNode dummy = new ListNode(0); - dummy.next = head; - ListNode start = dummy; - ListNode end = start.next; - int count = 0; - while (end != null) { - if (count == k) { - start = reverseGroup(start, end); - count = 0; - } - count++; - end = end.next; + public ListNode reverse(ListNode head, ListNode tail) { + ListNode pre = tail; + while (head != tail) { + ListNode t = head.next; + head.next = pre; + pre = head; + head = t; } - if (count == k) { - reverseGroup(start, end); - } - return dummy.next; + return pre; } } - public static class UnitTest { + public static void main(String[] args) { + Solution test = new Solution(); + ListNode node1 = new ListNode(1); + ListNode node2 = new ListNode(2); + ListNode node3 = new ListNode(3); + ListNode node4 = new ListNode(4); + ListNode node5 = new ListNode(5); + + node1.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node5; + ListNode head = test.reverseKGroup(node1, 3); + while (head != null) { + System.out.println(head.val + " "); + head = head.next; + } } } From 9e04289c7abeab12e8eafc2ddb45ac625b5a8efe Mon Sep 17 00:00:00 2001 From: Liang Xie Date: Mon, 11 Nov 2024 00:35:50 -0800 Subject: [PATCH 456/456] unit test and fixes --- src/main/java/divide_two_integers/DivideTwoIntegers.java | 3 +++ .../java/search_insert_position/SearchInsertPosition.java | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/divide_two_integers/DivideTwoIntegers.java b/src/main/java/divide_two_integers/DivideTwoIntegers.java index 3816eb1..4c6d1d2 100644 --- a/src/main/java/divide_two_integers/DivideTwoIntegers.java +++ b/src/main/java/divide_two_integers/DivideTwoIntegers.java @@ -1,7 +1,10 @@ package divide_two_integers; import org.junit.Test; +import org.junit.experimental.runners.Enclosed; +import org.junit.runner.RunWith; +@RunWith(Enclosed.class) public class DivideTwoIntegers { public class Solution { diff --git a/src/main/java/search_insert_position/SearchInsertPosition.java b/src/main/java/search_insert_position/SearchInsertPosition.java index 459f686..28f6513 100644 --- a/src/main/java/search_insert_position/SearchInsertPosition.java +++ b/src/main/java/search_insert_position/SearchInsertPosition.java @@ -6,15 +6,15 @@ public class Solution { public int searchInsert(int[] A, int target) { int left = 0; int right = A.length - 1; - while (left <= right) { + while (left < right) { int mid = left + (right - left) / 2; if (A[mid] < target) { left = mid + 1; } else { - right = mid - 1; + right = mid; } } - return left; + return right; } }