博文

目前显示的是 七月, 2018的博文

538. Convert BST to Greater Tree

Problem: Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13 Analysis: Reverse traversal from right to root to left. Solution: 1 2 3 4 5 6 7 8 9 10 11 12 class Solution { int sum = 0; public TreeNode convertBST(TreeNode root) { if (root == null ) return null ; convertBST(root.right); int val = root.val; root.val += sum; sum += val; convertBST(root.left); return root; } }

536. Construct Binary Tree from String

Problem: You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure. You always start to construct the  left  child node of the parent first if it exists. Example: Input: "4(2(3)(1))(6(5))" Output: return the tree root node representing the following tree: 4 / \ 2 6 / \ / 3 1 5 Note: There will only be  '(' ,  ')' ,  '-'  and  '0'  ~  '9'  in the input string. An empty tree is represented by  ""  instead of  "()" . Analysis: Partition string to get the correct string for subtree. The above example can be partition to root: 4, left: 2(3)(1), right 6(5).  Solution: class Solution { p...

516. Longest Palindromic Subsequence

Problem: Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. Example 1: Input: "bbbab" Output: 4 One possible longest palindromic subsequence is "bbbb". Example 2: Input: "cbbd" Output: 2 One possible longest palindromic subsequence is "bb". Analysis: dp[i][j] mean longest Palindromic  subsequence from index i to j in s. Solution: The reason i starts from len - 1 is that dp[i][j] depends on dp[i + 1][j - 1]. So we need to calc i + 1 and j - 1 first.  1: class Solution { 2: public int longestPalindromeSubseq(String s) { 3: int len = s.length(); 4: int[][] dp = new int[len][len]; 5: for (int i = len - 1; i >= 0; i--) { 6: dp[i][i] = 1; 7: for (int j = i + 1; j < len; j++) { 8: if (s.charAt(i) == s.charAt(j)) 9: ...

508. Most Frequent Subtree Sum

Problem: Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order. Examples 1 Input: 5 / \ 2 -3 return [2, -3, 4], since all the values happen only once, return all of them in any order. Examples 2 Input: 5 / \ 2 -5 return [2], since 2 happens twice, however -5 only occur once. Note:  You may assume the sum of values in any subtree is in the range of 32-bit signed integer. Analysis: Very straight forward divide and conquer. Use a map to record the frequency of sum. Mean while, use keep updating the most occurrence.  Solution: 1: class Solution { 2: int max = 0; 3: public int[] findFrequentTreeSum(TreeNode root) { 4: Map<Integ...

459. Repeated Substring Pattern

Problem: Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: "abab" Output: True Explanation: It's the substring "ab" twice. Example 2: Input: "aba" Output: False Example 3: Input: "abcabcabcabc" Output: True Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) Analysis: The qualified substring must start from index 0. And its length <= s.length/2. So we find all candidate substrings and test whether they can fit s. Solution: class Solution { public boolean repeatedSubstringPattern ( String s ) { if ( s = = null | | s . length ( ) = = 0 ) return false ; int len = s . length (...

396. Rotate Function

Problem: Given an array of integers  A  and let  n  to be its length. Assume  B k  to be an array obtained by rotating the array  A   k  positions clock-wise, we define a "rotation function"  F  on  A  as follow: F(k) = 0 * B k [0] + 1 * B k [1] + ... + (n-1) * B k [n-1] . Calculate the maximum value of  F(0), F(1), ..., F(n-1) . Note: n  is guaranteed to be less than 10 5 . Analysis: We can convert each number to A,B,C,D, then we get F(0) = 0A + 1B + 2C +3D F(1) = 0D + 1A + 2B +3C F(2) = 0C + 1D + 2A +3B F(3) = 0B + 1C + 2D +3A From there we can conclude that F(1) = F(0) + sum - 4D F(2) = F(1) + sum - 4C F(3) = F(2) + sum - 4B then  F(i) = F(i-1) + sum - n*A[n-i] http://www.cnblogs.com/grandyang/p/5869791.html Solution: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public int maxRotateFunction ( int [] A ) { int f = 0 , su...

387. First Unique Character in a String

Problem: Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Analysis: The idea is two pass. First pass count currency in map. Second path, find the first count == 1's char in map. Solution: class Solution { public int firstUniqChar ( String s ) { if ( s = = null | | s . length ( ) = = 0 ) return - 1 ; int res = 0 ; Set < Character > checkSet = new HashSet < > ( ) ; Set < Character > dupSet = new HashSet < > ( ) ; for ( char c : s . toCharArray ( ) ) { if ( ! checkSet . add ( c ) ) { dupSet . add ( c ) ; } } for ( int i = 0 ; i < s . length ( ) ; i + + ) { if ( ! dupSet . contains ( s . charAt ( i ) ) ) return i ; } return - 1 ; } }

449. Serialize and Deserialize BST

Problem: Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a  binary search tree . There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible. Analysis: This problem needs to encode as compact as possible so that "null" should be avoided. We use recursive preorder. While desalinizing, use lower bound and uppder bound to decide the legitimacy of current value. Converting data to queue, to reduce remove complexity to constant.  Similar problem 98. Validate Binary Search Tree W...

776. Split BST

图片
Problem: Given a Binary Search Tree (BST) with root node  root , and a target value  V , split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value.  It's not necessarily the case that the tree contains a node with value  V . Additionally, most of the structure of the original tree should remain.  Formally, for any child C with parent P in the original tree, if they are both in the same subtree after the split, then node C should still have the parent P. You should output the root TreeNode of both subtrees after splitting, in any order. Example 1: Input: root = [4,2,6,1,3,5,7], V = 2 Output: [[2,1],[4,3,6,null,null,5,7]] Explanation: Note that root, output[0], and output[1] are TreeNode objects, not arrays. The given tree [4,2,6,1,3,5,7] is represented by the following diagram: 4 / \ ...

450. Delete Node in a BST

Problem: Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note:  Time complexity should be O(height of tree). Example: root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7 Analysis: When we found the target node, we need to use the smallest node on its right branch to replace it. Then we need to call deleteNode again to delete the smallest node. Solution: class Solution { public TreeNode deleteNode(TreeNode root, int key) { ...

865. Smallest Subtree with all the Deepest Nodes

图片
Problem: Given a binary tree rooted at  root , the  depth  of each node is the shortest distance to the root. A node is  deepest  if it has the largest depth possible among any node in the  entire tree . The subtree of a node is that node, plus the set of all descendants of that node. Return the node with the largest depth such that it contains all the deepest nodes in its subtree. Example 1: Input: [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes colored in blue are the deepest nodes of the tree. The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree. The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2. Both the input and output have TreeNode type. Analysis: Very similar to LCA. Use post order divide and conquer approach. Depth is the standard to decide return. Use a result ob...

518. Coin Change 2

Problem: You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. Note:  You can assume that 0 <= amount <= 5000 1 <= coin <= 5000 the number of coins is less than 500 the answer is guaranteed to fit into signed 32-bit integer Example 1: Input: amount = 5, coins = [1, 2, 5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 Analysis: State dp[i][j], combination if 0~i coins to make up amount j. Transition: if not use i, we look at dp[i - 1][j]                   if use i, we look at dp[i][j - coins[i - 1]], since coin i can be used infinite times. If only use i once, we can treat dp[i][j - coins[i - 1]] not use i. It's easier to under stand with 1D dp array implementation. dp[i] += dp...

322. Coin Change

Problem: You are given coins of different denominations and a total amount of money  amount . Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return  -1 . Example 1: Input: coins = [1, 2, 5] , amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2] , amount = 3 Output: -1 Note : You may assume that you have an infinite number of each kind of coin. Analysis: State dp[i]: How many coins to make up amount i. Transition: current amount is larger than current coin, dp[i] = min(ap[i], dp[i - coins[j]]. For instance the amount is 11, dp[10] = 2, the coin with value 1 can make up 11 after 10, So we add 1 to dp[10]. Solution: Initialize dp to amount + 1 is to make sure prev amount, i - coins[j], has been fill. Take [2], 3 as an example. if we set dp[3] to dp[3 - 2] + 1, then dp[1] is not possible. The amount + 1 is a...

791. Custom Sort String

Problem:  and  T  are strings composed of lowercase letters. In  S , no letter occurs more than once. S  was sorted in some custom order previously. We want to permute the characters of  T  so that they match the order that  S  was sorted. More specifically, if  x  occurs before  y  in  S , then  x  should occur before  y  in the returned string. Return any permutation of  T  (as a string) that satisfies this property. Example : Input: S = "cba" T = "abcd" Output: "cbad" Explanation: "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs. Note: S  has length at most  26 , and no character is repeated in  S . T  has length at most  200 . S  and  T  consist of lowercas...

Merge Sort

图片
Analysis : First divide the array (red) until reaches single number. Then starting merge(green). Need a temp array to store the sorted elements while merging.  Solution : If start  == end, then the first mergeSort, start to mid, will fell into infinite recursive call.  public class Solution { /** * @param A: an integer array * @return : nothing */ public void sortIntegers2 ( int [] A ) { // write your code here mergeSort( A , new int [ A . length], 0 , A . length - 1 ); } private void mergeSort ( int [] A , int [] temp, int start, int end) { if (start >= end) { return ; } int mid = start + (end - start) / 2 ; mergeSort( A , temp, start, mid); mergeSort( A , temp, mid + 1 , end); merge( A , temp, start, end, mid); } private void merge ( int [] A , int [] temp, int start, int end, int mid) { int p1 = start, p2 = mid + 1 , p = s...