From fdcfaaa320294e1f8a38f55e046855e44d2ca5cb Mon Sep 17 00:00:00 2001 From: Ruofan Jin Date: Sun, 8 Nov 2015 14:09:54 -0500 Subject: [PATCH] My Solution Fisrt --- My Solutions/AddTwoNumbers.java | 46 ++++++ My Solutions/Anagram.java | 48 ++++++ My Solutions/BalancedPartition.java | 36 +++++ .../BestTimetoBuyandSellStockIII.java | 37 +++++ My Solutions/BinaryTreeTraversal.java | 58 +++++++ .../BinaryTreeZigzagLevelOrderTraversal.java | 82 ++++++++++ My Solutions/Candy.java | 52 +++++++ My Solutions/CatchThief.java | 31 ++++ My Solutions/CloneGraph.java | 48 ++++++ My Solutions/CombinationSum.java | 47 ++++++ My Solutions/Combinations.java | 41 +++++ My Solutions/CompareVersion.java | 22 +++ My Solutions/ContainsDuplicateIII.java | 39 +++++ My Solutions/ConvertSortedListToBST.java | 84 ++++++++++ My Solutions/CopyListWithRandomPointer.java | 43 ++++++ My Solutions/CountAndSay.java | 55 +++++++ My Solutions/CountPrimes.java | 35 +++++ My Solutions/DecodeWays.java | 58 +++++++ My Solutions/DivideTwoIntegers.java | 74 +++++++++ My Solutions/ExpressionAddOperators.java | 49 ++++++ My Solutions/FindMedian.java | 67 ++++++++ My Solutions/FindMedianfromDataStream.java | 55 +++++++ My Solutions/FirstMissingPositive.java | 31 ++++ My Solutions/FlatenBinaryTree.java | 32 ++++ My Solutions/FractionToRecurringDecimal.java | 47 ++++++ My Solutions/GameOfLive.java | 49 ++++++ My Solutions/GenerateParentheses.java | 43 ++++++ My Solutions/HappyNumber.java | 38 +++++ My Solutions/HouseRobber.java | 39 +++++ My Solutions/InorderPostorder.java | 43 ++++++ My Solutions/InsertInterval.java | 74 +++++++++ My Solutions/InsertionSortList.java | 70 +++++++++ My Solutions/Interval.java | 14 ++ My Solutions/JavaTest.java | 21 +++ My Solutions/KthLargestElementInAnArray.java | 49 ++++++ My Solutions/LRUCache.java | 82 ++++++++++ My Solutions/LRUCacheNew.java | 76 ++++++++++ My Solutions/LargestNumber.java | 40 +++++ My Solutions/LargestRectangleInHistogram.java | 52 +++++++ My Solutions/LetterCombination.java | 32 ++++ My Solutions/LevelOrderTraversal.java | 34 +++++ My Solutions/ListNode.java | 9 ++ .../LongestIncreasingSubsequence.java | 36 +++++ My Solutions/LongestPalindromeSubstring.java | 68 +++++++++ .../LongestSubstringWithoutRepeating.java | 33 ++++ My Solutions/LongestValidParentheses.java | 70 +++++++++ My Solutions/MaxPoint.java | 50 ++++++ My Solutions/MaximalRectangle.java | 92 +++++++++++ My Solutions/MaximalSquare.java | 33 ++++ My Solutions/MaximumGap.java | 67 ++++++++ My Solutions/MaximumProductSubarray.java | 59 ++++++++ My Solutions/MaximumSubarray.java | 28 ++++ My Solutions/MedianOfTwoSortedArray.java | 83 ++++++++++ My Solutions/MergeIntervals.java | 24 +++ My Solutions/MergeKSortedList.java | 54 +++++++ My Solutions/MergeSortedArray.java | 31 ++++ My Solutions/MinimumSizeSubarraySum.java | 64 ++++++++ My Solutions/MinimumWindowSubstring.java | 143 ++++++++++++++++++ My Solutions/NQueen.java | 67 ++++++++ My Solutions/NQueenII.java | 51 +++++++ My Solutions/NextPermutation.java | 40 +++++ My Solutions/Palindrome.java | 31 ++++ My Solutions/PalindromePartition.java | 73 +++++++++ My Solutions/PalindromePartitioningII.java | 29 ++++ My Solutions/PathSum.java | 38 +++++ My Solutions/PermutationSequence.java | 37 +++++ My Solutions/Permutations.java | 49 ++++++ My Solutions/PermutationsII.java | 51 +++++++ My Solutions/PhoneInterview.java | 67 ++++++++ My Solutions/PlusOne.java | 35 +++++ My Solutions/Point.java | 14 ++ .../PopulatingNextRightPointerInEachNode.java | 56 +++++++ ...opulatingNextRightPointerInEachNodeII.java | 72 +++++++++ My Solutions/RPN.java | 40 +++++ My Solutions/RandomListNode.java | 7 + My Solutions/RangeBitwiseAnd.java | 29 ++++ My Solutions/RecoverBinarySearchTree.java | 80 ++++++++++ My Solutions/RegularExpressionMatching.java | 42 +++++ My Solutions/RemoveDuplicate.java | 28 ++++ .../RemoveDuplicatesFromSortedArrayII.java | 32 ++++ My Solutions/RemoveDuplicatesII.java | 90 +++++++++++ My Solutions/ReorderList.java | 84 ++++++++++ My Solutions/RepeatedDNASequence.java | 48 ++++++ My Solutions/RestoreIPAddress.java | 51 +++++++ My Solutions/ReverseLinkedListII.java | 89 +++++++++++ My Solutions/ReverseNodeInKGroup.java | 44 ++++++ My Solutions/ReverseString.java | 33 ++++ My Solutions/ReverseWordsInAString.java | 25 +++ My Solutions/RightSideView.java | 41 +++++ My Solutions/RomanToInt.java | 29 ++++ My Solutions/RotateList.java | 47 ++++++ My Solutions/RotatedSortedArray.java | 90 +++++++++++ My Solutions/SExpressionOfATree.java | 23 +++ My Solutions/ScrambleString.java | 35 +++++ My Solutions/Search2DMatrix.java | 57 +++++++ My Solutions/SearchInRotatedArray.java | 36 +++++ My Solutions/SearchInsertPosition.java | 33 ++++ My Solutions/SearchRange.java | 43 ++++++ My Solutions/ShortestPalindrome.java | 39 +++++ My Solutions/SingleNumberII.java | 27 ++++ My Solutions/SlidingWindowMaximumGap.java | 34 +++++ My Solutions/SortColor.java | 68 +++++++++ My Solutions/SortList.java | 58 +++++++ My Solutions/SpiralMatrix.java | 47 ++++++ My Solutions/StringToInteger.java | 42 +++++ My Solutions/Subsets.java | 52 +++++++ My Solutions/SudokuSolver.java | 66 ++++++++ My Solutions/SummaryOfRanges.java | 59 ++++++++ My Solutions/SurroundedRegions.java | 101 +++++++++++++ My Solutions/SwapNodeInPairs.java | 54 +++++++ My Solutions/ThreeSum.java | 42 +++++ My Solutions/ThreeSumClosest.java | 36 +++++ My Solutions/TrappingRainWater.java | 27 ++++ My Solutions/TreeLinkNode.java | 8 + My Solutions/TreeNode.java | 9 ++ My Solutions/Triangle.java | 27 ++++ My Solutions/TwoSum.java | 20 +++ My Solutions/UndirectedGraphNode.java | 12 ++ My Solutions/UniqueBinarySearchTrees.java | 38 +++++ My Solutions/UniquePath.java | 35 +++++ My Solutions/WiggleSort.java | 53 +++++++ My Solutions/WildcardMatching.java | 58 +++++++ My Solutions/WordDictionary.java | 64 ++++++++ My Solutions/WordLadder.java | 74 +++++++++ My Solutions/WordLadderII.java | 67 ++++++++ My Solutions/WordPattern.java | 34 +++++ My Solutions/WordSearch.java | 59 ++++++++ My Solutions/WorkBreakII.java | 65 ++++++++ My Solutions/sqrt.java | 23 +++ 129 files changed, 6181 insertions(+) create mode 100644 My Solutions/AddTwoNumbers.java create mode 100644 My Solutions/Anagram.java create mode 100644 My Solutions/BalancedPartition.java create mode 100644 My Solutions/BestTimetoBuyandSellStockIII.java create mode 100644 My Solutions/BinaryTreeTraversal.java create mode 100644 My Solutions/BinaryTreeZigzagLevelOrderTraversal.java create mode 100644 My Solutions/Candy.java create mode 100644 My Solutions/CatchThief.java create mode 100644 My Solutions/CloneGraph.java create mode 100644 My Solutions/CombinationSum.java create mode 100644 My Solutions/Combinations.java create mode 100644 My Solutions/CompareVersion.java create mode 100644 My Solutions/ContainsDuplicateIII.java create mode 100644 My Solutions/ConvertSortedListToBST.java create mode 100644 My Solutions/CopyListWithRandomPointer.java create mode 100644 My Solutions/CountAndSay.java create mode 100644 My Solutions/CountPrimes.java create mode 100644 My Solutions/DecodeWays.java create mode 100644 My Solutions/DivideTwoIntegers.java create mode 100644 My Solutions/ExpressionAddOperators.java create mode 100644 My Solutions/FindMedian.java create mode 100644 My Solutions/FindMedianfromDataStream.java create mode 100644 My Solutions/FirstMissingPositive.java create mode 100644 My Solutions/FlatenBinaryTree.java create mode 100644 My Solutions/FractionToRecurringDecimal.java create mode 100644 My Solutions/GameOfLive.java create mode 100644 My Solutions/GenerateParentheses.java create mode 100644 My Solutions/HappyNumber.java create mode 100644 My Solutions/HouseRobber.java create mode 100644 My Solutions/InorderPostorder.java create mode 100644 My Solutions/InsertInterval.java create mode 100644 My Solutions/InsertionSortList.java create mode 100644 My Solutions/Interval.java create mode 100644 My Solutions/JavaTest.java create mode 100644 My Solutions/KthLargestElementInAnArray.java create mode 100644 My Solutions/LRUCache.java create mode 100644 My Solutions/LRUCacheNew.java create mode 100644 My Solutions/LargestNumber.java create mode 100644 My Solutions/LargestRectangleInHistogram.java create mode 100644 My Solutions/LetterCombination.java create mode 100644 My Solutions/LevelOrderTraversal.java create mode 100644 My Solutions/ListNode.java create mode 100644 My Solutions/LongestIncreasingSubsequence.java create mode 100644 My Solutions/LongestPalindromeSubstring.java create mode 100644 My Solutions/LongestSubstringWithoutRepeating.java create mode 100644 My Solutions/LongestValidParentheses.java create mode 100644 My Solutions/MaxPoint.java create mode 100644 My Solutions/MaximalRectangle.java create mode 100644 My Solutions/MaximalSquare.java create mode 100644 My Solutions/MaximumGap.java create mode 100644 My Solutions/MaximumProductSubarray.java create mode 100644 My Solutions/MaximumSubarray.java create mode 100644 My Solutions/MedianOfTwoSortedArray.java create mode 100644 My Solutions/MergeIntervals.java create mode 100644 My Solutions/MergeKSortedList.java create mode 100644 My Solutions/MergeSortedArray.java create mode 100644 My Solutions/MinimumSizeSubarraySum.java create mode 100644 My Solutions/MinimumWindowSubstring.java create mode 100644 My Solutions/NQueen.java create mode 100644 My Solutions/NQueenII.java create mode 100644 My Solutions/NextPermutation.java create mode 100644 My Solutions/Palindrome.java create mode 100644 My Solutions/PalindromePartition.java create mode 100644 My Solutions/PalindromePartitioningII.java create mode 100644 My Solutions/PathSum.java create mode 100644 My Solutions/PermutationSequence.java create mode 100644 My Solutions/Permutations.java create mode 100644 My Solutions/PermutationsII.java create mode 100644 My Solutions/PhoneInterview.java create mode 100644 My Solutions/PlusOne.java create mode 100644 My Solutions/Point.java create mode 100644 My Solutions/PopulatingNextRightPointerInEachNode.java create mode 100644 My Solutions/PopulatingNextRightPointerInEachNodeII.java create mode 100644 My Solutions/RPN.java create mode 100644 My Solutions/RandomListNode.java create mode 100644 My Solutions/RangeBitwiseAnd.java create mode 100644 My Solutions/RecoverBinarySearchTree.java create mode 100644 My Solutions/RegularExpressionMatching.java create mode 100644 My Solutions/RemoveDuplicate.java create mode 100644 My Solutions/RemoveDuplicatesFromSortedArrayII.java create mode 100644 My Solutions/RemoveDuplicatesII.java create mode 100644 My Solutions/ReorderList.java create mode 100644 My Solutions/RepeatedDNASequence.java create mode 100644 My Solutions/RestoreIPAddress.java create mode 100644 My Solutions/ReverseLinkedListII.java create mode 100644 My Solutions/ReverseNodeInKGroup.java create mode 100644 My Solutions/ReverseString.java create mode 100644 My Solutions/ReverseWordsInAString.java create mode 100644 My Solutions/RightSideView.java create mode 100644 My Solutions/RomanToInt.java create mode 100644 My Solutions/RotateList.java create mode 100644 My Solutions/RotatedSortedArray.java create mode 100644 My Solutions/SExpressionOfATree.java create mode 100644 My Solutions/ScrambleString.java create mode 100644 My Solutions/Search2DMatrix.java create mode 100644 My Solutions/SearchInRotatedArray.java create mode 100644 My Solutions/SearchInsertPosition.java create mode 100644 My Solutions/SearchRange.java create mode 100644 My Solutions/ShortestPalindrome.java create mode 100644 My Solutions/SingleNumberII.java create mode 100644 My Solutions/SlidingWindowMaximumGap.java create mode 100644 My Solutions/SortColor.java create mode 100644 My Solutions/SortList.java create mode 100644 My Solutions/SpiralMatrix.java create mode 100644 My Solutions/StringToInteger.java create mode 100644 My Solutions/Subsets.java create mode 100644 My Solutions/SudokuSolver.java create mode 100644 My Solutions/SummaryOfRanges.java create mode 100644 My Solutions/SurroundedRegions.java create mode 100644 My Solutions/SwapNodeInPairs.java create mode 100644 My Solutions/ThreeSum.java create mode 100644 My Solutions/ThreeSumClosest.java create mode 100644 My Solutions/TrappingRainWater.java create mode 100644 My Solutions/TreeLinkNode.java create mode 100644 My Solutions/TreeNode.java create mode 100644 My Solutions/Triangle.java create mode 100644 My Solutions/TwoSum.java create mode 100644 My Solutions/UndirectedGraphNode.java create mode 100644 My Solutions/UniqueBinarySearchTrees.java create mode 100644 My Solutions/UniquePath.java create mode 100644 My Solutions/WiggleSort.java create mode 100644 My Solutions/WildcardMatching.java create mode 100644 My Solutions/WordDictionary.java create mode 100644 My Solutions/WordLadder.java create mode 100644 My Solutions/WordLadderII.java create mode 100644 My Solutions/WordPattern.java create mode 100644 My Solutions/WordSearch.java create mode 100644 My Solutions/WorkBreakII.java create mode 100644 My Solutions/sqrt.java diff --git a/My Solutions/AddTwoNumbers.java b/My Solutions/AddTwoNumbers.java new file mode 100644 index 00000000..7f80cfc9 --- /dev/null +++ b/My Solutions/AddTwoNumbers.java @@ -0,0 +1,46 @@ +import java.util.*; + +public class AddTwoNumbers { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + Deque s1 = new ArrayDeque<>(); + Deque s2 = new ArrayDeque<>(); + + while (l1 != null) { + s1.push(l1.val); + l1 = l1.next; + } + while (l2 != null) { + s2.push(l2.val); + l2 = l2.next; + } + + int carry = 0; + ListNode tail = null; + while (!s1.isEmpty() || !s2.isEmpty()) { + + int op1 = s1.isEmpty() ? 0 : s1.pop(); + int op2 = s2.isEmpty() ? 0 : s2.pop(); + int sum = op1 + op2 + carry; + ListNode n = new ListNode(sum); + n.next = tail; + tail = n; + carry = sum >= 10 ? 1 : 0; + } + if (carry == 1) { + ListNode n = new ListNode(1); + n.next = tail; + tail = n; + } + return tail; + } + +} diff --git a/My Solutions/Anagram.java b/My Solutions/Anagram.java new file mode 100644 index 00000000..22de4404 --- /dev/null +++ b/My Solutions/Anagram.java @@ -0,0 +1,48 @@ +import java.util.*; + +public class Anagram { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public List anagrams(String[] strs) { + List l = new ArrayList<>(); + int len = strs.length; + if (len < 2) + return l; + + Map> m = new HashMap<>(); + Set s = new HashSet<>(); + + for (int i = 0; i < len; i++) { + String tmp = sort(strs[i]); + List list = m.get(tmp); + if (list == null) { + list = new ArrayList(); + list.add(i); + m.put(tmp, list); + } else { + list.add(i); + s.add(tmp); + } + } + for (String str : s) { + for (int i : m.get(str)) { + l.add(strs[i]); + } + } + return l; + } + + private String sort(String s) { + char[] c = s.toCharArray(); + Arrays.sort(c); + return new String(c); + } + +} diff --git a/My Solutions/BalancedPartition.java b/My Solutions/BalancedPartition.java new file mode 100644 index 00000000..81f5ce2f --- /dev/null +++ b/My Solutions/BalancedPartition.java @@ -0,0 +1,36 @@ +public class BalancedPartition { + + /** + * @param args + */ + public static void main(String[] args) { + BalancedPartition bp = new BalancedPartition(); + System.out.println(bp.partition(new int[] { 3, 1, 5, 9, 12 })); + + } + + public boolean partition(int[] nums) { + + int sum = 0; + for (int n : nums) + sum += n; + + boolean[][] dp = new boolean[nums.length][sum / 2 + 1]; + + for (int i = 0; i < nums.length; i++) { + dp[i][nums[i]] = true; + dp[i][0] = true; + if (i == 0) + continue; + for (int j = nums[i]; j <= sum / 2; j++) { + dp[i][j] = (dp[i - 1][j] || dp[i][j - nums[i]]); + } + } + + for (int i = 0; i < nums.length; i++) { + if (dp[i][sum / 2]) + return true; + } + return false; + } +} diff --git a/My Solutions/BestTimetoBuyandSellStockIII.java b/My Solutions/BestTimetoBuyandSellStockIII.java new file mode 100644 index 00000000..57e925fb --- /dev/null +++ b/My Solutions/BestTimetoBuyandSellStockIII.java @@ -0,0 +1,37 @@ +public class BestTimetoBuyandSellStockIII { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + + + private int[] prices; + + public int maxProfit(int[] prices) { + + int p = 0; + this.prices = prices; + for (int i = 2; i < prices.length - 2; i++) { + p = Math.max(p, maxProfit(0, i) + maxProfit(i, prices.length)); + } + + return p; + } + + private int maxProfit(int start, int end) { + int p = 0; + for (int i = start; i < end - 1; i++) { + if (prices[i + 1] > prices[i]) { + p += prices[i + 1] - prices[i]; + } + } + + return p; + } + +} diff --git a/My Solutions/BinaryTreeTraversal.java b/My Solutions/BinaryTreeTraversal.java new file mode 100644 index 00000000..4d4a865a --- /dev/null +++ b/My Solutions/BinaryTreeTraversal.java @@ -0,0 +1,58 @@ +import java.util.*; + +public class BinaryTreeTraversal { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + TreeNode t = new TreeNode(0); + t.left = new TreeNode(1); + t.right = new TreeNode(2); + inorderTraversal(t); + + } + + public static List inorderTraversal(TreeNode root) { + List res = new ArrayList<>(); + if (root == null) + return res; + + Deque s = new ArrayDeque<>(); + s.push(root); + + while (!s.isEmpty()) { + TreeNode n = s.pop(); + while (n.left != null) { + s.push(n); + n = n.left; + } + res.add(n.val); + if (n.right != null) + s.push(n.right); + } + return res; + } + + public static List preorderTraversal(TreeNode root) { + List res = new LinkedList<>(); + if (root == null) + return res; + // recursive(res, root); + Stack s = new Stack<>(); + s.push(root); + TreeNode n; + while (!s.isEmpty()) { + n = s.pop(); + res.add(n.val); + if (n.right != null) + s.push(n.right); + if (n.left != null) + s.push(n.left); + } + + return res; + } + +} diff --git a/My Solutions/BinaryTreeZigzagLevelOrderTraversal.java b/My Solutions/BinaryTreeZigzagLevelOrderTraversal.java new file mode 100644 index 00000000..7e3a9493 --- /dev/null +++ b/My Solutions/BinaryTreeZigzagLevelOrderTraversal.java @@ -0,0 +1,82 @@ +import java.util.*; + +public class BinaryTreeZigzagLevelOrderTraversal { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public List> zigzagLevelOrder(TreeNode root) { + List> levelOrder = new LinkedList<>(); + recursive(root, levelOrder, 0); + adjust(levelOrder); + return levelOrder; + } + + private void recursive(TreeNode root, List> levelOrder, + int level) { + if (root == null) + return; + if (level > levelOrder.size()) { + levelOrder.add(new LinkedList()); + } + levelOrder.get(level).add(root.val); + recursive(root.left, levelOrder, level + 1); + recursive(root.right, levelOrder, level + 1); + } + + private void adjust(List> levelOrder) { + for (int i = 0; i < levelOrder.size(); i++) { + if ((i & 1) == 1) { + Collections.reverse(levelOrder.get(i)); + } + } + return; + } + + private List> naive(TreeNode root) { + List> ret = new LinkedList<>(); + if (root == null) + return ret; + + List levelList = new LinkedList<>(); + levelList.add(root.val); + ret.add(levelList); + + Deque q = new ArrayDeque<>(); + + q.add(root); + int level = 0; + while (q.size() > 0) { + level++; + levelList = new LinkedList<>(); + Deque newQ = new ArrayDeque<>(); + while (q.size() > 0) { + TreeNode n = q.remove(); + if (n.left != null) { + newQ.add(n.left); + if (level % 2 == 1) + levelList.add(0, n.left.val); + else + levelList.add(n.left.val); + } + if (n.right != null) { + newQ.add(n.right); + if (level % 2 == 1) + levelList.add(0, n.right.val); + else + levelList.add(n.right.val); + } + } + if (levelList.size() > 0) + ret.add(levelList); + q = newQ; + } + return ret; + } + +} diff --git a/My Solutions/Candy.java b/My Solutions/Candy.java new file mode 100644 index 00000000..0d1e4c4f --- /dev/null +++ b/My Solutions/Candy.java @@ -0,0 +1,52 @@ +import java.util.*; + +public class Candy { + + /** + * @param args + */ + public static void main(String[] args) { + int[] test = { 1, 2, 2}; + Candy c = new Candy(); + System.out.print(c.candy(test)); + } + + public int candy(int[] ratings) { + int len = ratings.length; + if (len < 2) + return len; // 0 -> 0, 1 -> 1; + + int[] candies = new int[len]; + Arrays.fill(candies, 1); + + Map> m = new HashMap<>(); + + for (int i = 0; i < len; i++) { + if (m.containsKey(ratings[i])) { + m.get(ratings[i]).add(i); + } else { + List l = new ArrayList<>(); + l.add(i); + m.put(ratings[i], l); + } + } + + Integer[] rs = m.keySet().toArray(new Integer[0]); + Arrays.sort(rs); + + for (int i = 1; i < rs.length; i++) { //skip the lowest rating + List l = m.get(rs[i]); + for (int j : l) { + if (j - 1 >= 0 && candies[j] <= candies[j - 1]) + candies[j] = candies[j - 1] + 1; + if (j + 1 < len && candies[j] <= candies[j + 1]) + candies[j] = candies[j + 1] + 1; + } + } + + int sum = 0; + for (int i : candies) + sum += i; + return sum; + } +} diff --git a/My Solutions/CatchThief.java b/My Solutions/CatchThief.java new file mode 100644 index 00000000..f0f032eb --- /dev/null +++ b/My Solutions/CatchThief.java @@ -0,0 +1,31 @@ +import java.util.Arrays; + +public class CatchThief { + + /** + * @param args + */ + public static void main(String[] args) { + CatchThief ct = new CatchThief(); + System.out.println(ct.canCatch( + new int[] { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 }, 5)); + } + + public boolean canCatch(int[] seq, int n) { + + boolean[] dp = new boolean[n + 2]; + Arrays.fill(dp, true); + + dp[0] = dp[seq[0]] = dp[n + 1] = false; + + for (int i = 0; i < seq.length; i++) + for (int j = 1; j <= n; j++) + dp[j] = ((dp[j - 1] || dp[j + 1]) && j != seq[i]); + + for (int i = 1; i <= n; i++) + if (dp[i]) + return false; + + return true; + } +} diff --git a/My Solutions/CloneGraph.java b/My Solutions/CloneGraph.java new file mode 100644 index 00000000..9c105d6d --- /dev/null +++ b/My Solutions/CloneGraph.java @@ -0,0 +1,48 @@ +import java.util.*; + +public class CloneGraph { + + public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { + + if (node == null) { + return null; + } + + Stack toCloneStack = new Stack(); + Set visitedSet = new HashSet(); + Map cloneMap = new HashMap(); + + toCloneStack.push(node); + while (!toCloneStack.empty()) { + UndirectedGraphNode n = toCloneStack.pop(); + if (visitedSet.contains(n)) { + continue; + } + + UndirectedGraphNode clonedN; + if (cloneMap.containsKey(n)) { + clonedN = cloneMap.get(n); + } else { + clonedN = new UndirectedGraphNode(n.label); + cloneMap.put(n, clonedN); + } + + for (UndirectedGraphNode neighbor : n.neighbors) { + toCloneStack.push(neighbor); + + if (cloneMap.containsKey(neighbor)) { + clonedN.neighbors.add(cloneMap.get(neighbor)); + } else { + UndirectedGraphNode clonedNeighbor = new UndirectedGraphNode( + neighbor.label); + clonedN.neighbors.add(clonedNeighbor); + cloneMap.put(neighbor, clonedNeighbor); + } + } + visitedSet.add(n); + + } + + return cloneMap.get(node); + } +} diff --git a/My Solutions/CombinationSum.java b/My Solutions/CombinationSum.java new file mode 100644 index 00000000..41163f43 --- /dev/null +++ b/My Solutions/CombinationSum.java @@ -0,0 +1,47 @@ +import java.util.*; + +public class CombinationSum { + + /** + * @param args + */ + public static void main(String[] args) { + CombinationSum cs = new CombinationSum(); + List l = cs.combinationSum(new int[] { 1, 2 }, 3); + return; + } + + List> ret; + + public List> combinationSum(int[] candidates, int target) { + ret = new LinkedList<>(); + int len = candidates.length; + if (len == 0) + return ret; + List list = new LinkedList<>(); + Arrays.sort(candidates); + search(candidates, 0, target, list); + return ret; + } + + private void search(int[] nums, int start, int target, List list) { + int len = nums.length; + for (int i = start; i < len; i++) { + if (nums[i] < 0) + continue; + if (target == nums[i]) { + list.add(nums[i]); + ret.add(new LinkedList(list)); + list.remove(list.size() - 1); + return; + } else if (target < nums[i]) { + continue; + } else { + list.add(nums[i]); + search(nums, i, target - nums[i], list); + list.remove(list.size() - 1); + } + } + } + +} diff --git a/My Solutions/Combinations.java b/My Solutions/Combinations.java new file mode 100644 index 00000000..15c85421 --- /dev/null +++ b/My Solutions/Combinations.java @@ -0,0 +1,41 @@ +import java.util.ArrayList; +import java.util.List; + +public class Combinations { + + public static void main(String[] args) { + Combinations cb = new Combinations(); + cb.combine(4, 2); + } + + public List> combine(int n, int k) { + + List> lstlst = new ArrayList>(); + + if (k == 0) { + return null; + } else if (n == k) { + List lst = new ArrayList(); + for (int i = 1; i <= n; i++) { + lst.add(i); + lstlst.add(lst); + } + } else { + List> l1 = combine(n - 1, k); // not include n; + List> l2 = combine(n - 1, k - 1); // include n; + lstlst.addAll(l1); + if (l2 != null) { + for (List l : l2) { + l.add(n); + lstlst.add(l); + } + } else { + List l = new ArrayList(); + l.add(n); + lstlst.add(l); + } + } + return lstlst; + + } +} diff --git a/My Solutions/CompareVersion.java b/My Solutions/CompareVersion.java new file mode 100644 index 00000000..9b1a013f --- /dev/null +++ b/My Solutions/CompareVersion.java @@ -0,0 +1,22 @@ +public class CompareVersion { + + public static void main(String[] args) { + String v1 = "1.0"; + String v2 = "1"; + System.out.println(compareVersion(v1, v2)); + } + + public static int compareVersion(String version1, String version2) { + + if (version1.equals("") || version2.equals("")) { + return 0; + } + + String[] versions1 = version1.split("\\."); + String[] versions2 = version2.split("\\."); + int len = versions1.length > versions2.length? versions1.length: versions2.length; + + return 0; + + } +} \ No newline at end of file diff --git a/My Solutions/ContainsDuplicateIII.java b/My Solutions/ContainsDuplicateIII.java new file mode 100644 index 00000000..6bc471e1 --- /dev/null +++ b/My Solutions/ContainsDuplicateIII.java @@ -0,0 +1,39 @@ +import java.util.HashMap; +import java.util.Map; + +public class ContainsDuplicateIII { + + /** + * @param args + */ + public static void main(String[] args) { + ContainsDuplicateIII cd3 = new ContainsDuplicateIII(); + System.out.println(cd3.containsNearbyAlmostDuplicate(new int[] { -1, + 2147483647 }, 1, 2147483647)); + + } + + public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { + + Map map = new HashMap<>(); + + for (int i = 0; i < nums.length; i++) { + long b = ((long) nums[i] - Integer.MIN_VALUE) / ((long) t + 1); + if (map.get(b) != null || map.get(b - 1) != null + && nums[i] - map.get(b - 1) <= t || map.get(b + 1) != null + && map.get(b + 1) - nums[i] <= t) + return true; + else { + map.put(b, (long)nums[i]); + } + + if (map.keySet().size() > k) { + b = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1); + map.remove(b); + } + } + + return false; + } + +} diff --git a/My Solutions/ConvertSortedListToBST.java b/My Solutions/ConvertSortedListToBST.java new file mode 100644 index 00000000..dfdae1be --- /dev/null +++ b/My Solutions/ConvertSortedListToBST.java @@ -0,0 +1,84 @@ +import java.util.*; + +public class ConvertSortedListToBST { + + /** + * @param args + */ + public static void main(String[] args) { + + ListNode n = new ListNode(1); + n.next = new ListNode(3); + + TreeNode t = sortedListToBST(n); + + return; + + } + + public static TreeNode sortedListToBST(ListNode head) { + + int listCount = 0; + ListNode p = head; + while (p != null) { + listCount++; + p = p.next; + } + + if (listCount == 0) + return null; + + // construct the tree + int level = (int) (Math.log(listCount) / Math.log(2)) + 1; + TreeNode root = new TreeNode(-1); + Queue q = new ArrayDeque(); + q.add(root); + int nodeCount = 1; + for (int i = 0; i < level - 1; i++) { + Queue nextQ = new ArrayDeque<>(); + while (q.peek() != null) { + TreeNode tmp = q.remove(); + if (nodeCount++ < listCount) + nextQ.add(tmp.left = new TreeNode(-1)); + else { + i = level; + break; + } + if (nodeCount++ < listCount) + nextQ.add(tmp.right = new TreeNode(-1)); + else { + i = level; + break; + } + } + q = nextQ; + } + + DFS(root, head); + return root; + } + + private static ListNode DFS(TreeNode root, ListNode head) { + + if (root.left == null && root.right == null) { + root.val = head.val; + head = head.next; + return head; + } + + if (root.left != null) { + head = DFS(root.left, head); + } + root.val = head.val; + head = head.next; + if (root.right != null) { + head = DFS(root.right, head); + } + + return head; + + } + + + +} diff --git a/My Solutions/CopyListWithRandomPointer.java b/My Solutions/CopyListWithRandomPointer.java new file mode 100644 index 00000000..5cad757d --- /dev/null +++ b/My Solutions/CopyListWithRandomPointer.java @@ -0,0 +1,43 @@ +import java.util.HashMap; +import java.util.Map; + +public class CopyListWithRandomPointer { + public RandomListNode copyRandomList(RandomListNode head) { + return mapCopy(head); + } + + public RandomListNode mapCopy(RandomListNode head) { + + if (head == null) + return null; + + Map map = new HashMap(); + + RandomListNode headCopy = new RandomListNode(head.label); + RandomListNode p = head, q = headCopy; + + while (p != null) { + if (p.random == null) { + q.random = null; + } else if (map.containsKey(p.random)) { + q.random = map.get(p.random); + } else { + map.put(p.random, new RandomListNode(p.random.label)); + } + + if (p.next == null) { + q.next = null; + } else if (map.containsKey(p.next)) { + q.next = map.get(p.next); + } else { + map.put(p.next, new RandomListNode(p.next.label)); + } + + p = p.next; + q = q.next; + } + + return headCopy; + + } +} diff --git a/My Solutions/CountAndSay.java b/My Solutions/CountAndSay.java new file mode 100644 index 00000000..57b38d61 --- /dev/null +++ b/My Solutions/CountAndSay.java @@ -0,0 +1,55 @@ +public class CountAndSay { + + /** + * @param args + */ + public static void main(String[] args) { + CountAndSay cas = new CountAndSay(); + System.out.println(cas.countAndSay(30)); + } + + public String countAndSay(int n) { + + if (n == 0) + return ""; + String s = "1"; + while (n > 1) { + int i = 0; + StringBuilder sb = new StringBuilder(); + while (i < s.length()) { + char c = s.charAt(i++); + int count = 1; + while (i < s.length() && s.charAt(i) == c) { + i++; + count++; + } + sb.append(count); + sb.append(c); + } + s = sb.toString(); + n--; + } + return s; + } + + public String countAndSayOld(int n) { + + if (n == 1) + return "1"; + + String s = countAndSay(n - 1); + StringBuilder sb = new StringBuilder(); + + int i = 0, len = s.length(); + while (i++ < len) { + int count = 1; + while (i < len && s.charAt(i) == s.charAt(i - 1)) { + count++; + i++; + } + sb.append(count + "" + s.charAt(i - 1)); + } + return sb.toString(); + + } +} diff --git a/My Solutions/CountPrimes.java b/My Solutions/CountPrimes.java new file mode 100644 index 00000000..084a7093 --- /dev/null +++ b/My Solutions/CountPrimes.java @@ -0,0 +1,35 @@ +import java.util.BitSet; + + +public class CountPrimes { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + CountPrimes cp = new CountPrimes(); + System.out.println(cp.countPrimes(4)); + + } + + public int countPrimes(int n) { + + if (n < 2) return 0; + + BitSet set = new BitSet(n); + set.set(0, 2); + + for (int i = 2; i < n; i++) { + if (!set.get(i)) { + for (int j = i * 2; j < n; j += i) { + set.set(j); + } + } + } + + return n - set.cardinality(); + } + +} diff --git a/My Solutions/DecodeWays.java b/My Solutions/DecodeWays.java new file mode 100644 index 00000000..f6ba4e3b --- /dev/null +++ b/My Solutions/DecodeWays.java @@ -0,0 +1,58 @@ +public class DecodeWays { + + /** + * @param args + */ + public static void main(String[] args) { + DecodeWays dw = new DecodeWays(); + System.out.println(dw.numDecodings("110")); + + } + + private int[] t; + + public int numDecodings(String s) { + int len = s.length(); + t = new int[len + 1]; + t[0] = 1; + int n = helper(s, 0); + return n == -1 ? 0 : n; + } + + private int helper(String s, int i) { + int len = s.length() - i; + if (len == 0) + return 0; + if (s.charAt(i) == '0') + return -1; // error + if (len == 1) + return 1; + + if (s.charAt(i) - '0' <= 2 && s.charAt(i + 1) - '0' <= 6 + && s.charAt(i + 1) - '0' > 0) { + if (t[i + 1] == 0) + t[i + 1] = helper(s, i + 1); + if (i + 2 < len && t[i + 2] == 0) + t[i + 2] = helper(s, i + 2); + if (t[i + 1] == -1 && t[i + 2] == -1) + return -1; + return t[i + 1] + Math.max(1, t[i + 2]); + } else if (s.charAt(i) - '0' <= 2 && s.charAt(i + 1) - '0' == 0) { + if (i + 2 < len && t[i + 2] == 0) + t[i + 2] = helper(s, i + 2); + if (t[i + 2] == -1) + return -1; + return Math.max(1, t[i + 2]); + } else if (s.charAt(i) - '0' <= 1) { + if (t[i + 1] == 0) + t[i + 1] = helper(s, i + 1); + + return t[i + 1] == -1? -1: 1 + t[i + 1]; + } else { + if (t[i + 1] == 0) + t[i + 1] = helper(s, i + 1); + + return t[i + 1] == -1 ? -1 : t[i + 1]; + } + } +} diff --git a/My Solutions/DivideTwoIntegers.java b/My Solutions/DivideTwoIntegers.java new file mode 100644 index 00000000..d731c96d --- /dev/null +++ b/My Solutions/DivideTwoIntegers.java @@ -0,0 +1,74 @@ +public class DivideTwoIntegers { + + /** + * @param args + */ + public static void main(String[] args) { + DivideTwoIntegers dti = new DivideTwoIntegers(); + System.out.println(dti.divide2(2, 2)); + } + + public int divide2(int dividend, int divisor) { + + boolean isNegative = dividend >= 0 ^ divisor >= 0 ? true : false; + + Long dividendL = Math.abs((long) dividend); + Long divisorL = Math.abs((long) divisor); + + if (divisorL == 0) + return Integer.MAX_VALUE; + if (divisorL == 1) { + long tmp = isNegative ? -dividendL : dividendL; + return tmp > Integer.MAX_VALUE || tmp < Integer.MIN_VALUE ? Integer.MAX_VALUE + : (int) tmp; + } + + int quotient = 0; + while (dividendL >= divisorL) { + long i = 1, div = divisorL; + while (dividendL >> 2 >= div) { + i <<= 1; + div <<= 1; + } + dividendL -= div; + quotient += i; + } + return isNegative ? -quotient : quotient; + } + + public int divide(int dividend, int divisor) { + + boolean isNegative = false; + if (dividend >= 0 ^ divisor >= 0) + isNegative = true; + Long dividendL = Math.abs((long) dividend); + Long divisorL = Math.abs((long) divisor); + + if (divisorL == 0) + return Integer.MAX_VALUE; + if (divisorL == 1) { + long tmp = isNegative ? -dividendL : dividendL; + if (tmp > Integer.MAX_VALUE || tmp < Integer.MIN_VALUE) { + return Integer.MAX_VALUE; + } else { + return (int) tmp; + } + } + if (dividendL < divisorL) + return 0; + + int r = 0; + while (dividendL >= divisorL) { + int i = 1; + long tmp = divisorL; + while (dividendL >= tmp) { + dividendL -= tmp; + r += i; + tmp <<= 1; + i <<= 1; + } + } + return isNegative ? -r : r; + } + +} diff --git a/My Solutions/ExpressionAddOperators.java b/My Solutions/ExpressionAddOperators.java new file mode 100644 index 00000000..09faf8ee --- /dev/null +++ b/My Solutions/ExpressionAddOperators.java @@ -0,0 +1,49 @@ +import java.util.*; + +public class ExpressionAddOperators { + + /** + * @param args + */ + public static void main(String[] args) { + ExpressionAddOperators eao = new ExpressionAddOperators(); + List ret = eao.addOperators("000", 0); + return; + } + + private int target; + private String num; + private List res; + + public List addOperators(String num, int target) { + this.target = target; + this.num = num; + res = new LinkedList<>(); + + for (int i = 1; i <= num.length(); i++) { + String curVal = num.substring(0, i); + Long lVal = Long.parseLong(curVal); + if (i > 1 && lVal < 10) + continue; + helper("" + lVal, i, lVal, lVal); + } + return res; + } + + private void helper(String curExp, int pos, long curEval, long preVal) { + if (pos == num.length() && curEval == target) { + res.add(curExp); + return; + } + for (int i = pos + 1; i <= num.length(); i++) { + if (i > pos + 1 && num.charAt(pos) == '0') + return; + int curVal = Integer.parseInt(num.substring(pos, i)); + helper(curExp + "+" + curVal, i, curEval + curVal, curVal); + helper(curExp + "-" + curVal, i, curEval - curVal, -curVal); + helper(curExp + "*" + curVal, i, + curEval - preVal + preVal * curVal, preVal * curVal); + } + } + +} diff --git a/My Solutions/FindMedian.java b/My Solutions/FindMedian.java new file mode 100644 index 00000000..48ddab5f --- /dev/null +++ b/My Solutions/FindMedian.java @@ -0,0 +1,67 @@ +import java.util.Comparator; +import java.util.PriorityQueue; + +public class FindMedian { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + PriorityQueue test = new PriorityQueue<>(); + test.add(5); + test.add(6); + test.add(1); + test.add(3); + test.add(2); + + while (!test.isEmpty()) { + System.out.println(test.remove()); + } + } + + public double findMedian(int[] nums) { + + PriorityQueue left = new PriorityQueue<>( + new Comparator() { + public int compare(Integer a, Integer b) { + return b.compareTo(a); // descending order + } + }); + PriorityQueue right = new PriorityQueue<>( + new Comparator() { + public int compare(Integer a, Integer b) { + return a.compareTo(b); // descending order + } + }); + left.add(Integer.MIN_VALUE); + right.add(Integer.MAX_VALUE); + + for (int i = 0; i < nums.length; i++) { + if (left.size() == right.size()) { + if (nums[i] > right.peek()) { + int rightTop = right.remove(); + left.add(rightTop); + right.add(nums[i]); + } else { + left.add(nums[i]); + } + } else { + left.add(nums[i]); + int leftTop = left.remove(); + right.add(leftTop); + } + } + + if ((nums.length & 1) == 1) + return left.peek(); + else + return (left.peek() + right.peek()) / 2.0; + } + + class MyComparator implements Comparator { + public int compare(Integer a, Integer b) { + return a.compareTo(b); + } + } +} diff --git a/My Solutions/FindMedianfromDataStream.java b/My Solutions/FindMedianfromDataStream.java new file mode 100644 index 00000000..288b5bfb --- /dev/null +++ b/My Solutions/FindMedianfromDataStream.java @@ -0,0 +1,55 @@ +import java.util.Comparator; +import java.util.PriorityQueue; + +public class FindMedianfromDataStream { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + FindMedianfromDataStream f = new FindMedianfromDataStream(); + f.addNum(2); + System.out.println(f.findMedian()); + f.addNum(3); + System.out.println(f.findMedian()); + + } + + private PriorityQueue left, right; + + // Adds a number into the data structure. + public void addNum(int num) { + right.add(num); + left.add(right.poll()); + + if (right.size() < left.size()) { + right.add(left.poll()); + } + } + + // Returns the median of current data stream + public double findMedian() { + if (left.size() > right.size()) { + return left.peek(); + } else if (left.size() < right.size()) + return right.peek(); + else { + return (left.peek() + right.peek()) / 2.0; + } + } + + FindMedianfromDataStream() { + left = new PriorityQueue<>(1, new Comparator() { + public int compare(Integer a, Integer b) { + return b - a; + } + }); + right = new PriorityQueue<>(new Comparator() { + public int compare(Integer a, Integer b) { + return a - b; + } + }); + } + +} diff --git a/My Solutions/FirstMissingPositive.java b/My Solutions/FirstMissingPositive.java new file mode 100644 index 00000000..362677fe --- /dev/null +++ b/My Solutions/FirstMissingPositive.java @@ -0,0 +1,31 @@ +public class FirstMissingPositive { + + /** + * @param args + */ + public static void main(String[] args) { + FirstMissingPositive fmp = new FirstMissingPositive(); + fmp.firstMissingPositive(new int[] { 2, 1 }); + + } + + public int firstMissingPositive(int[] A) { + int len = A.length; + int i = 0; + while (i < len) { + if (A[i] > 0 && A[i] <= len && A[i] != i + 1 && A[i] != A[A[i] - 1]) { + int tmp = A[A[i] - 1]; + A[A[i] - 1] = A[i]; + A[i] = tmp; + } else { + i++; + } + } + + for (i = 0; i < len; i++) { + if (A[i] != i + 1) + return i + 1; + } + return len + 1; // all fit + } +} diff --git a/My Solutions/FlatenBinaryTree.java b/My Solutions/FlatenBinaryTree.java new file mode 100644 index 00000000..0edc6a95 --- /dev/null +++ b/My Solutions/FlatenBinaryTree.java @@ -0,0 +1,32 @@ +import java.util.*; + +public class FlatenBinaryTree { + + public static void main(String[] args) { + TreeNode t = new TreeNode(0); + flatten(t); + } + + public static void flatten(TreeNode root) { + Queue list = new LinkedList(); + visit(root, list); + + TreeNode vRoot = new TreeNode(0); + while (list.size() > 0) { + vRoot.left = null; + vRoot.right = list.poll(); + vRoot = vRoot.right; + } + } + + public static void visit(TreeNode t, Queue list) { + if (t == null) { + return; + } + list.add(t); + visit(t.left, list); + t.left = null; + visit(t.right, list); + t.right = null; + } +} diff --git a/My Solutions/FractionToRecurringDecimal.java b/My Solutions/FractionToRecurringDecimal.java new file mode 100644 index 00000000..d14d60d4 --- /dev/null +++ b/My Solutions/FractionToRecurringDecimal.java @@ -0,0 +1,47 @@ +import java.util.*; + +public class FractionToRecurringDecimal { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(fractionToDecimal(-1, -2147483648)); + } + + public static String fractionToDecimal(int numerator, int denominator) { + if (numerator == 0) + return "0"; + + String result = ""; + if (numerator > 0 ^ denominator > 0) { + result = "-"; + + } + + long num = Math.abs(numerator); + long den = Math.abs(denominator); + + result += num / den; // before fraction + num %= den; + + HashMap m = new HashMap<>(); // numerator, location + StringBuilder s = new StringBuilder(); + int loc = 0; + while (num != 0) { + num *= 10; + if (!m.containsKey(num)) { + s.append(num / den); + m.put(num, loc); + num %= den; + loc++; + } else { + int start = m.get(num); + return result + "." + s.substring(0, start) + "(" + + s.substring(start, loc) + ")"; + } + } + return loc == 0 ? result : result + "." + s.toString(); + } +} diff --git a/My Solutions/GameOfLive.java b/My Solutions/GameOfLive.java new file mode 100644 index 00000000..53c00e37 --- /dev/null +++ b/My Solutions/GameOfLive.java @@ -0,0 +1,49 @@ +public class GameOfLive { + + public static void main(String[] args) { + GameOfLive gol = new GameOfLive(); + int[][] board = new int[][] { + { 0, 0, 0, 0 }, + { 0, 1, 1, 0 }, + { 0, 1, 1, 0 }, + { 0, 0, 0, 0 } }; + gol.gameOfLife(board); + return; + } + + public void gameOfLife(int[][] board) { + + int nRow = board.length; + int nCol = board[0].length; + + // used the 2nd bit to indicate the new state. 0, dead to dead, 1-live + // to dead, 2 - dead to live, 3 = live to live + + int[][] neighbors = new int[][] { { -1, -1 }, { 0, -1 }, { 1, -1 }, + { -1, 0 }, { 1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 } }; + for (int i = 0; i < nRow; i++) { + for (int j = 0; j < nCol; j++) { + int nLive = 0; + for (int[] n : neighbors) { + if (i + n[0] < 0 || i + n[0] == nRow || j + n[1] < 0 + || j + n[1] == nCol) // border cases + continue; + else if ((board[i + n[0]][j + n[1]] & 1) == 1) + nLive++; + } + if (nLive == 2 || nLive == 3) + board[i][j] |= 2; // set to live + } + } + + for (int i = 0; i < nRow; i++) { + for (int j = 0; j < nCol; j++) { + if ((board[i][j] & 2) == 2) + board[i][j] = 1; + else { + board[i][j] = 0; + } + } + } + } +} diff --git a/My Solutions/GenerateParentheses.java b/My Solutions/GenerateParentheses.java new file mode 100644 index 00000000..0850ce41 --- /dev/null +++ b/My Solutions/GenerateParentheses.java @@ -0,0 +1,43 @@ +import java.util.*; + +public class GenerateParentheses { + + /** + * @param args + */ + public static void main(String[] args) { + + generateParenthesis(2); + return; + + } + + public static List generateParenthesis(int n) { + + List result = new LinkedList<>(); + StringBuilder s = new StringBuilder(); + sol1(result, s, n, 0); + return result; + + } + + private static void sol1(List l, StringBuilder s, int nL, int nR) { + + if (nL == 0 && nR == 0) { + l.add(s.toString()); + return; + } + if (nR > 0) { + s = s.append(")"); + sol1(l, s, nL, nR - 1); + s.deleteCharAt(s.length() - 1); + } + if (nL > 0) { + s = s.append("("); + sol1(l, s, nL - 1, nR + 1); + s.deleteCharAt(s.length() - 1); + + } + } + +} diff --git a/My Solutions/HappyNumber.java b/My Solutions/HappyNumber.java new file mode 100644 index 00000000..a5c95728 --- /dev/null +++ b/My Solutions/HappyNumber.java @@ -0,0 +1,38 @@ +import java.util.*; + +public class HappyNumber { + + /** + * @param args + */ + public static void main(String[] args) { + HappyNumber hn = new HappyNumber(); + System.out.println(hn.isHappy(7)); + + } + + public boolean isHappy(int n) { + + Set s = new HashSet<>(); + + while (!s.contains(n)) { + s.add(n); + n = sumOfSqures(n); + if (n == 1) + return true; + + } + + return false; + } + + int sumOfSqures(int n) { + int sum = 0; + while (n > 0) { + sum += (n % 10) * (n % 10); + n /= 10; + } + return sum; + } + +} diff --git a/My Solutions/HouseRobber.java b/My Solutions/HouseRobber.java new file mode 100644 index 00000000..d67ae147 --- /dev/null +++ b/My Solutions/HouseRobber.java @@ -0,0 +1,39 @@ +public class HouseRobber { + + /** + * @param args + */ + public static void main(String[] args) { + HouseRobber hr = new HouseRobber(); + System.out.println(hr.rob(new int[] { 1, 2 })); + } + + public int rob(int[] nums) { + + int len = nums.length; + if (len == 0) + return 0; + if (len == 1) + return nums[0]; + if (len == 2) + return Math.max(nums[0], nums[1]); + + int[] dp = new int[len]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + for (int i = 2; i < len - 1; i++) + dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]); + + int max1 = dp[len - 2]; + + dp[0] = 0; + dp[1] = nums[1]; + dp[2] = Math.max(nums[1], nums[2]); + + for (int i = 2; i < nums.length; i++) + dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]); + + return Math.max(max1, dp[len - 1]); + + } +} diff --git a/My Solutions/InorderPostorder.java b/My Solutions/InorderPostorder.java new file mode 100644 index 00000000..06acd084 --- /dev/null +++ b/My Solutions/InorderPostorder.java @@ -0,0 +1,43 @@ +public class InorderPostorder { + + /** + * @param args + */ + public static void main(String[] args) { + + InorderPostorder ip = new InorderPostorder(); + TreeNode t = ip.buildTree(new int[] { 1, 2}, new int[] {2, 1 }); + return; + } + + public TreeNode buildTree(int[] inorder, int[] postorder) { + return buildTree(inorder, 0, inorder.length, postorder, 0, + inorder.length); // end exclusive + + } + + private TreeNode buildTree(int[] inorder, int s1, int e1, int[] postorder, int s2, int e2) { + int len = e1 - s1; + if (len == 0) return null; + if (len == 1) return new TreeNode(inorder[0]); + + int rootVal = postorder[e2 - 1]; + TreeNode root = new TreeNode(rootVal); + int rootLoc = -1; + for (int i = 0; i < len; i++) { + if (inorder[s1 + i] == rootVal) { + rootLoc = s1 + i; + break; + } + } + + int leftLen = rootLoc - s1; + int rightLen = e1 - rootLoc - 1; + + root.left = buildTree(inorder, s1, rootLoc, postorder, s2, s2 + leftLen); // end exclusive + root.right = buildTree(inorder, rootLoc + 1, e1, postorder, s2 + leftLen, s2 + leftLen + rightLen); // end exclusive + + return root; + } + +} diff --git a/My Solutions/InsertInterval.java b/My Solutions/InsertInterval.java new file mode 100644 index 00000000..8f5565a1 --- /dev/null +++ b/My Solutions/InsertInterval.java @@ -0,0 +1,74 @@ +import java.util.*; + +public class InsertInterval { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + InsertInterval ii = new InsertInterval(); + List l = new LinkedList<>(); + l.add(new Interval(2, 4)); + l.add(new Interval(5, 7)); + l.add(new Interval(8, 10)); + l.add(new Interval(11, 13)); + List ret = ii.insert(l, new Interval(3, 8)); + + return; + + } + + public List insert(List intervals, Interval newInterval) { + List ret = new LinkedList<>(); + int len = intervals.size(); + if (len == 0) { + ret.add(newInterval); + return ret; + } + + if (newInterval.end < intervals.get(len - 1).start) { + ret.add(newInterval); + ret.addAll(intervals); + return ret; + } + + if (newInterval.start > intervals.get(len - 1).end) { + ret.addAll(intervals); + ret.add(newInterval); + return ret; + } + + int i = 0, start = 0, end = 0; + while (i < len) { + Interval in = intervals.get(i); + if (newInterval.start > in.end) { + i++; + ret.add(in); + } else { + start = Math.min(newInterval.start, in.start); // record the + // starting + // point + break; + } + } + + while (i < len) { + Interval in = intervals.get(i); + if (newInterval.end >= intervals.get(i).start) + i++; + else { + end = Math.max(newInterval.end, in.end); // record the starting + // point + break; + } + } + ret.add(new Interval(start, end)); + i++; + while (i < len) + ret.add(intervals.get(i++)); + return ret; + } + +} diff --git a/My Solutions/InsertionSortList.java b/My Solutions/InsertionSortList.java new file mode 100644 index 00000000..59583c3b --- /dev/null +++ b/My Solutions/InsertionSortList.java @@ -0,0 +1,70 @@ +import java.util.*; + +public class InsertionSortList { + + /** + * @param args + */ + public static void main(String[] args) { + + int t = 0; + System.out.println(t); + + InsertionSortList isl = new InsertionSortList(); + ListNode a = new ListNode(3); + a.next = new ListNode(2); + a.next.next = new ListNode(1); + ListNode ret = isl.insertionSortList(a); + return; + + } + + public ListNode insertionSortList(ListNode head) { + + ListNode vHead = new ListNode(-1); + // vHead.next = head; + + ListNode curr = head; + + // idea: for each current node, scan the first element that is larger, + // and insert curr before that node. + while (curr != null) { + + ListNode pre = vHead; + while (pre.next != null && pre.next.val <= curr.val) { + pre = pre.next; + } + ListNode n = curr.next; + curr.next = pre.next; + pre.next = curr; + curr = n; + } + + return vHead.next; + + } + + public String largestNumber(int[] num) { + int len = num.length; + List nums = new ArrayList<>(); + + for (int i : num) + nums.add(Integer.toString(i)); + Collections.sort(nums, new Comparator() { + public int compare(String a, String b) { + return (b + a).compareTo(a + b); + } + }); + + StringBuilder sb = new StringBuilder(); + for (String n : nums) { + sb.append(n); + } + + if (sb.charAt(0) == '0' && sb.length() > 1) + return "0"; + + return sb.toString(); + } + +} diff --git a/My Solutions/Interval.java b/My Solutions/Interval.java new file mode 100644 index 00000000..e63c72f8 --- /dev/null +++ b/My Solutions/Interval.java @@ -0,0 +1,14 @@ +public class Interval { + int start; + int end; + + Interval() { + start = 0; + end = 0; + } + + Interval(int s, int e) { + start = s; + end = e; + } +} \ No newline at end of file diff --git a/My Solutions/JavaTest.java b/My Solutions/JavaTest.java new file mode 100644 index 00000000..dda2f0af --- /dev/null +++ b/My Solutions/JavaTest.java @@ -0,0 +1,21 @@ +import java.util.Stack; + +public class JavaTest { + Stack stack = new Stack(); + Stack mini = new Stack(); + public void push(int x) { + stack.push(x); + mini.push(x); + } + public boolean isSame() { + return mini.peek() == stack.peek(); + } + + public static void main(String[] args) { + JavaTest javaTest = new JavaTest(); + javaTest.push(128); + System.out.println(javaTest.isSame()); + javaTest.push(5); + System.out.println(javaTest.isSame()); + } +} diff --git a/My Solutions/KthLargestElementInAnArray.java b/My Solutions/KthLargestElementInAnArray.java new file mode 100644 index 00000000..c62ce530 --- /dev/null +++ b/My Solutions/KthLargestElementInAnArray.java @@ -0,0 +1,49 @@ +public class KthLargestElementInAnArray { + + /** + * @param args + */ + public static void main(String[] args) { + KthLargestElementInAnArray k = new KthLargestElementInAnArray(); + System.out.println(k.findKthLargest(new int[] { 7, 6, 5, 4, 3, 2, 1 }, + 2)); + + } + + public int findKthLargest(int[] nums, int k) { + return findKth(nums, 0, nums.length - 1, nums.length + 1 - k); + } + + private int findKth(int[] nums, int s, int e, int k) { + + if (e - s + 1 == 1 && k == 1) + return nums[s]; + + int nLeft = partition(nums, s, e, k); // including pivot + if (nLeft > k) + return findKth(nums, s, s + nLeft - 2, k); + else if (nLeft < k) + return findKth(nums, s + nLeft, e, k - nLeft); + else + return nums[s + nLeft - 1]; + } + + private int partition(int[] nums, int l, int r, int k) { + int pivot = nums[r]; + int pos = l; + for (int i = l; i < r; i++) { + if (nums[i] < pivot) { + int tmp = nums[pos]; + nums[pos] = nums[i]; + nums[i] = tmp; + pos++; + } + } + + int tmp = nums[pos]; + nums[pos] = pivot; + nums[r] = tmp; + + return pos - l + 1; + } +} \ No newline at end of file diff --git a/My Solutions/LRUCache.java b/My Solutions/LRUCache.java new file mode 100644 index 00000000..04dff873 --- /dev/null +++ b/My Solutions/LRUCache.java @@ -0,0 +1,82 @@ +import java.util.*; + +public class LRUCache { + + private int capacity = 0; + private DlinkedNode head; + private DlinkedNode tail; + private Map map; + + public static void main(String[] args) { + LRUCache lru = new LRUCache(1); + lru.set(2, 1); + lru.get(2); + lru.set(3, 2); + lru.get(2); + lru.get(3); + } + + public LRUCache(int capacity) { + this.capacity = capacity; + + head = new DlinkedNode(); + tail = new DlinkedNode(); + head.next = tail; + tail.pre = head; + + map = new HashMap(); + + } + + public int get(int key) { + DlinkedNode node = map.get(key); + if (node != null) { + removeNode(node); + addToHead(node); + return node.value; + } else { + return -1; + } + } + + public void set(int key, int value) { + DlinkedNode node = map.get(key); + if (node != null) { + removeNode(node); + addToHead(node); + } else { + node = new DlinkedNode(); + node.key = key; + node.value = value; + + if (map.size() < capacity) { + addToHead(node); + } else { + removeNode(tail.pre); + addToHead(node); + } + } + return; + } + + private void removeNode(DlinkedNode node) { + node.pre.next = node.next; + node.next.pre = node.pre; + map.remove(node.key); + } + + private void addToHead(DlinkedNode node) { + node.next = head.next; + head.next.pre = node; + head.next = node; + node.pre = head; + map.put(node.key, node); + } +} + +class DlinkedNode { + int key; + int value; + DlinkedNode pre = null; + DlinkedNode next = null; +} \ No newline at end of file diff --git a/My Solutions/LRUCacheNew.java b/My Solutions/LRUCacheNew.java new file mode 100644 index 00000000..26ea94ba --- /dev/null +++ b/My Solutions/LRUCacheNew.java @@ -0,0 +1,76 @@ +import java.util.*; + +public class LRUCacheNew { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + Map map; + int capacity; + DListNode head, tail; + + public LRUCacheNew(int capacity) { + map = new HashMap<>(); + this.capacity = capacity; + head = new DListNode(-1); + tail = head; + } + + public int get(int key) { + if (map.containsKey(key)) { + DListNode node = map.get(key); + removeNode(node); + addToHead(node); + return node.value; + } + return -1; + } + + public void set(int key, int value) { + if (map.containsKey(key)) { + DListNode node = map.get(key); + removeNode(node); + addToHead(node); + } else { + DListNode node = new DListNode(value); + if (map.size() >= capacity) { + map.remove(key); + removeTailNode(); + } + addToHead(node); + map.put(key, node); + } + } + + private void addToHead(DListNode node) { + node.pre = head; + node.next = head.next; + head.next.pre = node; + head.next = node; + } + + private void removeNode(DListNode node) { + node.pre.next = node.next; + node.next.pre = node.pre; + } + + private void removeTailNode() { + tail = tail.pre; + } + + class DListNode { + int value; + DListNode pre = null; + DListNode next = null; + + DListNode(int value) { + this.value = value; + } + } + +} diff --git a/My Solutions/LargestNumber.java b/My Solutions/LargestNumber.java new file mode 100644 index 00000000..5e139d93 --- /dev/null +++ b/My Solutions/LargestNumber.java @@ -0,0 +1,40 @@ +import java.util.*; +import java.util.function.Function; +import java.util.function.ToDoubleFunction; +import java.util.function.ToIntFunction; +import java.util.function.ToLongFunction; + +public class LargestNumber { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public String largestNumber(int[] num) { + int len = num.length; + List nums = new ArrayList<>(); + + for (int i: num) nums.add(Integer.toString(i)); + Collections.sort(nums, new MyComparator()); + + StringBuilder sb = new StringBuilder(); + for (String n: nums){ + sb.append(n); + } + + return sb.toString(); + } + + class MyComparator implements Comparator { + public int compare(String a, String b) { + return (a+b).compareTo(b+a); + } + } + +} + + diff --git a/My Solutions/LargestRectangleInHistogram.java b/My Solutions/LargestRectangleInHistogram.java new file mode 100644 index 00000000..b64e77ad --- /dev/null +++ b/My Solutions/LargestRectangleInHistogram.java @@ -0,0 +1,52 @@ +import java.util.*; + +public class LargestRectangleInHistogram { + + /** + * @param args + */ + public static void main(String[] args) { + largestRectangleArea(new int[] { 6, 2, 5, 4, 5, 1, 6 }); + } + + public static int largestRectangleArea(int[] height) { + int len = height.length, i = 0, max = 0; + Stack s = new Stack<>(); + + while (i < len) { + + if (s.isEmpty() || height[s.peek()] < height[i]) + s.push(i++); + else { + int h = height[s.pop()]; + int area = h * (s.isEmpty() ? i : i - s.peek() - 1); + max = Math.max(max, area); + } + } + + while (!s.isEmpty()) { + max = Math.max(max, + height[s.pop()] * (s.isEmpty() ? i : i - s.peek() - 1)); + } + + return max; + } + + public static int largestRectangleArea1(int[] height) { + height = Arrays.copyOf(height, height.length + 1); + + int maxRect = 0; + Stack stack = new Stack(); + for (int i = 0; i < height.length; ++i) { + while (!stack.isEmpty() && height[i] < height[stack.peek()]) { + int rect = height[stack.pop()] + * (stack.isEmpty() ? i : (i - stack.peek() - 1)); + maxRect = Math.max(maxRect, rect); + } + stack.push(i); + } + + return maxRect; + } + +} diff --git a/My Solutions/LetterCombination.java b/My Solutions/LetterCombination.java new file mode 100644 index 00000000..62098683 --- /dev/null +++ b/My Solutions/LetterCombination.java @@ -0,0 +1,32 @@ +import java.util.*; + +public class LetterCombination { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + private static String[] map = new String[] { "0", "1", "abc", "def", "ghi", + "jkl", "mno", "pqrs", "tuv", "wxyz" }; + + public List letterCombinations(String digits) { + + List res = new LinkedList<>(); + res.add(""); + for (int i = 0; i < digits.length(); i++) { + List tmpres = new LinkedList(); + for (String str : res) { + String letters = map[(int) (digits.charAt(i) - '0')]; + for (int j = 0; i < letters.length(); i++) { + tmpres.add(str + letters.charAt(i)); + } + } + res = tmpres; + } + return res; + } +} diff --git a/My Solutions/LevelOrderTraversal.java b/My Solutions/LevelOrderTraversal.java new file mode 100644 index 00000000..5236e533 --- /dev/null +++ b/My Solutions/LevelOrderTraversal.java @@ -0,0 +1,34 @@ +import java.util.*; + +public class LevelOrderTraversal { + public List> levelOrder(TreeNode root) { + + if (root == null) { + return null; + } + + List> results = new ArrayList>(); + + Queue children = new LinkedList(); + children.add(root); + while (true) { + List level = new ArrayList(); + Queue grandChildren = new LinkedList(); + + while (children.size() > 0) { + TreeNode child = children.poll(); + level.add(child.val); + if (child.left != null) { + grandChildren.add(child.left); + } + if (child.right != null) { + grandChildren.add(child.right); + } + } + results.add(level); + if (grandChildren.size() == 0) { + return results; + } + } + } +} diff --git a/My Solutions/ListNode.java b/My Solutions/ListNode.java new file mode 100644 index 00000000..055061ad --- /dev/null +++ b/My Solutions/ListNode.java @@ -0,0 +1,9 @@ +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } +} \ No newline at end of file diff --git a/My Solutions/LongestIncreasingSubsequence.java b/My Solutions/LongestIncreasingSubsequence.java new file mode 100644 index 00000000..bcf3f5ae --- /dev/null +++ b/My Solutions/LongestIncreasingSubsequence.java @@ -0,0 +1,36 @@ +public class LongestIncreasingSubsequence { + + /** + * @param args + */ + public static void main(String[] args) { + LongestIncreasingSubsequence lis = new LongestIncreasingSubsequence(); + System.out.println(lis.lengthOfLIS(new int[] { 10, 9, 2, 5, 3, 7, 101, + 18 })); + } + + public int lengthOfLIS(int[] nums) { + int len = 0; + int[] a = new int[nums.length]; + for (int n : nums) { + int j = search(nums, 0, len - 1, n); + a[j] = n; + if (j == len) + len++; + } + return len; + } + + // find the first one that is smaller than n + private int search(int[] nums, int l, int r, int key) { + while (l <= r) { + int m = l + (r - l) / 2; + if (nums[m] >= key) + r = m - 1; + else + l = m + 1; + } + return l; + } + +} diff --git a/My Solutions/LongestPalindromeSubstring.java b/My Solutions/LongestPalindromeSubstring.java new file mode 100644 index 00000000..7f134bf4 --- /dev/null +++ b/My Solutions/LongestPalindromeSubstring.java @@ -0,0 +1,68 @@ +public class LongestPalindromeSubstring { + + /** + * @param args + */ + public static void main(String[] args) { + LongestPalindromeSubstring lps = new LongestPalindromeSubstring(); + System.out.println(lps.longestPalindrome("aaabaaaa")); + } + + public String longestPalindrome(String s) { + // return solveN2(s); //time: O(N^2), space: O(1) + return solveDP(s); // time: O(N^2), space: O(N^2) + } + + private String solveDP(String s) { + int len = s.length(), maxLen = 1, start = 0; + boolean[][] dp = new boolean[len][len]; // just use the upperright + // corner + for (int i = 0; i < len; i++) + dp[i][i] = true; + for (int i = 0; i < len - 1; i++) + if (s.charAt(i) == s.charAt(i + 1)) { + dp[i][i + 1] = true; + maxLen = 2; + start = i; + } + + for (int l = 3; l <= len; l++) { + for (int i = 0; i <= len - l; i++) { + int j = i + l - 1; + if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) { + dp[i][j] = true; + maxLen = l; + start = i; + } + } + } + return s.substring(start, start + maxLen); + + } + + private String solveN2(String s) { + int len = s.length(), maxLen = 0, start = 0; + if (len < 2) + return s; + + for (int i = 0; i < len; i++) { + if (isPalindrome(s, i - maxLen, i)) { + start = i - maxLen; + maxLen++; + } else if (i - maxLen - 1 >= 0 + && isPalindrome(s, i - maxLen - 1, i)) { + start = i - maxLen - 1; + maxLen += 2; + } + } + return s.substring(start, start + maxLen); + } + + private boolean isPalindrome(String s, int i, int j) { + while (i < j) + if (s.charAt(i++) != s.charAt(j--)) + return false; + return true; + } + +} diff --git a/My Solutions/LongestSubstringWithoutRepeating.java b/My Solutions/LongestSubstringWithoutRepeating.java new file mode 100644 index 00000000..5ee18157 --- /dev/null +++ b/My Solutions/LongestSubstringWithoutRepeating.java @@ -0,0 +1,33 @@ +import java.util.*; + +public class LongestSubstringWithoutRepeating { + + /** + * @param args + */ + public static void main(String[] args) { + System.out.println(lengthOfLongestSubstring("aa")); + } + + public static int lengthOfLongestSubstring(String s) { + + int len = s.length(); + int maxLen = 0, start = 0; + + Map m = new HashMap<>(); + for (int i = 0; i < len; i++) { + Integer loc = m.get(s.charAt(i)); + if (loc != null) { + if (loc >= start) { + maxLen = Math.max(maxLen, (i - 1) - start + 1); + start = loc + 1; + } + } + maxLen = Math.max(maxLen, i - start + 1); + m.put(s.charAt(i), i); + } + + return maxLen; + } + +} diff --git a/My Solutions/LongestValidParentheses.java b/My Solutions/LongestValidParentheses.java new file mode 100644 index 00000000..95ec7ab4 --- /dev/null +++ b/My Solutions/LongestValidParentheses.java @@ -0,0 +1,70 @@ +import java.util.Stack; + +public class LongestValidParentheses { + + /** + * @param args + */ + public static void main(String[] args) { + LongestValidParentheses lvp = new LongestValidParentheses(); + System.out.println(lvp.dpSol("()(())")); + + } + + private int dpSol(String s) { + int len = s.length(); + if (len < 2) + return 0; + int[] dp = new int[len + 1]; // first is empty + + for (int i = 1; i < len; i++) { + char c = s.charAt(i); + if (c == '(') { + continue; + } else { + if (s.charAt(i - 1) == '(') { + dp[i + 1] = dp[i - 1] + 2; + } else { + if (i - dp[i] - 1 >=0 && s.charAt(i - dp[i] - 1) == '(') { + dp[i + 1] = dp[i - dp[i] - 1] + i - (i - dp[i] - 1) + 1 ; + } else { + dp[i + 1] = 0; + } + } + } + } + + int max = 0; + for (int i = 0; i <= len; i++) { + max = Math.max(max, dp[i]); + } + return max; + } + + private int stackSol(String s) { + int lenS = s.length(); + Stack stack = new Stack<>(); + int last = 0; + int maxLen = 0; + + for (int i = 0; i < lenS; i++) { + if (s.charAt(i) == '(') { + stack.push(i); + } else { + if (stack.isEmpty()) { + last = i + 1; // not valid, reset starting position + } else { // there is a matching '(' + stack.pop(); + if (stack.isEmpty()) { + maxLen = Math.max(maxLen, i - last + 1); + } else { + maxLen = Math.max(maxLen, i - (stack.peek() + 1) + 1); + } + } + } + } + + return maxLen; + } + +} diff --git a/My Solutions/MaxPoint.java b/My Solutions/MaxPoint.java new file mode 100644 index 00000000..bd82510c --- /dev/null +++ b/My Solutions/MaxPoint.java @@ -0,0 +1,50 @@ +import java.util.*; + +public class MaxPoint { + + /** + * @param args + */ + public static void main(String[] args) { + MaxPoint mp = new MaxPoint(); + + Point[] p = new Point[3]; + p[0] = new Point(2, 3); + p[1] = new Point(3, 3); + p[2] = new Point(-5, 3); + + System.out.println(mp.maxPoints(p)); + } + + public int maxPoints(Point[] points) { + int len = points.length; + if (len < 2) + return len; + int max = 0; + + for (int i = 0; i < len; i++) { + Map m = new HashMap<>(); + int overlap = 1, maxV = 0, maxSlope = 0; + for (int j = i + 1; j < len; j++) { + if (points[i].x == points[j].x && points[i].y == points[j].y) { + overlap++; + } else if (points[i].x == points[j].x) { + int count = m.containsKey(Double.MAX_VALUE) ? m + .get(Double.MAX_VALUE) : 0; + m.put(Double.MAX_VALUE, ++count); + maxV = Math.max(maxV, count); + } else { + double slope = points[i].y == points[j].y? 0: (double) (points[i].y - points[j].y) + / (double) (points[i].x - points[j].x); + int count = m.containsKey(slope) ? m.get(slope) : 0; + m.put(slope, ++count); + maxSlope = Math.max(maxSlope, count); + } + } + max = Math.max(max, maxV + overlap); + max = Math.max(max, maxSlope + overlap); + } + return max; + } + +} diff --git a/My Solutions/MaximalRectangle.java b/My Solutions/MaximalRectangle.java new file mode 100644 index 00000000..4e2feb52 --- /dev/null +++ b/My Solutions/MaximalRectangle.java @@ -0,0 +1,92 @@ +import java.util.Arrays; +import java.util.Stack; + +public class MaximalRectangle { + + /** + * @param args + */ + public static void main(String[] args) { + MaximalRectangle mr = new MaximalRectangle(); + System.out.println(mr.maximalRectangle(new char[][] { { '1', '1' } })); + + } + + public int maximalRectangle(char[][] matrix) { + + // return sol1(matrix); + return sol2(matrix); + } + + private int sol2(char[][] matrix) { + int nRow = matrix.length; + if (nRow == 0) + return 0; + int nCol = matrix[0].length; + int maxArea = 0; + int[] height = new int[nCol + 1]; // add a virtual right column + + for (int i = 0; i < nRow; i++) { + for (int j = 0; j < nCol; j++) { + if (matrix[i][j] == '1') + height[j]++; + else + height[j] = 0; + } + + Stack s = new Stack<>(); + int j = 0; + while (j <= nCol) { + if (s.isEmpty() || height[j] > height[s.peek()]) + s.push(j++); + else { + int h = height[s.pop()]; + int area = h * (s.isEmpty() ? j : (j - s.peek() - 1)); + maxArea = Math.max(area, maxArea); + } + } + } + + return maxArea; + } + + private int sol1(char[][] matrix) { + int nRow = matrix.length; + if (nRow == 0) + return 0; + int nCol = matrix[0].length; + int maxArea = 0; + + int[] left = new int[nCol], right = new int[nCol], height = new int[nCol]; + Arrays.fill(right, nCol); + for (int i = 0; i < nRow; i++) { + int curr_left = 0, curr_right = nCol; + for (int j = 0; j < nCol; j++) { + if (matrix[i][j] == '1') + height[j]++; + else + height[j] = 0; + } + for (int j = 0; j < nCol; j++) { + if (matrix[i][j] == '1') + left[j] = Math.max(left[j], curr_left); + else { + left[j] = 0; + curr_left = j + 1; + } + } + for (int j = nCol - 1; j >= 0; j--) { + if (matrix[i][j] == '1') + right[j] = Math.min(right[j], curr_right); + else { + right[j] = nCol; + curr_right = j; + } + } + for (int j = 0; j < nCol; j++) + maxArea = Math.max(maxArea, (right[j] - left[j]) * height[j]); + } + return maxArea; + } + +} diff --git a/My Solutions/MaximalSquare.java b/My Solutions/MaximalSquare.java new file mode 100644 index 00000000..138a3f7c --- /dev/null +++ b/My Solutions/MaximalSquare.java @@ -0,0 +1,33 @@ +public class MaximalSquare { + + /** + * @param args + */ + public static void main(String[] args) { + MaximalSquare ms = new MaximalSquare(); + System.out.println(ms.maxSquare(new int[][] { { 1, 0, 1, 0, 0 }, + { 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 1 }, { 1, 0, 0, 1, 0 } })); + } + + public int maxSquare(int[][] matrix) { + int nRow = matrix.length; + if (nRow == 0) + return 0; + int nCol = matrix[0].length; + + int[][] dp = new int[nRow + 1][nCol + 1]; + int max = 0; + + for (int i = 1; i <= nRow; i++) { + for (int j = 1; j <= nCol; j++) { + if (matrix[i - 1][j - 1] == '1') { + dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), + dp[i - 1][j - 1]) + 1; + max = Math.max(max, dp[i][j]); + } + } + } + + return max * max; + } +} diff --git a/My Solutions/MaximumGap.java b/My Solutions/MaximumGap.java new file mode 100644 index 00000000..518796eb --- /dev/null +++ b/My Solutions/MaximumGap.java @@ -0,0 +1,67 @@ +import java.util.*; + +public class MaximumGap { + + /** + * @param args + */ + public static void main(String[] args) { + MaximumGap mg = new MaximumGap(); + System.out.print(mg.maximumGap(new int[]{1, 10000000})); + + } + + public int maximumGap(int[] num) { + int len = num.length; + if (len < 2) + return 0; + int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; + for (int n : num) { + if (n > max) + max = n; + if (n < min) + min = n; + } + + int gapLen = (max - min) / len + 1; + Map m = new HashMap<>(); + + for (int n : num) { + int i = n / gapLen; + if (m.containsKey(i)) { + MyData tmp = m.get(i); + tmp.update(n); + m.put(i, tmp); + } else { + MyData tmp = new MyData(); + tmp.update(n); + m.put(i, tmp); + } + } + + int maxGap = Integer.MIN_VALUE; + int prev = min; + for (int i = 0; i <= len; i++) { + if (m.containsKey(i)) { + maxGap = Math.max(maxGap, m.get(i).min - prev); + prev = m.get(i).max; + } + } + return maxGap; + } + + class MyData { + int max, min; + + public MyData() { + max = Integer.MIN_VALUE; + min = Integer.MAX_VALUE; + } + + public void update(int n) { + this.max = Math.max(this.max, n); + this.min = Math.min(this.min, n); + } + } + +} diff --git a/My Solutions/MaximumProductSubarray.java b/My Solutions/MaximumProductSubarray.java new file mode 100644 index 00000000..41883c24 --- /dev/null +++ b/My Solutions/MaximumProductSubarray.java @@ -0,0 +1,59 @@ +public class MaximumProductSubarray { + + /** + * @param args + */ + public static void main(String[] args) { + System.out.print(maxProduct1(new int[] { -4, -3, -2 })); + + } + + public static int maxProduct1(int[] A) { + int len = A.length; + int max = A[0], min = A[0]; + int ret = A[0]; + + for (int i = 1; i < len; i++) { + if (A[i] < 0) { + max = max ^ min; + min = max ^ min; + max = max ^ min; + } + + max = Math.max(A[i], max * A[i]); + min = Math.min(A[i], min * A[i]); + ret = Math.max(ret, max); + + } + return max; + } + + public static int maxProduct(int A[]) { + // store the result that is the max we have found so far + int r = A[0]; + + // imax/imin stores the max/min product of + // subarray that ends with the current number A[i] + for (int i = 1, imax = r, imin = r; i < A.length; i++) { + // multiplied by a negative makes big number smaller, small number + // bigger + // so we redefine the extremums by swapping them + if (A[i] < 0) { + int tmp = imax; + imax = imin; + imin = tmp; + } + + // max/min product for the current number is either the current + // number itself + // or the max/min by the previous number times the current one + imax = Math.max(A[i], imax * A[i]); + imin = Math.min(A[i], imin * A[i]); + + // the newly computed max value is a candidate for our global result + r = Math.max(r, imax); + } + return r; + } + +} diff --git a/My Solutions/MaximumSubarray.java b/My Solutions/MaximumSubarray.java new file mode 100644 index 00000000..a8ee6cec --- /dev/null +++ b/My Solutions/MaximumSubarray.java @@ -0,0 +1,28 @@ +public class MaximumSubarray { + + /** + * @param args + */ + public static void main(String[] args) { + MaximumSubarray ms = new MaximumSubarray(); + System.out.println(ms.maxSubArray(new int[] { 1, -1, 1 })); + } + + public int maxSubArray(int[] nums) { + return dnc(nums, 0, nums.length - 1); + } + + private int dnc(int[] nums, int left, int right) { // divide and conquer + int len = right - left + 1; + if (len == 0) + return 0; + if (len == 1) + return nums[left]; + + int mid = left + (right - left) / 2; + int leftMax = dnc(nums, left, mid); + int rightMax = dnc(nums, mid + 1, right); + + return Math.max(leftMax + rightMax, Math.max(leftMax, rightMax)); + } +} diff --git a/My Solutions/MedianOfTwoSortedArray.java b/My Solutions/MedianOfTwoSortedArray.java new file mode 100644 index 00000000..b391925c --- /dev/null +++ b/My Solutions/MedianOfTwoSortedArray.java @@ -0,0 +1,83 @@ +import java.util.Arrays; + +public class MedianOfTwoSortedArray { + + public static void main(String[] args) { + int[] A = { 1, 2 }; + int[] B = { 1, 2 }; + System.out.println(findMedianSortedArrays(A, B)); + } + + public static double findMedianSortedArrays(int A[], int B[]) { + // return sol1(A, B); + + int m = A.length, n = B.length; + if (m == 0) return (B[n / 2] + B[(n - 1) / 2]) / 2; + if (n == 0) return (A[n / 2] + A[(n - 1) / 2]) / 2; + + if (m > n) + return sol2(B, A, Math.max(0, (n - m) / 2 - 1), + Math.min(n - 1, (m + n) / 2) - 1); + else + return sol2(A, B, Math.max(0, (m - n) / 2 - 1), + Math.min(m - 1, (m + n) / 2 - 1)); + + } + + private static double sol2(int A[], int B[], int left, int right) { + int m = A.length, n = B.length; + int i = (left + right) / 2; + int j = (m + n) / 2 - (i + 1) - 1; + + if ((j == -1 || A[i] > B[j]) && (j == m - 1 || A[i] <= B[j + 1])) + return A[i]; + else if ((j == -1 || A[i] > B[j]) && (j != m - 1 || A[i] > B[j + 1])) + return sol2(A, B, left, i - 1); + else + return sol2(A, B, i + 1, right); + } + + private static double sol1(int A[], int B[]) { + int lenA = A.length; + int lenB = B.length; + return (double) (findKth(A, 0, lenA - 1, B, 0, lenB - 1, + (lenA + lenB) / 2) + findKth(A, 0, lenA - 1, B, 0, lenB - 1, + (lenA + lenB - 1) / 2)) / 2; + } + + private static int findKth(int A[], int leftA, int rightA, int B[], + int leftB, int rightB, int k) { + int lenA = leftA > rightA ? 0 : rightA - leftA + 1; + int lenB = leftB > rightB ? 0 : rightB - leftB + 1; + + if (lenA == 0) { + return B[leftB + k]; + } else if (lenB == 0) { + return A[leftA + k]; + } + + int midAPos = lenA / 2; + int midBPos = lenB / 2; + int midAVal = A[leftA + midAPos]; + int midBVal = B[leftB + midBPos]; + + if (midAPos + midBPos < k) { + if (midAVal > midBVal) { + return findKth(A, leftA, rightA, B, leftB + midBPos + 1, + rightB, k - midBPos - 1); + } else { + return findKth(A, leftA + midAPos + 1, rightA, B, leftB, + rightB, k - midAPos - 1); + } + } else { + if (midAVal > midBVal) { + return findKth(A, leftA, leftA + midAPos - 1, B, leftB, rightB, + k); + } else { + return findKth(A, leftA, rightA, B, leftB, leftB + midBPos - 1, + k); + } + } + } + +} diff --git a/My Solutions/MergeIntervals.java b/My Solutions/MergeIntervals.java new file mode 100644 index 00000000..155e138b --- /dev/null +++ b/My Solutions/MergeIntervals.java @@ -0,0 +1,24 @@ +import java.util.*; + +public class MergeIntervals { + + /** + * @param args + */ + public static void main(String[] args) { + MergeIntervals mi = new MergeIntervals(); + + } + + public List merge(List intervals) { + + Collections.sort(intervals, new Comparator() { + public int compare(Interval i1, Interval i2) { + return Integer.compare(i1.start, i2.start); + } + }); + + return intervals; + + } +} diff --git a/My Solutions/MergeKSortedList.java b/My Solutions/MergeKSortedList.java new file mode 100644 index 00000000..71526569 --- /dev/null +++ b/My Solutions/MergeKSortedList.java @@ -0,0 +1,54 @@ +import java.util.List; + +public class MergeKSortedList { + + + public ListNode mergeKLists(List lists) { + + int len = lists.size(); + + if (len == 0) { + return null; + } else if (len == 1) { + return lists.get(0); + } else if (len == 2) { + return mergeSort(lists.get(0), lists.get(1)); + } else { + return mergeSort(mergeKLists(lists.subList(0, len / 2)), + mergeKLists(lists.subList(len / 2, len))); + } + + } + + public ListNode mergeSort(ListNode l1, ListNode l2) { + + ListNode head = new ListNode(-1); + ListNode end = head; + + if (l1 == null) { + return l2; + } else if (l2 == null) { + return l1; + } + + while (l1 != null && l2 != null) { + if (l1.val < l2.val) { + end.next = new ListNode(l1.val); + l1 = l1.next; + } else { + end.next = new ListNode(l2.val); + l2 = l2.next; + } + end = end.next; + } + + if (l1 == null) { + end.next = l2; + } + if (l2 == null) { + end.next = l1; + } + + return head.next; + } +} \ No newline at end of file diff --git a/My Solutions/MergeSortedArray.java b/My Solutions/MergeSortedArray.java new file mode 100644 index 00000000..6d64b216 --- /dev/null +++ b/My Solutions/MergeSortedArray.java @@ -0,0 +1,31 @@ +public class MergeSortedArray { + public void merge(int A[], int m, int B[], int n) { + + + int lenA = A.length; + + for (int i = 0; i < m; i++) { + A[lenA - 1 - i] = A[m - 1 - i]; + } + + int ia = n, ib = 0, ic = 0; + while (ia < m + n && ib < n) { + if (A[ia] <= B[ib]) { + A[ic++] = A[ia++]; + } else { + A[ic++] = A[ib++]; + } + } + + if (ia > m + n) { + while (ib < n) { + A[ic++] = A[ib++]; + } + } else { + while (ia < m + n) { + A[ic++] = A[ia++]; + } + } + + } +} diff --git a/My Solutions/MinimumSizeSubarraySum.java b/My Solutions/MinimumSizeSubarraySum.java new file mode 100644 index 00000000..dcbcdf59 --- /dev/null +++ b/My Solutions/MinimumSizeSubarraySum.java @@ -0,0 +1,64 @@ +public class MinimumSizeSubarraySum { + + /** + * @param args + */ + public static void main(String[] args) { + MinimumSizeSubarraySum msss = new MinimumSizeSubarraySum(); + System.out.println(msss.minSubArrayLen(5, new int[] { 2, 3, 1, 1, 1, 1, + 1 })); + return; + } + + public int minSubArrayLen(int s, int[] nums) { + return solveNLogN(s, nums); + } + + private int solveNLogN(int s, int[] nums) { + int min = Integer.MAX_VALUE; + int[] sums = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + if (i == 0) + sums[i] = nums[i]; + else + sums[i] = sums[i - 1] + nums[i]; + } + for (int j = 0; j < nums.length; j++) { + if (sums[j] < s) + continue; + int i = binarySearch(0, j, sums[j] - s, sums); + min = Math.min(min, j - i); + } + return min == Integer.MAX_VALUE ? 0 : min; + } + + // find the rightmost that <= key + private int binarySearch(int start, int end, int key, int[] nums) { + int i = start, j = end; + while (i < j) { + int mid = (int) (i + Math.ceil((j - i) / 2.0)); + if (nums[mid] > key) + j = mid - 1; + else + i = mid; + } + return i; + } + + private int solveN(int s, int[] nums) { + int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE; + while (i <= j && j < nums.length) { + while (j < nums.length && sum < s) { + sum += nums[j++]; + } + if (sum < s) + break; // good! + while (i <= j && sum >= s) { + min = Math.min(min, j - i); + sum -= nums[i++]; + } + } + return min == Integer.MAX_VALUE ? 0 : min; + } + +} diff --git a/My Solutions/MinimumWindowSubstring.java b/My Solutions/MinimumWindowSubstring.java new file mode 100644 index 00000000..9f6945dc --- /dev/null +++ b/My Solutions/MinimumWindowSubstring.java @@ -0,0 +1,143 @@ +import java.util.*; + +public class MinimumWindowSubstring { + + /** + * @param args + */ + public static void main(String[] args) { + MinimumWindowSubstring mws = new MinimumWindowSubstring(); + System.out.println(mws.findSubstring("abababab", new String[] { "a", + "b", "a" })); + } + + public List findSubstring(String s, String[] words) { + // return brutalForce(s, words); + return slidingWindow(s, words); + } + + private List slidingWindow(String s, String[] words) { + List result = new LinkedList<>(); + if (words.length == 0 || words[0].length() == 0 + || s.length() < words[0].length()) + return result; + + HashMap dict = new HashMap<>(); + for (int i = 0; i < words.length; i++) + dict.put(words[i], + dict.containsKey(words[i]) ? dict.get(words[i]) + 1 : 1); + + int winSize = words.length * words[0].length(); + int wordLen = words[0].length(); + + for (int offset = 0; offset < wordLen; offset++) { + int i = offset, j = i; + HashMap curr = new HashMap<>(dict); + while (j <= s.length() - wordLen) { + String str = s.substring(j, j + wordLen); + if (curr.containsKey(str)) { + if (curr.get(str) > 0) { // match + curr.put(str, curr.get(str) - 1); + } else { // more than needed, try shift to the right + if (s.substring(i, i + wordLen).equals(str)) { + i += wordLen; // succeed. + } else { // failed. move i to the right. + while (!s.substring(i, i + wordLen).equals(str)) { + curr.put( + s.substring(i, i + wordLen), + curr.get(s.substring(i, i + wordLen)) + 1); + i += wordLen; + } + i += wordLen; // start from next + } + } + } else { + i = j + wordLen; + curr = new HashMap<>(dict); + } + j += wordLen; + if (j - i == winSize) { + result.add(i); + } + } + + } + return result; + } + + private List improvedBrutalForce(String s, String[] words) { + List result = new LinkedList<>(); + if (words.length == 0 || words[0].length() == 0 + || s.length() < words[0].length()) + return result; + + Hashtable dict = new Hashtable<>(); + for (int i = 0; i < words.length; i++) + dict.put(words[i], + dict.containsKey(words[i]) ? dict.get(words[i]) + 1 : 1); + + int winSize = words.length * words[0].length(); + int wordLen = words[0].length(); + + for (int offset = 0; offset < wordLen; offset++) { + int i = offset; + + while (i <= s.length() - winSize) { + Hashtable curr = new Hashtable<>(dict); + int j = i; + while (j < s.length() && j - i < winSize) { + String str = s.substring(j, j + wordLen); + if (!curr.containsKey(str)) { + break; + } else { + int count = curr.get(str); + if (count > 1) { + curr.put(str, count - 1); + } else { + curr.remove(str); + } + } + j += wordLen; + } + if (curr.size() == 0) { // found!!! + result.add(i); + } + i += wordLen; + } + } + return result; + } + + private List brutalForce(String s, String[] words) { + List ret = new LinkedList<>(); + + int sLen = s.length(); + int wLen = words.length; + + if (wLen == 0) + return ret; + int wordLen = words[0].length(); + + Map wordSet = new HashMap<>(); + for (String w : words) + wordSet.put(w, wordSet.containsKey(w) ? wordSet.get(w) + 1 : 1); + + for (int i = 0; i + wordLen * wLen <= sLen; i++) { + Map currSet = new HashMap<>(wordSet); + for (int j = i; j - i < wordLen * wLen; j += wordLen) { + String currStr = s.substring(j, j + wordLen); + if (!currSet.containsKey(currStr)) + break; + int count = currSet.get(currStr); + if (count > 1) + currSet.put(currStr, count - 1); + else + currSet.remove(currStr); + } + if (currSet.isEmpty()) + ret.add(i); + } + + return ret; + } +} diff --git a/My Solutions/NQueen.java b/My Solutions/NQueen.java new file mode 100644 index 00000000..7df2f6eb --- /dev/null +++ b/My Solutions/NQueen.java @@ -0,0 +1,67 @@ +import java.util.*; + +public class NQueen { + + /** + * @param args + */ + public static void main(String[] args) { + NQueen nq = new NQueen(); + + List sol = nq.solveNQueens(1); + return; + + } + + private boolean[] column, diag, diagx; + private int nRow; + private List res; + private int[] queen; + + public List solveNQueens(int n) { + + res = new ArrayList<>(); + nRow = n; + column = new boolean[n]; + diag = new boolean[2 * n + 1]; + diagx = new boolean[2 * n - 1]; + queen = new int[n]; + + DFS(1); + return res; + } + + private void DFS(int n) { + if (n > nRow) { + res.add(genSolution()); + return; + } + + for (int i = 0; i < nRow; i++) { + if (column[i] || diag[i + n - 1] || diagx[n + nRow - i - 2]) { + continue; + } else { + column[i] = diag[i + n - 1] = diagx[n + nRow - i - 2] = true; + queen[n - 1] = i; + DFS(n + 1); + column[i] = diag[i + n - 1] = diagx[n + nRow - i - 2] = false; + } + } + } + + private String[] genSolution() { + String[] sol = new String[nRow]; + for (int i = 0; i < nRow; i++) { + StringBuilder s = new StringBuilder(); + for (int j = 0; j < nRow; j++) { + if (queen[i] == j) { + s.append('Q'); + } else + s.append('.'); + } + sol[i] = s.toString(); + } + return sol; + } + +} diff --git a/My Solutions/NQueenII.java b/My Solutions/NQueenII.java new file mode 100644 index 00000000..dbc99861 --- /dev/null +++ b/My Solutions/NQueenII.java @@ -0,0 +1,51 @@ +import java.util.*; + +public class NQueenII { + + /** + * @param args + */ + public static void main(String[] args) { + NQueenII nq = new NQueenII(); + + System.out.println(nq.totalNQueens(4)); + return; + + } + + private int nQueen; + private boolean[] column, diag, diagx; + private int[] queen; + private int total = 0; + + public int totalNQueens(int n) { + + this.nQueen = n; + this.column = new boolean[n]; + this.diag = new boolean[2 * n - 1]; + this.diagx = new boolean[2 * n - 1]; + this.queen = new int[n]; + + DFS(1); + return total; + } + + private void DFS(int n) { + if (n > nQueen) { + total += 1; + return; + } + + for (int i = 0; i < nQueen; i++) { + if (column[i] | diag[n - 1 + i] | diagx[n - 1 + nQueen - 1 - i]) { + continue; + } else { + column[i] = diag[n - 1 + i] = diagx[n - 1 + nQueen - 1 - i] = true; + queen[n - 1] = i; + DFS(n + 1); + column[i] = diag[n - 1 + i] = diagx[n - 1 + nQueen - 1 - i] = false; + } + } + } + +} diff --git a/My Solutions/NextPermutation.java b/My Solutions/NextPermutation.java new file mode 100644 index 00000000..e29a1ca2 --- /dev/null +++ b/My Solutions/NextPermutation.java @@ -0,0 +1,40 @@ +public class NextPermutation { + + /** + * @param args + */ + public static void main(String[] args) { + NextPermutation np = new NextPermutation(); + np.nextPermutation(new int[] { 5, 1, 1 }); + return; + } + + public void nextPermutation(int[] num) { + int n = num.length; + if (n < 2) + return; + + int i = n - 1; + while (i > 0 && num[i - 1] >= num[i]) + i--; + + int j = i; + if (i > 0) { + while (j < n && num[j] > num[i - 1]) + j++; + // swap + int tmp = num[i - 1]; + num[i - 1] = num[j - 1]; + num[j - 1] = tmp; + } + + // reverse + j = n - 1; + while (i < j) { + int tmp = num[i]; + num[i++] = num[j]; + num[j--] = tmp; + } + } + +} diff --git a/My Solutions/Palindrome.java b/My Solutions/Palindrome.java new file mode 100644 index 00000000..0541695e --- /dev/null +++ b/My Solutions/Palindrome.java @@ -0,0 +1,31 @@ +public class Palindrome { + public boolean isPalindrome(String s) { + int len = s.length(); + if (len == 0) + return true; + + int begin = 0, end = len - 1; + + while (begin <= end) { + while (!isAlphaNumeric(s.charAt(begin))) + begin++; + while (!isAlphaNumeric(s.charAt(end))) + end--; + + if (Character.toLowerCase(s.charAt(begin)) == Character + .toLowerCase(s.charAt(end))) { + begin++; + end--; + } else { + return false; + } + } + return true; + } + + public boolean isAlphaNumeric(char c) { + if (Character.isLetterOrDigit(c)) + return true; + return false; + } +} diff --git a/My Solutions/PalindromePartition.java b/My Solutions/PalindromePartition.java new file mode 100644 index 00000000..7fc940b5 --- /dev/null +++ b/My Solutions/PalindromePartition.java @@ -0,0 +1,73 @@ +import java.util.*; + +public class PalindromePartition { + public static void main(String[] args) { + + PalindromePartition pp = new PalindromePartition(); + List> result = pp.partition("a"); + return; + } + + private List> result; + private List curr; + + public List> partition(String s) { + + result = new LinkedList<>(); + curr = new ArrayList<>(); + + backTracking(s); + return result; + } + + private void backTracking(String s) { + int len = s.length(); + if (len == 0) { + result.add(new LinkedList<>(curr)); + return; + } + + for (int i = 1; i <= len; i++) { + String left = s.substring(0, i); + if (!isPalindrome(left)) + continue; + curr.add(left); + String right = s.substring(i); + backTracking(right); + curr.remove(curr.size() - 1); + } + } + + private boolean isPalindrome(String s) { + int i = 0, j = s.length() - 1; + while (i < j) + if (s.charAt(i++) != s.charAt(j--)) + return false; + return true; + } + + public List> partitionOld(String s) { + + List> result = new LinkedList<>(); + int len = s.length(); + + for (int i = 1; i <= len; i++) { + String firstHalf = s.substring(0, i); + if (isPalindrome(firstHalf)) { + List> partitions = partition(s.substring(i)); + if (partitions.isEmpty()) { + List l = new LinkedList<>(); + l.add(firstHalf); + partitions.add(l); + + } else { + for (List l : partitions) { + l.add(firstHalf); + } + } + result.addAll(partitions); + } + } + return result; + } +} diff --git a/My Solutions/PalindromePartitioningII.java b/My Solutions/PalindromePartitioningII.java new file mode 100644 index 00000000..181de4f4 --- /dev/null +++ b/My Solutions/PalindromePartitioningII.java @@ -0,0 +1,29 @@ +public class PalindromePartitioningII { + + /** + * @param args + */ + public static void main(String[] args) { + PalindromePartitioningII pp2 = new PalindromePartitioningII(); + pp2.minCut("bb"); + } + + public int minCut(String s) { + + int len = s.length(); + int[] t = new int[len + 1]; // DP table + + for (int i = 0; i <= len; i++) + t[i] = i - 1; // let t[0] = -1 for consistency + for (int i = 0; i < len; i++) { + for (int j = 0; i - j >= 0 && i + j < len + && s.charAt(i - j) == s.charAt(i + j); j++) + t[i + j + 1] = Math.min(t[i + j + 1], 1 + t[i - j]); + + for (int j = 0; i - j >= 0 && i + j + 1 < len + && s.charAt(i - j) == s.charAt(i + j + 1); j++) + t[i + j + 2] = Math.min(t[i + j + 2], 1 + t[i - j]); + } + return t[len]; + } +} diff --git a/My Solutions/PathSum.java b/My Solutions/PathSum.java new file mode 100644 index 00000000..3fcd4058 --- /dev/null +++ b/My Solutions/PathSum.java @@ -0,0 +1,38 @@ +import java.util.ArrayList; +import java.util.List; + +public class PathSum { + public List> pathSum(TreeNode root, int sum) { + + List> listlist = new ArrayList>(); + + if (root == null) { + return listlist; + } + + if (root.left == null && root.right == null) { + + if (root.val == sum) { + List list = new ArrayList(); + list.add(root.val); + listlist.add(list); + } + + } else { + List> ll1 = pathSum(root.left, sum - root.val); + List> ll2 = pathSum(root.right, sum - root.val); + for (List l : ll1) { + l.add(0, root.val); + listlist.add(l); + } + ; + for (List l : ll2) { + l.add(0, root.val); + listlist.add(l); + } + ; + } + + return listlist; + } +} diff --git a/My Solutions/PermutationSequence.java b/My Solutions/PermutationSequence.java new file mode 100644 index 00000000..0c1eece8 --- /dev/null +++ b/My Solutions/PermutationSequence.java @@ -0,0 +1,37 @@ +import java.util.*; + +public class PermutationSequence { + + /** + * @param args + */ + public static void main(String[] args) { + getPermutation(3, 4); + + } + + public static String getPermutation(int n, int k) { + List cand = new LinkedList<>(); + for (int i = 1; i <= n; i++) + cand.add(i); + StringBuilder sb = new StringBuilder(); + k--; + + for (int i = n - 1; i >= 0; i--) { + int pos = (int) Math.ceil(k / factorial(i)); + k %= factorial(i); + sb.append(cand.get(pos)); + cand.remove(pos); + } + + return sb.toString(); + } + + private static int factorial(int n) { + int ret = 1; + for (int i = 1; i < n; i++) + ret *= i; + return ret; + } + +} diff --git a/My Solutions/Permutations.java b/My Solutions/Permutations.java new file mode 100644 index 00000000..da8f8b37 --- /dev/null +++ b/My Solutions/Permutations.java @@ -0,0 +1,49 @@ +import java.util.*; + +public class Permutations { + + /** + * @param args + */ + public static void main(String[] args) { + Permutations p = new Permutations(); + p.permute(new int[] { -1, -1, 3, -1 }); + } + + private int[] num; + private boolean[] flag; + private int n; + private List> ret; + private LinkedList curr; + + public List> permute(int[] num) { + int len = num.length; + this.num = num; + this.flag = new boolean[len]; + this.n = len; + this.ret = new LinkedList<>(); + this.curr = new LinkedList<>(); + + permute(0); + return ret; + } + + private void permute(int k) { + if (k == n) { + ret.add(curr); + curr = new LinkedList<>(); + return; + } + + for (int i = 0; i < n; i++) { + if (i > 0 && num[i] == num[i - 1]) continue; + if (!flag[i]) { + curr.add(num[i]); + flag[i] = true; + permute(k + 1); + flag[i] = false; + curr.removeLast(); + } + } + } +} diff --git a/My Solutions/PermutationsII.java b/My Solutions/PermutationsII.java new file mode 100644 index 00000000..404a7fbc --- /dev/null +++ b/My Solutions/PermutationsII.java @@ -0,0 +1,51 @@ +import java.util.*; + +public class PermutationsII { + + /** + * @param args + */ + public static void main(String[] args) { + PermutationsII p2 = new PermutationsII(); + p2.permuteUnique(new int[] { -1, -1, 3, -1 }); + } + + private int[] num; + private boolean[] flag; + private int n; + private List> ret; + private LinkedList curr; + + public List> permuteUnique(int[] num) { + int len = num.length; + Arrays.sort(num); + this.num = num; + this.flag = new boolean[len]; + this.n = len; + this.ret = new LinkedList<>(); + this.curr = new LinkedList<>(); + + permute(0); + return ret; + } + + private void permute(int k) { + if (k == n) { + ret.add(new LinkedList<>(curr)); + return; + } + + for (int i = 0; i < n; i++) { + if (!flag[i]) { + if (i > 0 && num[i] == num[i - 1] && flag[i - 1] == true) + continue; + curr.add(num[i]); + flag[i] = true; + permute(k + 1); + flag[i] = false; + curr.removeLast(); + } + } + } + +} diff --git a/My Solutions/PhoneInterview.java b/My Solutions/PhoneInterview.java new file mode 100644 index 00000000..814b4f21 --- /dev/null +++ b/My Solutions/PhoneInterview.java @@ -0,0 +1,67 @@ +import java.util.*; + +public class PhoneInterview { + + /** + * @param args + */ + public static void main(String[] args) { + PhoneInterview pi = new PhoneInterview(); + + pi.myTest(); + + } + + private void myTest() { + + List testList = new LinkedList<>(); + int[] testArray = new int[] { 1, 2, 3, 4 }; + testList.subList(0, 1); + Arrays.sort(testArray); + Collections.sort(testList); + Collections.reverse(testList); + } + + public boolean isParlindrome(String s) { + + if (s == null) return false; + int n = s.length(); + if (n < 2) return true; + + int i = 0, j = n - 1; + while (i < j) { + if (s.charAt(i) != s.charAt(j)) return false; + } + return true; + } + + class Averager { + + int nWnd; + Queue values; + + public Averager(int n) { + nWnd = n; + values = new LinkedList<>(); + } + + public double addValue(double num) { + int len = values.size(); + if (len < nWnd) values.add(num); + else { + values.remove(); + values.add(num); + } + return getAvg(); + } + + private double getAvg() { + double sum = 0; + for (Double v: values) { + sum += v; + } + return sum / values.size(); + } + } + +} \ No newline at end of file diff --git a/My Solutions/PlusOne.java b/My Solutions/PlusOne.java new file mode 100644 index 00000000..31853d2a --- /dev/null +++ b/My Solutions/PlusOne.java @@ -0,0 +1,35 @@ +import java.util.Arrays; + +public class PlusOne { + + /** + * @param args + */ + public static void main(String[] args) { + plusOne(new int[] { 0 }); + + } + + public static int[] plusOne(int[] digits) { + + int len = digits.length; + int newdigits[] = new int[len + 1]; + int carry = 0, sum = 0; + for (int i = len - 1; i >= 0; i--) { + sum = digits[i] + carry; + if (sum > 9) { + carry = 1; + newdigits[i + 1] = sum % 10; + } else { + carry = 0; + newdigits[i + 1] = sum; + } + } + if (carry == 1) { + newdigits[0] = 1; + return newdigits; + } else + return Arrays.copyOfRange(newdigits, 1, len + 1); + } + +} diff --git a/My Solutions/Point.java b/My Solutions/Point.java new file mode 100644 index 00000000..3e3a2884 --- /dev/null +++ b/My Solutions/Point.java @@ -0,0 +1,14 @@ +class Point { + int x; + int y; + + Point() { + x = 0; + y = 0; + } + + Point(int a, int b) { + x = a; + y = b; + } +} \ No newline at end of file diff --git a/My Solutions/PopulatingNextRightPointerInEachNode.java b/My Solutions/PopulatingNextRightPointerInEachNode.java new file mode 100644 index 00000000..60deac08 --- /dev/null +++ b/My Solutions/PopulatingNextRightPointerInEachNode.java @@ -0,0 +1,56 @@ +import java.util.*; + +public class PopulatingNextRightPointerInEachNode { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public void connect(TreeLinkNode root) { + + sol2(root); + // sol1(root); + } + + private void sol2(TreeLinkNode root) { + + TreeLinkNode left = root; + while (left != null) { + TreeLinkNode curr = left; + while (curr != null) { + if (curr.left != null) + curr.left.next = curr.right; + if (curr.right != null && curr.next != null) + curr.right.next = curr.next.left; + curr = curr.next; + } + left = left.left; + } + } + + private void sol1(TreeLinkNode root) { + if (root == null || root.left == null && root.right == null) + return; + + Queue currQ = new LinkedList<>(); + Queue newQ; + currQ.add(root); + + while (!currQ.isEmpty()) { + newQ = new LinkedList<>(); + TreeLinkNode currN; + while ((currN = currQ.poll()) != null) { + if (currN.left != null) + newQ.add(currN.left); + if (currN.right != null) + newQ.add(currN.right); + currN.next = currQ.peek(); + } + currQ = newQ; + } + } +} diff --git a/My Solutions/PopulatingNextRightPointerInEachNodeII.java b/My Solutions/PopulatingNextRightPointerInEachNodeII.java new file mode 100644 index 00000000..6f85821b --- /dev/null +++ b/My Solutions/PopulatingNextRightPointerInEachNodeII.java @@ -0,0 +1,72 @@ +public class PopulatingNextRightPointerInEachNodeII { + + /** + * @param args + */ + public static void main(String[] args) { + + TreeLinkNode root = new TreeLinkNode(0); + root.left = new TreeLinkNode(2); + root.right = new TreeLinkNode(4); + root.left.left = new TreeLinkNode(1); + root.right.left = new TreeLinkNode(3); + root.right.right = new TreeLinkNode(-1); + root.left.left.left = new TreeLinkNode(5); + root.left.left.right = new TreeLinkNode(1); + root.right.left.right = new TreeLinkNode(6); + root.right.right.right = new TreeLinkNode(8); + + connect(root); + return; + + } + + public static void connect(TreeLinkNode root) { + TreeLinkNode tempChild = new TreeLinkNode(0); + while (root != null) { + tempChild.next = null; + + TreeLinkNode currentChild = tempChild; + while (root != null) { + if (root.left != null) { + currentChild.next = root.left; + currentChild = currentChild.next; + } + if (root.right != null) { + currentChild.next = root.right; + currentChild = currentChild.next; + } + root = root.next; + } + root = tempChild.next; + } + } + + public static void connect1(TreeLinkNode root) { + TreeLinkNode left = root; + + while (left != null) { + + TreeLinkNode curr = left; + left = null; + while (curr != null) { + if (left == null & curr.left != null) { + left = curr.left; + if (curr.right != null) + curr.left.next = curr.right; + if (curr.right == null && curr.next != null) + curr.left.next = curr.next.left == null ? curr.next.right + : curr.next.left; + } + if (left == null & curr.right != null) { + left = curr.right; + if (curr.next != null) + curr.right.next = curr.next.left == null ? curr.next.right + : curr.next.left; + } + curr = curr.next; + } + } + } + +} diff --git a/My Solutions/RPN.java b/My Solutions/RPN.java new file mode 100644 index 00000000..3f003e59 --- /dev/null +++ b/My Solutions/RPN.java @@ -0,0 +1,40 @@ +import java.util.Stack; + +public class RPN { + public int evalRPN(String[] tokens) { + + int len = tokens.length; + int op1, op2; + + Stack tokStack = new Stack(); + + for (int i = 0; i < len; i++) { + switch (tokens[i]) { + case "+": + op2 = tokStack.pop(); + op1 = tokStack.pop(); + tokStack.push(op1+op2); + break; + case "-": + op2 = tokStack.pop(); + op1 = tokStack.pop(); + tokStack.push(op1-op2); + break; + case "*": + op2 = tokStack.pop(); + op1 = tokStack.pop(); + tokStack.push(op1*op2); + break; + case "/": + op2 = tokStack.pop(); + op1 = tokStack.pop(); + tokStack.push(op1/op2); + break; + default: + tokStack.push(Integer.parseInt(tokens[i])); + break; + } + } + return tokStack.pop(); + } +} \ No newline at end of file diff --git a/My Solutions/RandomListNode.java b/My Solutions/RandomListNode.java new file mode 100644 index 00000000..df2fb57d --- /dev/null +++ b/My Solutions/RandomListNode.java @@ -0,0 +1,7 @@ +public class RandomListNode { + int label; + RandomListNode next, random; + RandomListNode(int x) { + this.label = x; + } +} diff --git a/My Solutions/RangeBitwiseAnd.java b/My Solutions/RangeBitwiseAnd.java new file mode 100644 index 00000000..ec05a8bd --- /dev/null +++ b/My Solutions/RangeBitwiseAnd.java @@ -0,0 +1,29 @@ +public class RangeBitwiseAnd { + + /** + * @param args + */ + public static void main(String[] args) { + RangeBitwiseAnd rba = new RangeBitwiseAnd(); + System.out.println(rba.rangeBitwiseAnd(3, 3)); + } + + public int rangeBitwiseAnd(int m, int n) { + + + + long low = 1, high = 2; + + while (high <= n && low <= m) { + low <<= 1; + high <<= 1; + } + + if (low <= m && high >= n) + return (int) low; + else + return 0; + + } + +} diff --git a/My Solutions/RecoverBinarySearchTree.java b/My Solutions/RecoverBinarySearchTree.java new file mode 100644 index 00000000..32844209 --- /dev/null +++ b/My Solutions/RecoverBinarySearchTree.java @@ -0,0 +1,80 @@ +public class RecoverBinarySearchTree { + + /** + * @param args + */ + public static void main(String[] args) { + RecoverBinarySearchTree rbst = new RecoverBinarySearchTree(); + TreeNode root = new TreeNode(1); + root.left = new TreeNode(3); + root.right = new TreeNode(2); + rbst.recoverTree(root); + return; + } + + TreeNode first = null, second = null, + prev = new TreeNode(Integer.MIN_VALUE); + + public void recoverTree(TreeNode root) { + sol1(root); + // sol2(root); + } + + private void sol2(TreeNode root) { // morris traversal + TreeNode curr = root, prev = null, tmp; + while (curr != null) { + if (curr.left == null) { + prev = curr; + curr = curr.right; + } else { + tmp = curr.left; + while (tmp.right != null && tmp.right != curr) + tmp = tmp.right; + if (tmp.right == null) { + tmp.right = curr; + curr = curr.left; + } else { // come to the rightmost child + tmp.right = null; + prev = curr; + curr = curr.right; + } + } + + if (prev != null && curr != null && prev.val > curr.val) { + if (first == null) { + first = prev; + second = curr; + } else + second = curr; + } + } + + int t = first.val; + first.val = second.val; + second.val = t; + + } + + private void sol1(TreeNode root) { + traverse(root); + int tmp = first.val; + first.val = second.val; + second.val = tmp; + return; + } + + private void traverse(TreeNode root) { + if (root == null) + return; + traverse(root.left); // inorder traversal + + if (first == null && prev.val > root.val) + first = prev; + if (first != null && prev.val > root.val) + second = root; // swap the smallest with the largest + + prev = root; + traverse(root.right); + } + +} diff --git a/My Solutions/RegularExpressionMatching.java b/My Solutions/RegularExpressionMatching.java new file mode 100644 index 00000000..da5bdb53 --- /dev/null +++ b/My Solutions/RegularExpressionMatching.java @@ -0,0 +1,42 @@ +public class RegularExpressionMatching { + + /** + * @param args + */ + public static void main(String[] args) { + RegularExpressionMatching rem = new RegularExpressionMatching(); + System.out.println(rem.isMatch("a", ".*..a*")); + } + + public boolean isMatch(String s, String p) { + int lenS = s.length(), lenP = p.length(); + if (lenP == 0) + return lenS == 0; + if (lenP == 1) + return lenS == 1 && isMatchFirst(s, p); + if (lenS == 0 && p.charAt(1) != '*') + return false; + + if (p.charAt(1) != '*') { + if (lenS < 2) { + return isMatchFirst(s, p) && isMatch("", p.substring(1)); + } else { + return isMatchFirst(s, p) + && isMatch(s.substring(1), p.substring(1)); + } + } + + int i = 0; + while (i < lenS && (s.charAt(i) == p.charAt(0) || p.charAt(0) == '.')) { + if (lenP > 2 && isMatch(s.substring(i), p.substring(2))) + return true; + i++; + } + + return isMatch(s.substring(i), p.substring(2)); + } + + private boolean isMatchFirst(String s, String p) { + return s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'; + } +} diff --git a/My Solutions/RemoveDuplicate.java b/My Solutions/RemoveDuplicate.java new file mode 100644 index 00000000..5a15cb4b --- /dev/null +++ b/My Solutions/RemoveDuplicate.java @@ -0,0 +1,28 @@ +public class RemoveDuplicate { + + public static void main(String[] args) { + System.out.println(removeDuplicates(new int[] { 1, 1, 2,2 })); + } + + public static int removeDuplicates(int[] A) { + + int len = A.length; + if (len < 2) + return len; + + int i = 0, j = 1; + + while (i < len && j < A.length) { + while (A[i] == A[j]) { + len--; + if (j < A.length - 1) { + j++; + } else { + return len; + } + } + A[++i] = A[j++]; + } + return len; + } +} diff --git a/My Solutions/RemoveDuplicatesFromSortedArrayII.java b/My Solutions/RemoveDuplicatesFromSortedArrayII.java new file mode 100644 index 00000000..ba90a51a --- /dev/null +++ b/My Solutions/RemoveDuplicatesFromSortedArrayII.java @@ -0,0 +1,32 @@ +public class RemoveDuplicatesFromSortedArrayII { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public int removeDuplicates(int[] A) { + int len = A.length; + if (len < 3) + return len; + + int i = 0; + int count = 1; + for (int j = 2; j < len; j++) { + if (A[j] != A[i] && count < 2) { + i++; + A[i] = A[j]; + count = 1; + } else if (A[j] == A[i] && count < 2) { + count++; + i++; + } + } + + return 0; + + } +} diff --git a/My Solutions/RemoveDuplicatesII.java b/My Solutions/RemoveDuplicatesII.java new file mode 100644 index 00000000..bf013091 --- /dev/null +++ b/My Solutions/RemoveDuplicatesII.java @@ -0,0 +1,90 @@ +import java.util.HashSet; +import java.util.Set; + +public class RemoveDuplicatesII { + + public static void main(String[] args) { + RemoveDuplicatesII rd = new RemoveDuplicatesII(); + + ListNode test = new ListNode(1); + test.next = new ListNode(2); + + printList(test); + + ListNode result = rd.deleteDuplicates(test); + printList (result); + + } + + public static void printList(ListNode l) { + while (l != null) { + System.out.println(l.val); + l = l.next; + } + } + + public ListNode deleteDuplicates(ListNode head) { + return solution2(head); + } + + + public ListNode solution2(ListNode head){ + if(head == null){ + return null; // for empty input + } + + ListNode vHead = new ListNode(-100000); // create a virtual start + ListNode prev = vHead; + ListNode curr = head; + + while(curr != null) { + boolean isRepeat = false; + while (curr.next != null && curr.next.val == curr.val){ + isRepeat = true; + curr=curr.next; + } + if(isRepeat){ + prev.next = curr.next; + isRepeat = false; + }else{ + prev.next = curr; + prev = curr; + } + curr = curr.next; + } + + return vHead.next; + } + + public ListNode solution1(ListNode head) { + + Set vSet = new HashSet(); + Set dupSet = new HashSet(); + + ListNode curr = head; + + while (curr != null) { + + if (vSet.contains(curr.val)) { + dupSet.add(curr.val); + } else { + vSet.add(curr.val); + } + curr = curr.next; + } + + ListNode vHead = new ListNode(0); // create a virtual head + ListNode prev = vHead; + + while (head != null) { + if (!dupSet.contains(head.val)) { + prev.next = head; + prev = head; + } + head = head.next; + prev.next = null; + } + + return vHead.next; + } +} \ No newline at end of file diff --git a/My Solutions/ReorderList.java b/My Solutions/ReorderList.java new file mode 100644 index 00000000..8b19ad11 --- /dev/null +++ b/My Solutions/ReorderList.java @@ -0,0 +1,84 @@ +import java.util.*; + +public class ReorderList { + + /** + * @param args + */ + public static void main(String[] args) { + ReorderList rl = new ReorderList(); + + ListNode a = new ListNode(1); + a.next = new ListNode(2); + a.next.next = new ListNode(3); + a.next.next.next = new ListNode(4); + rl.reorderList(a); + return; + } + + public void reorderList(ListNode head) { + + noStack(head); + return; + } + + private void noStack(ListNode head) { + if (head == null || head.next == null) + return; + ListNode vHead = new ListNode(0); + vHead.next = head; + ListNode slow = vHead, fast = vHead; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + ListNode rHead = slow.next; + slow.next = null; + + ListNode pre = null; + while (rHead!= null) { + ListNode tmp = rHead.next; + rHead.next = pre; + pre = rHead; + rHead = tmp; + } + + rHead = pre; + + while (head != null && rHead != null) { + ListNode tmp = rHead.next; + rHead.next = head.next; + head.next = rHead; + head = rHead.next; + rHead = tmp; + } + + return; + } + + private void useStack(ListNode head) { + if (head == null || head.next == null) + return; + ListNode slow = head, fast = head; + Stack s = new Stack<>(); + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + while (slow != null) { + s.push(slow); + slow = slow.next; + } + + slow = head; + while (!s.isEmpty()) { + fast = s.pop(); + fast.next = slow.next; + slow.next = fast; + slow = fast.next; + } + slow.next = null; + } + +} diff --git a/My Solutions/RepeatedDNASequence.java b/My Solutions/RepeatedDNASequence.java new file mode 100644 index 00000000..b29e5cea --- /dev/null +++ b/My Solutions/RepeatedDNASequence.java @@ -0,0 +1,48 @@ +import java.util.*; + +public class RepeatedDNASequence { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public List findRepeatedDnaSequences(String s) { + + return sol1(s); + //return sol2(s); + + } + + private List sol1(String s) { + HashMap m = new HashMap<>(); + List result = new LinkedList<>(); + + int len = s.length(); + if (len <= 10) { + return result; + } + + int key = 0; + for (int i = 0; i < 9; i++) { + key = key << 2 | s.charAt(i) >> 1 & 3; + } + + for (int i = 9; i < len; i++) { + Integer count = m + .get(key = (key << 2 & 0xFFFFF | s.charAt(i) >> 1 & 3)); + if (count == null) { + m.put(key, 1); + } else if (count == 1) { + result.add(s.substring(i - 9, i + 1)); + m.put(key, 2); + } + } + + return result; + } + +} diff --git a/My Solutions/RestoreIPAddress.java b/My Solutions/RestoreIPAddress.java new file mode 100644 index 00000000..9ba762fc --- /dev/null +++ b/My Solutions/RestoreIPAddress.java @@ -0,0 +1,51 @@ +import java.util.*; + +public class RestoreIPAddress { + + /** + * @param args + */ + public static void main(String[] args) { + RestoreIPAddress ria = new RestoreIPAddress(); + ria.restoreIpAddresses("25525511135"); + return; + + } + + private List ret; + private LinkedList ip; + + public List restoreIpAddresses(String s) { + ret = new LinkedList<>(); + ip = new LinkedList<>(); + int len = s.length(); + if (len < 4 || len > 12) + return ret; + + DFS(s, 0); + return ret; + } + + private void DFS(String s, int n) { + if (n == 4) { + if (s.length() == 0) { + StringBuilder sb = new StringBuilder(); + for (int i : ip) { + sb.append(i + ""); + } + ret.add(sb.toString().substring(0, sb.length())); + } + } + + for (int i = 1; i <= 3 && i <= s.length(); i++) { + String tmp = s.substring(0, i); + int subIP = Integer.parseInt(tmp); + if (subIP <= 255) { + ip.add(subIP); + DFS(s.substring(i), n + 1); + ip.removeLast(); + } + } + } + +} diff --git a/My Solutions/ReverseLinkedListII.java b/My Solutions/ReverseLinkedListII.java new file mode 100644 index 00000000..ccbaa51e --- /dev/null +++ b/My Solutions/ReverseLinkedListII.java @@ -0,0 +1,89 @@ +public class ReverseLinkedListII { + + public static void main(String[] args) { + ListNode a = new ListNode(1); + a.next = new ListNode(2); + a.next.next = new ListNode(3); + a.next.next.next = new ListNode(4); + a.next.next.next.next = new ListNode(5); + + //ListNode rst = reverseBetween(a, 2, 3); + ListNode rst = iterativeReverse(a); + + while (rst != null) { + System.out.println(rst.val); + rst = rst.next; + } + + } + + public static ListNode iterativeReverse(ListNode curr){ + + ListNode prev = null; + ListNode next = null; + + while (curr != null){ + next = curr.next; + curr.next=prev; + prev = curr; + curr = next; + } + + return prev; + + } + + public static ListNode recursiveReverse(ListNode head){ + if (head == null || head.next == null){ + return head; + } + + ListNode curr = head; + ListNode next = curr.next; + //curr.next = null; + + ListNode reversedHead = recursiveReverse(next); + next.next = curr; + + + return reversedHead; + + } + + public static ListNode reverseBetween(ListNode head, int m, int n) { + if (head == null || head.next == null || m == n) { + return head; + } + + ListNode vHead = new ListNode(-1); + vHead.next = head; + + ListNode pre = vHead; + + n = n - m; + + while (--m > 0) { + pre = pre.next; + } + + + + ListNode cur = pre.next; + ListNode next = cur.next; + + while (n-- > 0) { + ListNode nn = next.next; + next.next = cur; + cur = next; + next = nn; + } + + ListNode oldStart = pre.next; + pre.next = cur; + oldStart.next = next; + + return vHead.next; + + } + +} \ No newline at end of file diff --git a/My Solutions/ReverseNodeInKGroup.java b/My Solutions/ReverseNodeInKGroup.java new file mode 100644 index 00000000..43420665 --- /dev/null +++ b/My Solutions/ReverseNodeInKGroup.java @@ -0,0 +1,44 @@ +public class ReverseNodeInKGroup { + + /** + * @param args + */ + public static void main(String[] args) { + ListNode a = new ListNode(1); + a.next = new ListNode(2); + reverseKGroup(a, 3); + return; + } + + public static ListNode reverseKGroup(ListNode head, int k) { + if (head == null || head.next == null || k < 2) + return head; + ListNode vHead = new ListNode(-1); + vHead.next = head; + ListNode preHead = vHead, tail = vHead; + + while (true) { + + for (int i = 0; i < k; i++) { + if (tail.next == null) + return vHead.next; + tail = tail.next; + } + ListNode nn = tail.next; + ListNode pre = nn, curr = head; + + while (curr != nn) { + ListNode tmp = curr.next; + curr.next = pre; + pre = curr; + curr = tmp; + } + + preHead.next = tail; + tail = head; + head = tail.next; + + } + } + +} diff --git a/My Solutions/ReverseString.java b/My Solutions/ReverseString.java new file mode 100644 index 00000000..f826d3b4 --- /dev/null +++ b/My Solutions/ReverseString.java @@ -0,0 +1,33 @@ +public class ReverseString { + + public static void main(String[] args) { + String s = "Welcome"; + System.out.println(reverse(s)); + + System.out.println(fib(5)); + + System.out.println(formatRGB(123,211,40)); + } + + public static String reverse(String str) { + + char[] chars = str.toCharArray(); + int len = chars.length; + + for (int i = 0; i < len / 2; i++) { + char tmp = chars[i]; + chars[i] = chars[len - 1 - i]; + chars[len - 1 - i] = tmp; + } + + return new String(chars); + } + + public static int fib(int n) { + return n<2?1:fib(n-1)+fib(n-2); + } + + public static String formatRGB ( int r, int g, int b ) { + return String.format ( "%02X%02X%02X", r, g, b ); + } +} diff --git a/My Solutions/ReverseWordsInAString.java b/My Solutions/ReverseWordsInAString.java new file mode 100644 index 00000000..5c5f0ca3 --- /dev/null +++ b/My Solutions/ReverseWordsInAString.java @@ -0,0 +1,25 @@ +public class ReverseWordsInAString { + + /** + * @param args + */ + public static void main(String[] args) { + System.out.println(reverseWords(" a b ")); + + } + + public static String reverseWords(String s) { + + s = s.trim(); + String[] words = s.split(" "); + StringBuilder r = new StringBuilder(); + for (String w : words) { + if (w.equals("")) + continue; + r.insert(0, w.trim() + " "); + } + + return r.toString().trim(); + } + +} diff --git a/My Solutions/RightSideView.java b/My Solutions/RightSideView.java new file mode 100644 index 00000000..1f122daa --- /dev/null +++ b/My Solutions/RightSideView.java @@ -0,0 +1,41 @@ +import java.util.*; + +public class RightSideView { + + /** + * @param args + */ + public static void main(String[] args) { + RightSideView rsv = new RightSideView(); + + TreeNode root = new TreeNode(1); + + rsv.rightSideView(root); + + } + + public List rightSideView(TreeNode root) { + List ret = new LinkedList<>(); + if (root == null) + return ret; + + List curr = new LinkedList<>(); + curr.add(root); + ret.add(root.val); + + while (!curr.isEmpty()) { + LinkedList next = new LinkedList<>(); + while (!curr.isEmpty()) { + TreeNode tmp = curr.remove(0); + if (tmp.left != null) + next.add(tmp.left); + if (tmp.right != null) + next.add(tmp.right); + } + ret.add(next.getLast().val); + curr = next; + } + return ret; + } + +} diff --git a/My Solutions/RomanToInt.java b/My Solutions/RomanToInt.java new file mode 100644 index 00000000..f073c095 --- /dev/null +++ b/My Solutions/RomanToInt.java @@ -0,0 +1,29 @@ +import java.util.*; + +public class RomanToInt { + private static Map rMap; + static { + rMap = new HashMap(); + rMap.put('I', 1); + rMap.put('V', 5); + rMap.put('X', 10); + rMap.put('L', 50); + rMap.put('C', 100); + rMap.put('D', 500); + rMap.put('M', 1000); + }; + + public int romanToInt(String s) { + int result = 0; + int len = s.length(); + + for (int i = 0; i < len; i++) { + int v = rMap.get(s.charAt(i)); + if (i < len - 1 && v < rMap.get(s.charAt(i + 1))) { + v = -v; + } + result += v; + } + return result; + } +} \ No newline at end of file diff --git a/My Solutions/RotateList.java b/My Solutions/RotateList.java new file mode 100644 index 00000000..69825587 --- /dev/null +++ b/My Solutions/RotateList.java @@ -0,0 +1,47 @@ +public class RotateList { + + /** + * @param args + */ + public static void main(String[] args) { + RotateList rl = new RotateList(); + ListNode a = new ListNode(1); + a.next = new ListNode(2); + ListNode ret = rl.rotateRight(a, 5); + return; + + } + + public ListNode rotateRight(ListNode head, int n) { + + if (head == null || head.next == null) + return head; + ListNode fast = head, slow = head; + + int count = 1; + while (fast.next != null) { + count++; + fast = fast.next; + } + fast = head; + + for (int i = 0; i < n % count; i++) { + if (fast.next != null) { + fast = fast.next; + } else { + fast = head; + } + } + + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + + fast.next = head; + ListNode ret = slow.next; + slow.next = null; + return ret; + } + +} diff --git a/My Solutions/RotatedSortedArray.java b/My Solutions/RotatedSortedArray.java new file mode 100644 index 00000000..5ba3dd38 --- /dev/null +++ b/My Solutions/RotatedSortedArray.java @@ -0,0 +1,90 @@ +public class RotatedSortedArray { + + public static void main(String[] args) { + + RotatedSortedArray rsa = new RotatedSortedArray(); + + int[] array = {2,3,4,5,1}; + + System.out.println(rsa.search(array, 1)); + } + + public int search(int[] A, int target) { + + switch (A.length) { + case 0: + return -1; + case 1: + if (A[0] == target) { + return 0; + } else { + return -1; + } + case 2: + if (A[0] == target) { + return 0; + } else if (A[1] == target) { + return 1; + } else { + return -1; + } + default: + + int pivot = findPivot(A, 0, A.length - 1); + System.out.println("pivot:" + pivot); + + if (pivot == -1) { + return binarySearch(A, target, 0, A.length - 1); + } else { + int first = binarySearch(A, target, 0, pivot - 1); + if (first == -1) { + return binarySearch(A, target, pivot, A.length - 1); + } else { + return first; + } + } + } + } + + public int binarySearch(int[] A, int target, int left, int right) { + while (left <= right) { + int mid = (left + right) / 2; + if (A[mid] == target) { + return mid; + } else if (A[mid] > target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return -1; + + } + + public int findPivot(int[] A, int lo, int hi) { + + while (lo <= hi) { + + if (lo == hi || A[lo] < A[hi]) + return lo; + + if (1 == hi - lo) + return A[lo] > A[hi] ? hi : lo; + + int mid = (lo + hi) / 2; + if (A[mid - 1] > A[mid] && mid - 1 == lo) + return mid; + if (A[mid - 1] > A[mid] && mid == hi) + return mid; + if (A[mid - 1] > A[mid] && A[mid] < A[mid + 1]) + return mid; + if (A[lo] < A[mid] && A[mid] > A[hi]) + lo = mid + 1; + if (A[lo] > A[mid] && A[mid] < A[hi]) + hi = mid - 1; + } + + return -1; + + } +} diff --git a/My Solutions/SExpressionOfATree.java b/My Solutions/SExpressionOfATree.java new file mode 100644 index 00000000..4a3c8fa6 --- /dev/null +++ b/My Solutions/SExpressionOfATree.java @@ -0,0 +1,23 @@ +public class SExpressionOfATree { + + /** + * @param args + */ + public static void main(String[] args) { + SExpressionOfATree se = new SExpressionOfATree(); + TreeNode a = new TreeNode(1); + a.left = new TreeNode(2); + a.right = new TreeNode(3); + System.out.println(se.buildExpression(a)); + + } + + String buildExpression(TreeNode root) { + if (root == null) { + return ""; + } + return "(" + root.val + buildExpression(root.left) + + buildExpression(root.right) + ")"; + } + +} diff --git a/My Solutions/ScrambleString.java b/My Solutions/ScrambleString.java new file mode 100644 index 00000000..84e540d3 --- /dev/null +++ b/My Solutions/ScrambleString.java @@ -0,0 +1,35 @@ +public class ScrambleString { + + /** + * @param args + */ + public static void main(String[] args) { + ScrambleString ss = new ScrambleString(); + System.out.println(ss.isScramble("abb", "bba")); + } + + public boolean isScramble(String s1, String s2) { + int len = s1.length(); + if (len != s2.length()) + return false; + + // dp[i][j][l]: whether s2.substr(j,j+l) is a scrambled string of + // s1.substr(i,i+l) + boolean[][][] dp = new boolean[len + 1][len + 1][len + 1]; + + for (int l = 1; l <= len; l++) { + 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 d = 1; d < l; d++) { + dp[i][j][l] |= dp[0][0][d] && dp[d][d][l - d]; + dp[i][j][l] |= dp[0][l - d][d] && dp[d][0][l - d]; + } + } + } + } + + return dp[0][0][len]; + } + +} diff --git a/My Solutions/Search2DMatrix.java b/My Solutions/Search2DMatrix.java new file mode 100644 index 00000000..5c392d66 --- /dev/null +++ b/My Solutions/Search2DMatrix.java @@ -0,0 +1,57 @@ +public class Search2DMatrix { + + public static void main(String[] args) { + int[][] matrix = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, + { 23, 30, 34, 50 } }; + System.out.println(searchMatrix(matrix, 10)); + + } + + public static boolean searchMatrix(int[][] matrix, int target) { + + if (matrix == null) { + return false; + } + + int lowRow = 0, highRow = matrix.length - 1; + int lowCol = 0, highCol = matrix[0].length - 1; + + if (matrix[lowRow][0] > target || matrix[highRow][highCol] < target) { + return false; + } + + while (lowRow < highRow) { + int midRow = (lowRow + highRow) / 2; + + if (matrix[midRow][highCol] == target) { + return true; + } + if (matrix[midRow][0] < target) { + lowRow = midRow; + } + if (matrix[midRow][highCol] < target) { + lowRow = midRow + 1; + } + if (matrix[midRow][0] > target) { + highRow = midRow - 1; + } + if (matrix[midRow][highCol] > target) { + highRow = midRow; + } + + } + + while (lowCol <= highCol) { + int midCol = (lowCol + highCol) / 2; + if (matrix[lowRow][midCol] < target) { + lowCol = midCol + 1; + } else if (matrix[lowRow][midCol] > target) { + highCol = midCol - 1; + } else { + return true; + } + } + + return false; + } +} diff --git a/My Solutions/SearchInRotatedArray.java b/My Solutions/SearchInRotatedArray.java new file mode 100644 index 00000000..157d2ea3 --- /dev/null +++ b/My Solutions/SearchInRotatedArray.java @@ -0,0 +1,36 @@ +public class SearchInRotatedArray { + + /** + * @param args + */ + public static void main(String[] args) { + System.out.println(search(new int[] { 3,4,5,6,1,2}, 2)); + } + + public static int search(int[] A, int target) { + + int i = 0, j = A.length - 1; + + while (i <= j) { + int mid = i + (j - i) / 2; + if (A[mid] == target) + return mid; + if (A[i] <= A[mid]) { + if (A[i] <= target && target < A[mid]) { + j = mid - 1; + } else { + i = mid + 1; + } + + } else { + if (A[mid] < target && target <= A[j]) { + i = mid + 1; + } else { + j = mid - 1; + } + } + } + return -1; + } + +} diff --git a/My Solutions/SearchInsertPosition.java b/My Solutions/SearchInsertPosition.java new file mode 100644 index 00000000..450c2299 --- /dev/null +++ b/My Solutions/SearchInsertPosition.java @@ -0,0 +1,33 @@ +public class SearchInsertPosition { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(searchInsert(new int[] { 1, 2, 3 }, 1)); + } + + public static int searchInsert(int[] A, int target) { + int len = A.length; + if (len == 0 || target < A[0]) + return 0; + if (target > A[len - 1]) + return len; + + int i = 0, j = len - 1; + + while (i <= j) { + int mid = i + (j - i) / 2; + if (A[mid] == target) + return mid; + else if (A[mid] > target) + j = mid - 1; + else if (A[mid] < target) + i = mid + 1; + } + + return i; + } + +} \ No newline at end of file diff --git a/My Solutions/SearchRange.java b/My Solutions/SearchRange.java new file mode 100644 index 00000000..ecd16152 --- /dev/null +++ b/My Solutions/SearchRange.java @@ -0,0 +1,43 @@ +public class SearchRange { + + /** + * @param args + */ + public static void main(String[] args) { + SearchRange sr = new SearchRange(); + System.out.print(sr.searchRange(new int[] { 2, 2 }, 1)[0]); + System.out.print(sr.searchRange(new int[] { 2, 2 }, 1)[1]); + } + + public int[] searchRange(int[] A, int target) { + int n = A.length, left = -1, right = -1; + left = findLeft(A, target, 0, n - 1); + right = findRight(A, target, 0, n - 1); + return new int[] { left, right }; + } + + private int findLeft(int A[], int target, int s, int e) { + while (s < e) { + int mid = s + (e - s) / 2; + if (A[mid] < target) { + s = mid + 1; + } else { + e = mid; + } + } + return A[s] == target ? s : -1; + } + + private int findRight(int A[], int target, int s, int e) { + while (s < e) { + int mid = s + (e - s + 1) / 2; + if (A[mid] > target) { + e = mid - 1; + } else { + s = mid; + } + } + return A[e] == target ? e : -1; + } + +} diff --git a/My Solutions/ShortestPalindrome.java b/My Solutions/ShortestPalindrome.java new file mode 100644 index 00000000..4495bb7f --- /dev/null +++ b/My Solutions/ShortestPalindrome.java @@ -0,0 +1,39 @@ +public class ShortestPalindrome { + + public static void main(String[] args) { + ShortestPalindrome sp = new ShortestPalindrome(); + System.out.println(sp.shortestPalindrome("abb")); + } + + public String shortestPalindrome(String s) { + + int len = s.length(); + if (len <= 1) return s; + + + int i = (len - 1) / 2; + for (; i >= 0; i--) { + if (isPalindrome(s, i, i + 1)) { + i = i * 2 + 1; + break; + } + if (isPalindrome(s, i, i)) { + i = i * 2; + break; + } + } + String suffix = s.substring(i + 1); + return new StringBuilder(suffix).reverse().toString() + s; + + } + + private boolean isPalindrome(String s, int i, int j) { + while (i >=0 && j < s.length()) { + if (s.charAt(i) != s.charAt(j)) + return false; + i--; + j++; + } + return i < 0; + } +} diff --git a/My Solutions/SingleNumberII.java b/My Solutions/SingleNumberII.java new file mode 100644 index 00000000..1ec76cf0 --- /dev/null +++ b/My Solutions/SingleNumberII.java @@ -0,0 +1,27 @@ +public class SingleNumberII { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public int singleNumber(int[] A) { + int[] count = new int[32]; + int res = 0; + + for (int i = 0; i < 32; i++) { + for (int j = 0; j < A.length; j++) { + count[i] += (A[j] >> i & 1) == 1 ? 1 : 0; + count[i] %= 3; + } + res |= count[i] << i; + + } + + return res; + } + +} diff --git a/My Solutions/SlidingWindowMaximumGap.java b/My Solutions/SlidingWindowMaximumGap.java new file mode 100644 index 00000000..0b16fbcf --- /dev/null +++ b/My Solutions/SlidingWindowMaximumGap.java @@ -0,0 +1,34 @@ +import java.util.*; + +public class SlidingWindowMaximumGap { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public int maxDiff(int[] A) { + int max = Integer.MIN_VALUE; + + Deque maxQ = new ArrayDeque<>(); + Deque minQ = new ArrayDeque<>(); + + for (int i = 0; i < A.length; i++) { + while (!maxQ.isEmpty() && A[i] > A[maxQ.peekLast()]) { + maxQ.removeLast(); + } + maxQ.push(i); + + while (!minQ.isEmpty() && A[i] < A[minQ.peekLast()]) { + minQ.removeLast(); + } + minQ.push(i); + max = Math.max(maxQ.peekFirst() - minQ.peekFirst(), max); + } + return max; + + } +} diff --git a/My Solutions/SortColor.java b/My Solutions/SortColor.java new file mode 100644 index 00000000..ef1bc463 --- /dev/null +++ b/My Solutions/SortColor.java @@ -0,0 +1,68 @@ +import java.util.Arrays; + +public class SortColor { + + public static void main(String[] args) { + SortColor sc = new SortColor(); + int[] test = { 0 }; + sc.sortColors(test); + } + + public void sortColors(int[] A) { + // countSort(A); + onePassSort(A); + } + + public void onePassSort(int[] A) { + int len = A.length; + int head = 0, tail = len - 1; + int curr = 0; + while (curr <= tail) { + switch (A[curr]) { + case 0: + A[curr++] = A[head]; + A[head++] = 0; + break; + case 1: + curr++; + break; + case 2: + A[curr++] = A[tail]; + A[tail--] = 2; + break; + } + } + } + + public void countSort(int[] A) { + int count0 = 0, count1 = 0, count2 = 0; + for (int i = 0; i < A.length; i++) { + switch (A[i]) { + case 0: + count0++; + break; + case 1: + count1++; + break; + case 2: + count2++; + break; + } + } + + int i = 0; + while (count0-- > 0) { + A[i++] = 0; + } + + while (count1-- > 0) { + A[i++] = 1; + } + + while (count2-- > 0) { + A[i++] = 2; + } + + } + +} \ No newline at end of file diff --git a/My Solutions/SortList.java b/My Solutions/SortList.java new file mode 100644 index 00000000..ab527fdb --- /dev/null +++ b/My Solutions/SortList.java @@ -0,0 +1,58 @@ +public class SortList { + + /** + * @param args + */ + public static void main(String[] args) { + SortList sl = new SortList(); + + ListNode a = new ListNode(2); + a.next = new ListNode(1); + + ListNode result = sl.sortList(a); + return; + + } + + public ListNode sortList(ListNode head) { + + if (head == null || head.next == null) + return head; + + ListNode vHead = new ListNode(-1); + vHead.next = head; + ListNode slow = vHead, fast = vHead; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + ListNode secondHalf = sortList(slow.next); + slow.next = null; + return merge(sortList(head), secondHalf); + + } + + private ListNode merge(ListNode l1, ListNode l2) { + ListNode vHead = new ListNode(-1); + ListNode curr = vHead; + + while (l1 != null && l2 != null) { + if (l1.val < l2.val) { + curr.next = l1; + l1 = l1.next; + } else { + curr.next = l2; + l2 = l2.next; + } + curr = curr.next; + } + + if (l1 == null) { + curr.next = l2; + } else { + curr.next = l1; + } + return vHead.next; + } +} diff --git a/My Solutions/SpiralMatrix.java b/My Solutions/SpiralMatrix.java new file mode 100644 index 00000000..fc5a02ce --- /dev/null +++ b/My Solutions/SpiralMatrix.java @@ -0,0 +1,47 @@ +import java.util.*; + +public class SpiralMatrix { + + /** + * @param args + */ + public static void main(String[] args) { + SpiralMatrix sm = new SpiralMatrix(); + List ret = sm.spiralOrder(new int[][]{{2,3}}); + return; + + } + + public List spiralOrder(int[][] matrix) { + List ret = new LinkedList<>(); + int nRow = matrix.length; + if (nRow == 0) + return ret; + int nCol = matrix[0].length; + int rs = 0, re = nRow - 1, cs = 0, ce = nCol - 1; + + while (ret.size() < nRow * nCol) { + for (int i = cs; i <= ce; i++) { + ret.add(matrix[rs][i]); + } + rs++; + + for (int i = rs; i <= re; i++) { + ret.add(matrix[i][ce]); + } + ce--; + + for (int i = ce; i >= cs; i--) { + ret.add(matrix[re][i]); + } + re--; + + for (int i = re; i >= rs; i--) { + ret.add(matrix[i][cs]); + } + cs++; + } + return ret; + } + +} diff --git a/My Solutions/StringToInteger.java b/My Solutions/StringToInteger.java new file mode 100644 index 00000000..3415a3cb --- /dev/null +++ b/My Solutions/StringToInteger.java @@ -0,0 +1,42 @@ +public class StringToInteger { + + /** + * @param args + */ + public static void main(String[] args) { + atoi("-1"); + } + + public static int atoi(String str) { + int len = str.length(); + if (len == 0) + return 0; + int i = 0; + while (str.charAt(i) == ' ') + i++; + boolean isNeg = false; + if (str.charAt(i) == '-') { + isNeg = true; + i++; // skip the sign + } + if (str.charAt(i) == '+') + i++; + + if (len > 10) { + return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE; + } + + long result = 0; + for (int j = i; j < str.length(); j++) { + result *= 10; + result += (int) (str.charAt(j) - '0'); + if (isNeg && -result < Integer.MIN_VALUE) + return Integer.MIN_VALUE; + else if (!isNeg && result > Integer.MAX_VALUE) + return Integer.MAX_VALUE; + } + + return isNeg ? (int) -result : (int) result; + } + +} diff --git a/My Solutions/Subsets.java b/My Solutions/Subsets.java new file mode 100644 index 00000000..4396801a --- /dev/null +++ b/My Solutions/Subsets.java @@ -0,0 +1,52 @@ +import java.util.*; + +public class Subsets { + + /** + * @param args + */ + public static void main(String[] args) { + subsetsWithDup(new int[] {1,2,2}); + + } + + public List> subsets(int[] S) { + + int len = S.length; + List> ret = new LinkedList<>(); + long n = (long) Math.pow(2, len); + for (long i = 0; i < n; i++) { + List tmp = new LinkedList<>(); + for (int j = 0; j < len; j++) { + if ((i >> j & 1L) == 1) { + tmp.add(S[j]); + } + } + ret.add(tmp); + } + return ret; + } + + public static List> subsetsWithDup(int[] num) { + + Arrays.sort(num); + List> ret = new LinkedList<>(); + List empty = new LinkedList<>(); + ret.add(empty); + int len = num.length, l = 0; + if (len < 1) + return ret; + for (int i = 0; i < len; i++) { + int n = ret.size(); + if (i == 0 || num[i] != num[i - 1]) + l = n; // size of last set without dups + for (int j = n - l; j < n; j++) { + List newList = new LinkedList(ret.get(j)); + newList.add(num[i]); + ret.add(newList); + } + } + return ret; + + } +} diff --git a/My Solutions/SudokuSolver.java b/My Solutions/SudokuSolver.java new file mode 100644 index 00000000..b15b645b --- /dev/null +++ b/My Solutions/SudokuSolver.java @@ -0,0 +1,66 @@ +public class SudokuSolver { + + public static void main(String[] args) { + SudokuSolver ss = new SudokuSolver(); + char[][] myboard = new char[][] { + { '.', '.', '9', '7', '4', '8', '.', '.', '.' }, + { '7', '.', '.', '.', '.', '.', '.', '.', '.' }, + { '.', '2', '.', '1', '.', '9', '.', '.', '.' }, + { '.', '.', '7', '.', '.', '.', '2', '4', '.' }, + { '.', '6', '4', '.', '1', '.', '5', '9', '.' }, + { '.', '9', '8', '.', '.', '.', '3', '.', '.' }, + { '.', '.', '.', '8', '.', '3', '.', '2', '.' }, + { '.', '.', '.', '.', '.', '.', '.', '.', '6' }, + { '.', '.', '.', '2', '7', '5', '9', '.', '.' }, }; + ss.solveSudoku(myboard); + return; + } + + private char[][] board; + + public void solveSudoku(char[][] board) { + this.board = board; + boolean ret = solve(0); + return; + } + + private boolean solve(int loc) { + if (loc == 81) + return true; // all done + int row = loc / 9, col = loc % 9; + if (board[row][col] != '.') + return solve(loc + 1); + for (char c = '1'; c <= '9'; c++) { + board[row][col] = c; + if (isValid(row, col) && solve(loc + 1)) { + return true; + } + board[row][col] = '.'; + } + return false; + } + + private boolean isValid(int row, int col) { + char c = board[row][col]; + + for (int i = 0; i < 9; i++) { + if (i != col && board[row][i] == c) // check row + return false; + + if (i != row && board[i][col] == c) // check col + return false; + } + + // check block + int sx = row / 3 * 3; + int sy = col / 3 * 3; + + for (int i = sx; i < sx + 3; i++) { + for (int j = sy; j < sy + 3; j++) { + if (i != row && j != col && board[i][j] == c) + return false; + } + } + return true; + } +} diff --git a/My Solutions/SummaryOfRanges.java b/My Solutions/SummaryOfRanges.java new file mode 100644 index 00000000..03ddf1de --- /dev/null +++ b/My Solutions/SummaryOfRanges.java @@ -0,0 +1,59 @@ +import java.util.*; + +public class SummaryOfRanges { + + /** + * @param args + */ + public static void main(String[] args) { + SummaryOfRanges cor = new SummaryOfRanges(); + List a = cor.summaryRanges(new int[] { 0, 1 }); + return; + } + + public List summaryRanges(int[] nums) { + + List ret = new LinkedList<>(); + if (nums.length == 0) + return ret; + if (nums.length == 1) { + ret.add(nums[0] + ""); + return ret; + } + + int state = 1, prev = nums[0]; + StringBuilder currStr = new StringBuilder(); + currStr.append(prev); + + for (int i = 1; i < nums.length; i++) { + + int curr = nums[i]; + if (curr == prev) + continue; // repeating numbers + if (state == 1 && curr > prev + 1) { + ret.add(currStr.toString()); + prev = curr; + currStr = new StringBuilder(); + currStr.append(prev); + } + if (state == 1 && curr == prev + 1) { + state = 2; + currStr.append("->"); + } + + if (state == 2 && curr == prev + 1) { + prev = curr; + } + + if (state == 2 && curr > prev + 1) { + currStr.append(prev); + ret.add(currStr.toString()); + prev = curr; + currStr = new StringBuilder(); + currStr.append(prev); + state = 1; + } + } + return ret; + } +} diff --git a/My Solutions/SurroundedRegions.java b/My Solutions/SurroundedRegions.java new file mode 100644 index 00000000..bea901eb --- /dev/null +++ b/My Solutions/SurroundedRegions.java @@ -0,0 +1,101 @@ +import java.util.*; + +public class SurroundedRegions { + + public static void main(String[] args) { + char[][] test = new char[][] { { 'O', 'X', 'O', 'O', 'X', 'X' }, + { 'O', 'X', 'X', 'X', 'O', 'X' }, + { 'X', 'O', 'O', 'X', 'O', 'O' }, + { 'X', 'O', 'X', 'X', 'X', 'X' }, + { 'O', 'O', 'X', 'O', 'X', 'X' }, + { 'X', 'X', 'O', 'O', 'O', 'O' } }; + solve(test); + System.out.print(test); + } + + private static int height; + private static int width; + + public static void solve(char[][] board) { + + if (board == null || board.length == 0) + return; + height = board.length; + width = board[0].length; + if (height == 1 && width == 1) + return; + + // check borders + // from top + for (int i = 0; i < width; i++) { + if (board[0][i] == 'O') { + dfsMark(board, 0, i); + } + } + // from bottom + for (int i = height - 1; i < width; i++) { + if (board[height - 1][i] == 'O') { + dfsMark(board, height - 1, i); + } + } + // from left + for (int i = 0; i < height; i++) { + if (board[i][0] == 'O') { + dfsMark(board, i, 0); + } + } + // from right + for (int i = 0; i < height; i++) { + if (board[width - 1][i] == 'O') { + dfsMark(board, width - 1, i); + } + } + // final round + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { + if (board[i][j] == 'U') + board[i][j] = 'O'; + else if (board[i][j] == 'O') + board[i][j] = 'X'; + } + } + } + + private static void dfsMark(char[][] board, int x, int y) { + + Stack s = new Stack(); + s.push(new Point(x, y)); + + while (!s.isEmpty()) { + Point p = s.pop(); + board[p.x][p.y] = 'U'; + + if (p.x - 1 > 0 && board[p.x - 1][p.y] == 'O') { + s.push(new Point(p.x - 1, p.y)); + } + + if (p.x + 1 < height && board[p.x + 1][p.y] == 'O') { + s.push(new Point(p.x + 1, p.y)); + } + + if (p.y - 1 > 0 && board[p.x][p.y - 1] == 'O') { + s.push(new Point(p.x, p.y - 1)); + } + + if (p.y + 1 < width && board[p.x][p.y + 1] == 'O') { + s.push(new Point(p.x, p.y + 1)); + } + + } + } + + static class Point { + int x; + int y; + + Point(int x, int y) { + this.x = x; + this.y = y; + } + } +} diff --git a/My Solutions/SwapNodeInPairs.java b/My Solutions/SwapNodeInPairs.java new file mode 100644 index 00000000..f5f9688a --- /dev/null +++ b/My Solutions/SwapNodeInPairs.java @@ -0,0 +1,54 @@ +public class SwapNodeInPairs { + + /** + * @param args + */ + public static void main(String[] args) { + ListNode a = new ListNode(1); + a.next = new ListNode(2); + // a.next.next = new ListNode(3); + swapPairs(a); + + } + + public static ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) + return head; + + ListNode oddHead = new ListNode(-1), evenHead = new ListNode(-1); + ListNode odd = oddHead, even = evenHead; + int count = 0; + while (head != null) { + if (count++ % 2 == 0) { + odd.next = head; + odd = odd.next; + } else { + even.next = head; + even = even.next; + } + head = head.next; + } + + odd.next = even.next = null; + ListNode vHead = new ListNode(-1); + ListNode curr = vHead; + odd = oddHead.next; + even = evenHead.next; + for (int i = 0; i < count; i++) { + if (i % 2 == 1) { + curr.next = odd; + odd = odd.next; + } else { + if (even == null) { + curr.next = odd; + break; + } + curr.next = even; + even = even.next; + } + curr = curr.next; + } + return vHead.next; + } + +} diff --git a/My Solutions/ThreeSum.java b/My Solutions/ThreeSum.java new file mode 100644 index 00000000..88d18a00 --- /dev/null +++ b/My Solutions/ThreeSum.java @@ -0,0 +1,42 @@ +import java.util.*; + +public class ThreeSum { + + public static void main(String[] args) { + int[] test = new int[] { -1, 0, 1, 0 }; + + System.out.println(threeSum(test)); + } + + public static List> threeSum(int[] num) { + + List> result = new LinkedList<>(); + int len = num.length; + + if (len < 3) + return result; + Arrays.sort(num); + + for (int i = 0; i < len - 2; i++) { + int j = i + 1, k = len - 1, target = -num[i]; + while (j < k) { + if (num[j] + num[k] == target) { + result.add(Arrays.asList(num[i], num[j], num[k])); // sorted + while (num[j] == num[j + 1]) + j++; + while (num[k] == num[k - 1]) + k--; + j++; + k--; + } else if (num[j] + num[k] < target) { + j++; + } else { + k--; + } + } + } + + return result; + + } +} \ No newline at end of file diff --git a/My Solutions/ThreeSumClosest.java b/My Solutions/ThreeSumClosest.java new file mode 100644 index 00000000..d55e5167 --- /dev/null +++ b/My Solutions/ThreeSumClosest.java @@ -0,0 +1,36 @@ +import java.util.Arrays; + +public class ThreeSumClosest { + + public static void main(String[] args) { + System.out.print(threeSumClosest(new int[] { 1, 1, -1, -1, 3 }, 1)); + + } + + public static int threeSumClosest(int[] num, int target) { + + Arrays.sort(num); + int len = num.length; + int minDiff = Integer.MAX_VALUE; + + for (int i = 0; i < len - 2; i++) { + + int j = i + 1, k = len - 1; + while (j < k) { + int diff = num[i] + num[j] + num[k] - target; + if (Math.abs(diff) < Math.abs(minDiff)) + minDiff = diff; + while (j < k && num[j + 1] == num[j]) + j++; + while (j < k && num[k - 1] == num[k]) + k--; + if (diff > 0) + k--; + else + j++; + } + } + + return target + minDiff; + } +} \ No newline at end of file diff --git a/My Solutions/TrappingRainWater.java b/My Solutions/TrappingRainWater.java new file mode 100644 index 00000000..d1252e0c --- /dev/null +++ b/My Solutions/TrappingRainWater.java @@ -0,0 +1,27 @@ +public class TrappingRainWater { + + /** + * @param args + */ + public static void main(String[] args) { + TrappingRainWater trw = new TrappingRainWater(); + trw.trap(new int[] { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }); + + } + + public int trap(int[] height) { + int i = 0, j = height.length - 1, sum = 0, curr = 0; + while (i < j) { + int min = Math.min(height[i], height[j]); + if (curr < min) + curr = min; + if (height[i] < height[j]) { + sum += curr - height[i++]; + } else { + sum += curr - height[j--]; + } + } + return sum; + } + +} diff --git a/My Solutions/TreeLinkNode.java b/My Solutions/TreeLinkNode.java new file mode 100644 index 00000000..c22308f4 --- /dev/null +++ b/My Solutions/TreeLinkNode.java @@ -0,0 +1,8 @@ +public class TreeLinkNode { + int val; + TreeLinkNode left, right, next; + + TreeLinkNode(int x) { + val = x; + } +} diff --git a/My Solutions/TreeNode.java b/My Solutions/TreeNode.java new file mode 100644 index 00000000..837ec25b --- /dev/null +++ b/My Solutions/TreeNode.java @@ -0,0 +1,9 @@ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/My Solutions/Triangle.java b/My Solutions/Triangle.java new file mode 100644 index 00000000..3404079d --- /dev/null +++ b/My Solutions/Triangle.java @@ -0,0 +1,27 @@ +import java.util.*; + +public class Triangle { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + + public int minimumTotal(List> triangle) { + + int n = triangle.size(); + int[] cost = new int[n + 1]; // for the initial case + + for (int i = n - 1; i > 0; i--) { + List level = triangle.get(i); + for (int j = 0; j < level.size(); j++) { + cost[j] = Math.min(cost[j] + level.get(j), cost[j+1] + level.get(j)); + } + } + + return cost[0]; + } +} diff --git a/My Solutions/TwoSum.java b/My Solutions/TwoSum.java new file mode 100644 index 00000000..6b5474ef --- /dev/null +++ b/My Solutions/TwoSum.java @@ -0,0 +1,20 @@ +import java.util.*; + +public class TwoSum { + public int[] twoSum(int[] numbers, int target) { + Map m = new HashMap(); + for (int i = 0; i < numbers.length; i++) { + m.put(numbers[i], i); + } + + for (int i = 0; i < numbers.length; i++) { + if (m.get(target - numbers[i]) != null + && m.get(target - numbers[i]) < i) { + return new int[] { i, m.get(target - numbers[i]) }; + } + } + + return null; + + } +} diff --git a/My Solutions/UndirectedGraphNode.java b/My Solutions/UndirectedGraphNode.java new file mode 100644 index 00000000..7687f0a8 --- /dev/null +++ b/My Solutions/UndirectedGraphNode.java @@ -0,0 +1,12 @@ +import java.util.ArrayList; +import java.util.List; + +class UndirectedGraphNode { + int label; + List neighbors; + + UndirectedGraphNode(int x) { + label = x; + neighbors = new ArrayList(); + } +}; diff --git a/My Solutions/UniqueBinarySearchTrees.java b/My Solutions/UniqueBinarySearchTrees.java new file mode 100644 index 00000000..4f3b4d9b --- /dev/null +++ b/My Solutions/UniqueBinarySearchTrees.java @@ -0,0 +1,38 @@ +public class UniqueBinarySearchTrees { + + /** + * @param args + */ + public static void main(String[] args) { + UniqueBinarySearchTrees ubst = new UniqueBinarySearchTrees(); + System.out.println(ubst.numTrees(19)); + } + + public int numTrees(int n) { + //return dp(n); + return recursive(1, n); + } + + private int recursive(int start, int end) { + if (start >= end) + return 1; + int sum = 0; + for (int i = start; i <= end; i++) { + int left = recursive(start, i - 1); + int right = recursive(i + 1, end); + sum += left * right; + } + return sum; + } + + private int dp(int n) { + int[] G = new int[n + 1]; + G[0] = G[1] = 1; + for (int i = 2; i <= n; i++) + for (int j = 1; j <= i; j++) + G[i] += G[j - 1] * G[i - j]; // G[j-1] left tree, G[i-j] - right + // tree; + return G[n]; + } + +} diff --git a/My Solutions/UniquePath.java b/My Solutions/UniquePath.java new file mode 100644 index 00000000..bb7165f0 --- /dev/null +++ b/My Solutions/UniquePath.java @@ -0,0 +1,35 @@ +public class UniquePath { + + /** + * @param args + */ + public static void main(String[] args) { + UniquePath up = new UniquePath(); + up.uniquePaths(10, 10); + } + + public int uniquePaths(int m, int n) { + + // essentially it is C(m+n-2, n-1): in total m+n-2 steps, choose n-1 + // step to go downward + if (m < n) + return uniquePaths(n, m); // swap + + int a = m + n - 2; + int b = n - 1; + + double res = 1; + + for (int i = 1; i <= a; i++) + res *= i; + + for (int i = 1; i <= b; i++) + res /= i; + + for (int i = 1; i <= a - b; i++) + res /= i; + + return (int)res; + } + +} diff --git a/My Solutions/WiggleSort.java b/My Solutions/WiggleSort.java new file mode 100644 index 00000000..50453d35 --- /dev/null +++ b/My Solutions/WiggleSort.java @@ -0,0 +1,53 @@ +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Set; +import java.util.Vector; +import java.util.concurrent.ConcurrentLinkedQueue; + +public class WiggleSort { + + /** + * @param args + */ + public static void main(String[] args) { + WiggleSort ws = new WiggleSort(); + int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + int[] result = ws.wiggleSort(nums); + + Vector v = new Vector(); + List l = new LinkedList(); + Set s = new HashSet(); + ConcurrentLinkedQueue clq = new ConcurrentLinkedQueue<>(); + clq.offer(1); + Hashtable ht = new Hashtable<>(); + + HashMap m = new HashMap(); + + return; + } + + public int[] wiggleSort(int[] nums) { + + boolean shouldBeGreater = false; + + for (int i = 0; i < nums.length - 1; i++) { + if (shouldBeGreater && nums[i] < nums[i + 1]) { + int tmp = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = tmp; + } + + if (!shouldBeGreater && nums[i] > nums[i + 1]) { + int tmp = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = tmp; + } + shouldBeGreater = !shouldBeGreater; + } + return nums; + } +} diff --git a/My Solutions/WildcardMatching.java b/My Solutions/WildcardMatching.java new file mode 100644 index 00000000..3d7037ee --- /dev/null +++ b/My Solutions/WildcardMatching.java @@ -0,0 +1,58 @@ +public class WildcardMatching { + + String s, p; + int lenS, lenP; + + public static void main(String[] args) { + WildcardMatching wm = new WildcardMatching(); + System.out.println(wm.recursive("ab", "?*")); + } + + private boolean recursive(String s, String p) { + int lenS = s.length(), lenP = p.length(); + if (lenS > 5 || lenP > 5) + return true; + + if (lenP == 0) + return lenS == 0; + if (lenS == 0) + return p.charAt(0) == '*' && recursive(s, p.substring(1)); + + if (s.charAt(0) == p.charAt(0) || p.charAt(0) == '?') { + return recursive(s.substring(1), p.substring(1)); + } else if (p.charAt(0) == '*') { + for (int i = 0; i <= lenS; i++) { + if (recursive(s.substring(i), p.substring(1))) + return true; + } + return false; + } else + return false; + } + + private boolean iterative(String s, String p) { + int lenS = s.length(), lenP = p.length(); + int i = 0, j = 0; + int lastS = 0, lastP = -1; + + while (i < lenS) { + if (j < lenP && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?')) { + i++; + j++; + } else if (j < lenP && p.charAt(j) == '*') { + lastS = i; + lastP = j; + j++; // first assume match zero, so don't increase i; + } else if (lastP != -1) { // there was a '*' + j = lastP + 1; // next char after '*' + lastS++; // move s forward one letter + i = lastS; + } else + return false; + } + while (j < lenP) + if (p.charAt(j++) != '*') + return false; + return true; + } +} \ No newline at end of file diff --git a/My Solutions/WordDictionary.java b/My Solutions/WordDictionary.java new file mode 100644 index 00000000..4707e3db --- /dev/null +++ b/My Solutions/WordDictionary.java @@ -0,0 +1,64 @@ + +public class WordDictionary { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} + +class DictNode { + private DictNode[] children; + private boolean isWord; + public DictNode() { + children = new DictNode[26]; + } + + public void add(String word) { + int len = word.length(); + DictNode curr = this; + for (int i = 0; i < len; i++) { + int idx = word.charAt(i) - 'a'; + if (curr.children[idx] == null) { + curr.children[idx] = new DictNode(); + } + curr = curr.children[idx]; + } + curr.isWord = true; + } + + public boolean search(String word) { + return searchHelper(this, word); + } + + private boolean searchHelper(DictNode root, String word) { + int len = word.length(); + if (len == 0) return root.isWord; + + char c = word.charAt(0); + int idx = c - 'a'; + + if (c == '.') { + for (int i = 0; i < 26; i++) { + if (root.children[i] != null) { + if (searchHelper(root.children[i], word.substring(1))) + return true; + } + } + } else { + if (root.children[idx] != null) { + return searchHelper(root.children[idx], word.substring(1)); + } + } + return false; + } +} + +// Your WordDictionary object will be instantiated and called as such: +// WordDictionary wordDictionary = new WordDictionary(); +// wordDictionary.addWord("word"); +// wordDictionary.search("pattern"); \ No newline at end of file diff --git a/My Solutions/WordLadder.java b/My Solutions/WordLadder.java new file mode 100644 index 00000000..37879b9f --- /dev/null +++ b/My Solutions/WordLadder.java @@ -0,0 +1,74 @@ +import java.util.*; + +public class WordLadder { + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + + String a = "ab"; + String c = "cd"; + Set dict = new HashSet<>(); + dict.add("ad"); + dict.add("bd"); + dict.add("cd"); + + System.out.println(ladderLength(a, c, dict)); + + } + + public static int ladderLength(String start, String end, Set dict) { + if (start.equals(end)) + return 1; + int dictSize = dict.size(); + + Set visited = new HashSet<>(); + Deque q = new ArrayDeque<>(); + q.add(start); + q.add(""); // as a separator + visited.add(start); + + int nStep = 2; + + while (!q.isEmpty()) { + String curr = q.remove(); + for (int i = 0; i < curr.length(); i++) { + StringBuilder s = new StringBuilder(curr); + for (char c = 'a'; c <= 'z'; c++) { + s.setCharAt(i, c); + String tmp = new String(s); + if (tmp.equals(curr)) + continue; + if (dict.contains(tmp) && !visited.contains(tmp)) { + if (tmp.equals(end)) + return nStep; + else { + visited.add(tmp); + q.add(tmp); + } + } + } + } + + if (!q.isEmpty() && q.peek().length() == 0) { + q.remove(); + nStep++; + q.add(""); // marker element + } + } + return 0; + } + + private static boolean isNeighbor(String a, String b) { + int len = a.length(); + int count = 0; + for (int i = 0; i < len; i++) { + if (a.charAt(i) != b.charAt(i)) + count++; + } + return count == 1 ? true : false; + } + +} diff --git a/My Solutions/WordLadderII.java b/My Solutions/WordLadderII.java new file mode 100644 index 00000000..7f1b6687 --- /dev/null +++ b/My Solutions/WordLadderII.java @@ -0,0 +1,67 @@ +import java.util.*; + +public class WordLadderII { + + /** + * @param args + */ + public static void main(String[] args) { + WordLadderII wl2 = new WordLadderII(); + Set dict = new HashSet<>(); + dict.add("a"); + dict.add("b"); + dict.add("c"); + + List result = wl2.findLadders("a", "c", dict); + return; + } + + int minStep; + List current; + List> ret; + Set visited; + String target; + + public List> findLadders(String start, String end, + Set dict) { + ret = new LinkedList<>(); + if (start.equals(end)) + return ret; + + minStep = -1; + current = new LinkedList<>(); + visited = new HashSet<>(); + target = end; + + current.add(start); + visited.add(start); + findLadder(1); + return ret; + } + + private void findLadder(int n) { + if (minStep != -1 && n > minStep) + return; + String tail = current.get(current.size() - 1); // get the last string + + for (int i = 0; i < current.size(); i++) { + StringBuilder sb = new StringBuilder(tail); + for (char c = 'a'; c <= 'z'; c++) { + sb.setCharAt(i, c); + String neighbor = sb.toString(); + if (neighbor.equals(tail)) + continue; + if (neighbor.equals(target)) { + minStep = n; + ret.add(new ArrayList(current)); + return; + } + visited.add(neighbor); + current.add(neighbor); + findLadder(n + 1); + current.remove(neighbor); + } + } + } + +} diff --git a/My Solutions/WordPattern.java b/My Solutions/WordPattern.java new file mode 100644 index 00000000..d7b5a01a --- /dev/null +++ b/My Solutions/WordPattern.java @@ -0,0 +1,34 @@ +import java.util.*; + +public class WordPattern { + + /** + * @param args + */ + public static void main(String[] args) { + + WordPattern wp = new WordPattern(); + System.out.println(wp.wordPattern("abba", "dog cat cat fish")); + } + + public boolean wordPattern(String pattern, String str) { + int nP = pattern.length(); + String[] ss = str.split(" "); + int nS = ss.length; + if (nP != nS) + return false; + Map map = new HashMap<>(); + + for (int i = 0; i < nP; i++) { + char c = pattern.charAt(i); + if (map.containsKey(c)) { + if (!map.get(c).equals(ss[i])) + return false; + } else { + map.put(c, ss[i]); + } + } + return true; + } + +} diff --git a/My Solutions/WordSearch.java b/My Solutions/WordSearch.java new file mode 100644 index 00000000..f3d86eb0 --- /dev/null +++ b/My Solutions/WordSearch.java @@ -0,0 +1,59 @@ +public class WordSearch { + + /** + * @param args + */ + public static void main(String[] args) { + WordSearch ws = new WordSearch(); + System.out.println(ws.exist(new char[][] { + { 'a', 'b', 'c', 'e' }, + { 's', 'f', 'c', 's' }, + { 'a', 'd', 'e', 'e' } }, "asadeb")); + + } + + String word; + char[][] board; + boolean[][] flag; + int len = 0; + int nRow = 0; + int nCol = 0; + + public boolean exist(char[][] board, String word) { + len = word.length(); + this.word = word; + this.board = board; + nRow = board.length; + if (len == 0) + return true; + if (nRow == 0) + return false; + if (nRow > 0) { + nCol = board[0].length; + if (nRow * nCol < len) + return false; + flag = new boolean[nRow][nCol]; + } + + for (int i = 0; i < nRow; i++) + for (int j = 0; j < nCol; j++) + if (find(1, i, j)) + return true; + return false; + } + + private boolean find(int k, int x, int y) { + if (k == len) + return true; + if (x < 0 || x >= nRow || y < 0 || y >= nCol || flag[x][y] + || word.charAt(k) != board[x][y]) + return false; + flag[x][y] = true; + if (find(k + 1, x - 1, y) || find(k + 1, x + 1, y) + || find(k + 1, x, y - 1) || find(k + 1, x, y + 1)) + return true; + flag[x][y] = false; + return false; + } + +} diff --git a/My Solutions/WorkBreakII.java b/My Solutions/WorkBreakII.java new file mode 100644 index 00000000..9a79bc92 --- /dev/null +++ b/My Solutions/WorkBreakII.java @@ -0,0 +1,65 @@ +import java.util.*; + +public class WorkBreakII { + + /** + * @param args + */ + public static void main(String[] args) { + WorkBreakII wb2 = new WorkBreakII(); + + Set test = new HashSet<>(); + test.add("a"); + + List res = wb2.wordBreak("a", test); + + return; + } + + Map> rMap; // result map + Set imSet; // impossible set + Set dict; + + public List wordBreak(String s, Set dict) { + + // if (s.length() > 100) return null; + + rMap = new HashMap<>(); // result map + imSet = new HashSet<>(); // impossible set + this.dict = dict; + + return helper(s); + } + + private List helper(String s) { + + if (rMap.containsKey(s)) + return rMap.get(s); + if (imSet.contains(s)) + return null; + + List ret = new LinkedList<>(); + + for (int i = 1; i <= s.length(); i++) { + String front = s.substring(0, i); + String end = s.substring(i); + if (dict.contains(front)) { + if (i == s.length()) { + ret.add(front); + } else { + List remainSet = wordBreak(end, dict); + if (remainSet == null) { + imSet.add(end); + return null; + } else { + for (String str : remainSet) { + ret.add(front + " " + str); + } + rMap.put(end, remainSet); + } + } + } + } + return ret; + } +} diff --git a/My Solutions/sqrt.java b/My Solutions/sqrt.java new file mode 100644 index 00000000..6b5c426c --- /dev/null +++ b/My Solutions/sqrt.java @@ -0,0 +1,23 @@ +public class sqrt { + + /** + * @param args + */ + public static void main(String[] args) { + System.out.print(newton(2147395599)); + } + + public static int newton(int x) { + if (x < 2) + return x; + long y = x >> 1; + long dy = (long) (y * y - x); + while (dy > 0){ + y -= (dy - 1) / (y << 1) + 1; + dy = y * y - x; + } + + return (int)y; + } + +}