??xml version="1.0" encoding="utf-8" standalone="yes"?>久久人人爽人人爽人人片av高清,日韩福利二区,亚洲综合无码一区二区http://www.aygfsteel.com/menglee/category/54046.htmlU风U雨Q皆入我?/description>zh-cnTue, 14 Jan 2014 22:53:39 GMTTue, 14 Jan 2014 22:53:39 GMT60[Leetcode] Trapping Rain Waterhttp://www.aygfsteel.com/menglee/archive/2014/01/14/408898.htmlMeng LeeMeng LeeTue, 14 Jan 2014 01:16:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/14/408898.htmlhttp://www.aygfsteel.com/menglee/comments/408898.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/14/408898.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408898.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408898.html法很简单,核心思想是:Ҏ个值A[i]来说Q能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i双的最高的值rightMostHeight[i]。(均不包含自nQ。如果min(left,right) > A[i]Q那么在iq个位置上能trapped的water是min(left,right) – A[i]?/div>
有了q个x好办了Q第一遍从左到双数lleftMostHeightQ第二遍从右到左计算rightMostHeightQ在W二遍的同时可以计出i位置的结果了Q而且q不需要开I间来存放rightMostHeight数组?/div>
旉复杂度是O(n)Q只扫了两遍?br />
 1 public class TrappingRainWater {
 2     public int trap(int A[], int n) {
 3         if (n <= 2)
 4             return 0;
 5 
 6         int[] lmh = new int[n];
 7         lmh[0] = 0;
 8         int maxh = A[0];
 9         for (int i = 1; i < n; ++i) {
10             lmh[i] = maxh;
11             if (maxh < A[i])
12                 maxh = A[i];
13         }
14         int trapped = 0;
15         maxh = A[n - 1];
16         for (int i = n - 2; i > 0; --i) {
17             int left = lmh[i];
18             int right = maxh;
19             int container = Math.min(left, right);
20             if (container > A[i]) {
21                 trapped += container - A[i];
22             }
23             if (maxh < A[i])
24                 maxh = A[i];
25         }
26         return trapped;
27     }
28 }


Meng Lee 2014-01-14 09:16 发表评论
]]>[Leetcode] Permutation Sequencehttp://www.aygfsteel.com/menglee/archive/2014/01/07/408642.htmlMeng LeeMeng LeeTue, 07 Jan 2014 08:06:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/07/408642.htmlhttp://www.aygfsteel.com/menglee/comments/408642.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/07/408642.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408642.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408642.htmlThe set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.

q道题其实有很强的规律可循。首先,n个元素的排列L是n!。在下面的分析中Q让k的范围是0 <= k < n!。(题目代码实际上是1<=k<=n!)
可以看到一个规律,是qnQ个排列中,W一位的元素L(n-1)!一l出现的Q也p如果p = k / (n-1)!Q那么排列的最开始一个元素一定是arr[p]?/div>
q个规律可以cL下去Q在剩余的n-1个元素中逐渐挑选出W二个,W三个,...Q到Wn个元素。程序就l束?/div>
 1 /**
 2  * The set [1,2,3,…,n] contains a total of n! unique permutations.
 3  * 
 4  * By listing and labeling all of the permutations in order, We get the
 5  * following sequence (ie, for n = 3):
 6  * 
 7  * "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation
 8  * sequence.
 9  * 
10  * Note: Given n will be between 1 and 9 inclusive.
11  * 
12  */
13 
14 public class PermutationSequence {
15     public String getPermutation(int n, int k) {
16         char[] arr = new char[n];
17         int pro = 1;
18         for (int i = 0; i < n; ++i) {
19             arr[i] = (char) ('1' + i);
20             pro *= (i + 1);
21         }
22         k = k - 1;
23         k %= pro;
24         pro /= n;
25         for (int i = 0; i < n - 1; ++i) {
26             int selectI = k / pro;
27             k = k % pro;
28             pro /= (n - i - 1);
29             int temp = arr[selectI + i];
30             for (int j = selectI; j > 0; --j) {
31                 arr[i + j] = arr[i + j - 1];
32             }
33             arr[i] = (char) temp;
34         }
35         return String.valueOf(arr);
36     }
37 }
38 


Meng Lee 2014-01-07 16:06 发表评论
]]>[Leetcode] Lowest Common Ancestor of a Binary Search Tree (BST) && Lowest Common Ancestor of Binary Treehttp://www.aygfsteel.com/menglee/archive/2014/01/06/408544.htmlMeng LeeMeng LeeMon, 06 Jan 2014 01:32:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/06/408544.htmlhttp://www.aygfsteel.com/menglee/comments/408544.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/06/408544.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408544.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408544.html
Lowest Common Ancestor of a Binary Search Tree (BST)
Given a binary search tree (BST), find the lowest common ancestor of two given nodes in the BST.
       _______6______
      /              \
   ___2__          ___8__
  /      \        /      \
  0      _4       7       9
        /  \
        3   5
Using the above tree as an example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. 
But how about LCA of nodes 2 and 4? Should it be 6 or 2?
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between 
two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a 
node to be a descendant of itself).” Since a node can be a descendant of itself, the LCA of 2 and 
4 should be 2, according to this definition.
Hint:
A top-down walk from the root of the tree is enough.

 1 public class LowestCommonAncestorOfaBinarySearchTree {
 2     public TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
 3         if (root == null || p == null || q == null)
 4             return null;
 5         if (Math.max(p.val, q.val) < root.val)
 6             return LCA(root.left, p, q);
 7         if (Math.min(p.val, q.val) > root.val)
 8             return LCA(root.right, p, q);
 9         return root;
10     }
11 }


Given a binary tree, find the lowest common ancestor of two given nodes in the tree.
 
 
        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
  6      _2       0       8
         /  \
         7   4
If you are not so sure about the definition of lowest common ancestor (LCA), please refer to my previous 
post: Lowest Common Ancestor of a Binary Search Tree (BST) or the definition of LCA here. Using the tree 
above as an example, the LCA of nodes 5 and 1 is 3. Please note that LCA for nodes 5 and 4 is 5.
 
Hint:
Top-down or bottom-up? Consider both approaches and see which one is more efficient.
 1 public class LowestCommonAncestorOfBinaryTree {
 2     public TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
 3         if (root == null)
 4             return null;
 5         if (root == p || root == q)
 6             return root;
 7         TreeNode left = LCA(root.left, p, q);
 8         TreeNode right = LCA(root.right, p, q);
 9         if (left != null && right != null)
10             return root;
11         return left != null ? left : right;
12     }
13 }


Meng Lee 2014-01-06 09:32 发表评论
]]>[Leetcode] Scramble Stringhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408521.htmlMeng LeeMeng LeeSun, 05 Jan 2014 04:33:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/05/408521.htmlhttp://www.aygfsteel.com/menglee/comments/408521.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408521.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408521.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408521.htmlGiven a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t
We say that "rgeat" is a scrambled string of "great".
Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".
    rgtae
   /    \
  rg    tae
 / \    /  \
r   g  ta  e
       / \
      t   a
We say that "rgtae" is a scrambled string of "great".
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

 1 public class ScrambleString {
 2     public boolean isScramble(String s1, String s2) {
 3         if (s1.length() != s2.length())
 4             return false;
 5         if (s1.equals(s2))
 6             return true;
 7 
 8         int[] A = new int[26];
 9         for (int i = 0; i < s1.length(); i++) {
10             ++A[s1.charAt(i) - 'a'];
11         }
12 
13         for (int j = 0; j < s2.length(); j++) {
14             --A[s2.charAt(j) - 'a'];
15         }
16 
17         for (int k = 0; k < 26; k++) {
18             if (A[k] != 0)
19                 return false;
20         }
21 
22         for (int i = 1; i < s1.length(); i++) {
23             boolean result = isScramble(s1.substring(0, i), s2.substring(0, i))
24                     && isScramble(s1.substring(i), s2.substring(i));
25             result = result
26                     || (isScramble(s1.substring(0, i),
27                             s2.substring(s2.length() - i, s2.length())) && isScramble(
28                             s1.substring(i), s2.substring(0, s2.length() - i)));
29             if (result)
30                 return true;
31         }
32         return false;
33     }
34 }


Meng Lee 2014-01-05 12:33 发表评论
]]>
[Leetcode] Largest Rectangle in Histogramhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408520.htmlMeng LeeMeng LeeSun, 05 Jan 2014 04:31:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/05/408520.htmlhttp://www.aygfsteel.com/menglee/comments/408520.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/05/408520.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408520.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408520.htmlGiven n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given height = [2,1,5,6,2,3],
return 10.

本题需要用栈l护一个高度单调递增的序列下标,如果遇到一个元素比当前栈顶元素高度,那么出栈Qƈ计算当前最大面U。如果栈为空Q需要特D考虑?br />
 1 public class LargestRectangleinHistogram {
 2     public int largestRectangleArea(int[] height) {
 3         Stack<Integer> stack = new Stack<Integer>();
 4         int i = 0;
 5         int maxArea = 0;
 6         int[] h = new int[height.length + 1];
 7         h = Arrays.copyOf(height, height.length + 1);
 8         while (i < h.length) {
 9             if (stack.isEmpty() || h[stack.peek()] <= h[i]) {
10                 stack.push(i++);
11             } else {
12                 int t = stack.pop();
13                 maxArea = Math.max(maxArea, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
14             }
15         }
16         return maxArea;
17     }
18 }


Meng Lee 2014-01-05 12:31 发表评论
]]>
[Leetcode] Binary Tree Inorder Traversalhttp://www.aygfsteel.com/menglee/archive/2014/01/04/408477.htmlMeng LeeMeng LeeSat, 04 Jan 2014 03:17:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/04/408477.htmlhttp://www.aygfsteel.com/menglee/comments/408477.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/04/408477.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408477.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408477.htmlGiven a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

切记p节点初始时指向root.left。代码如下:
 1 public class BinaryTreeInorderTraversal {
 2     public ArrayList<Integer> inorderTraversal(TreeNode root) {
 3         ArrayList<Integer> inOrder = new ArrayList<Integer>();
 4         if (root == null)
 5             return inOrder;
 6         Stack<TreeNode> s = new Stack<TreeNode>();
 7         s.add(root);
 8         TreeNode p = root.left;
 9         while (!s.empty()) {
10             while (p != null) {
11                 s.add(p);
12                 p = p.left;
13             }
14             TreeNode n = s.pop();
15             inOrder.add(n.val);
16             p = n.right;
17             if (p != null) {
18                 s.add(p);
19                 p = p.left;
20             }
21         }
22         return inOrder;
23     }
24 }


Meng Lee 2014-01-04 11:17 发表评论
]]>
[Leetcode] Subsets IIhttp://www.aygfsteel.com/menglee/archive/2014/01/03/408444.htmlMeng LeeMeng LeeFri, 03 Jan 2014 08:40:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/03/408444.htmlhttp://www.aygfsteel.com/menglee/comments/408444.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/03/408444.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408444.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408444.htmlGiven a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

׃元素中可能存在重复,因此较之于Subset的实玎ͼ需要加一些判断。如果碰C重复元素Q只需要在上一ơP代新增的子集的基上再q行q代卛_。实C码如下:
 1 public class SubsetsII {
 2     public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
 3         ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
 4         ArrayList<ArrayList<Integer>> lastLevel = null;
 5         ret.add(new ArrayList<Integer>());
 6         Arrays.sort(num);
 7         for (int i = 0; i < num.length; i++) {
 8             ArrayList<ArrayList<Integer>> tmp = new ArrayList<ArrayList<Integer>>();
 9             ArrayList<ArrayList<Integer>> prev = i == 0 || num[i] != num[i - 1] ? ret : lastLevel;
10             for (ArrayList<Integer> s : prev) {
11                 ArrayList<Integer> newSet = new ArrayList<Integer>(s);
12                 newSet.add(num[i]);
13                 tmp.add(newSet);
14             }
15             ret.addAll(tmp);
16             lastLevel = tmp;
17         }
18         return ret;
19     }
20 }


Meng Lee 2014-01-03 16:40 发表评论
]]>
[Leetcode] Word Ladder IIhttp://www.aygfsteel.com/menglee/archive/2014/01/02/408381.htmlMeng LeeMeng LeeThu, 02 Jan 2014 05:59:00 GMThttp://www.aygfsteel.com/menglee/archive/2014/01/02/408381.htmlhttp://www.aygfsteel.com/menglee/comments/408381.htmlhttp://www.aygfsteel.com/menglee/archive/2014/01/02/408381.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408381.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408381.htmlGiven two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.

q个题目应该是leetcode上比较难的题目了。刚开始我采用了和Word Ladder怼的做法,只是用ArrayList记录了当前变换\径,在小数据的情况下可以AcceptQ但是大数据时。究其原因,是由于ؓ每个当前节点记录变换路径的时候,需要复制之前的ArrayListQ这个时间开销较大?br />其实Q我们可以采用一个Map<String, HashSet<String>>l构Q记录字典单词的每一个前驱,q样我们可以从end反向遍历Q构造出转换路径?br />同时Q我利用了两个ArrayListQ交替记录上一层和下一层的节点Q如果下一层节点ؓI,则不存在路径Q立卌回。如果下一层中出现了endQ证明找C所有的最短\径,停止搜烦开始构造\径。实C码如下:
 1 public class WordLadderII {
 2     private void GeneratePath(Map<String, ArrayList<String>> prevMap,
 3             ArrayList<String> path, String word,
 4             ArrayList<ArrayList<String>> ret) {
 5         if (prevMap.get(word).size() == 0) {
 6             path.add(0, word);
 7             ArrayList<String> curPath = new ArrayList<String>(path);
 8             ret.add(curPath);
 9             path.remove(0);
10             return;
11         }
12 
13         path.add(0, word);
14         for (String pt : prevMap.get(word)) {
15             GeneratePath(prevMap, path, pt, ret);
16         }
17         path.remove(0);
18     }
19 
20     public ArrayList<ArrayList<String>> findLadders(String start, String end,
21             HashSet<String> dict) {
22         ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
23         Map<String, ArrayList<String>> prevMap = new HashMap<String, ArrayList<String>>();
24         dict.add(start);
25         dict.add(end);
26         for (String d : dict) {
27             prevMap.put(d, new ArrayList<String>());
28         }
29         ArrayList<HashSet<String>> candidates = new ArrayList<HashSet<String>>();
30         candidates.add(new HashSet<String>());
31         candidates.add(new HashSet<String>());
32         int current = 0;
33         int previous = 1;
34         candidates.get(current).add(start);
35         while (true) {
36             current = current == 0 ? 1 : 0;
37             previous = previous == 0 ? 1 : 0;
38             for (String d : candidates.get(previous)) {
39                 dict.remove(d);
40             }
41             candidates.get(current).clear();
42             for (String wd : candidates.get(previous)) {
43                 for (int pos = 0; pos < wd.length(); ++pos) {
44                     StringBuffer word = new StringBuffer(wd);
45                     for (int i = 'a'; i <= 'z'; ++i) {
46                         if (wd.charAt(pos) == i) {
47                             continue;
48                         }
49 
50                         word.setCharAt(pos, (char) i);
51 
52                         if (dict.contains(word.toString())) {
53                             prevMap.get(word.toString()).add(wd);
54                             candidates.get(current).add(word.toString());
55                         }
56                     }
57                 }
58             }
59 
60             if (candidates.get(current).size() == 0) {
61                 return ret;
62             }
63             if (candidates.get(current).contains(end)) {
64                 break;
65             }
66         }
67 
68         ArrayList<String> path = new ArrayList<String>();
69         GeneratePath(prevMap, path, end, ret);
70 
71         return ret;
72     }
73 }


Meng Lee 2014-01-02 13:59 发表评论
]]>
[Leetcode] Distinct Subsequences && Edit Distancehttp://www.aygfsteel.com/menglee/archive/2013/12/31/408231.htmlMeng LeeMeng LeeTue, 31 Dec 2013 02:21:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/31/408231.htmlhttp://www.aygfsteel.com/menglee/comments/408231.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/31/408231.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408231.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408231.htmlDistinct Subsequences

Given a string S and a string T, count the number of distinct sub sequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.

q两个题目很怼Q状态方E是f(i, j) = f(i - 1, j) + S[i] == T[j]? f(i - 1, j - 1) : 0 Where f(i, j) is the number of distinct sub-sequence for T[0:j] in S[0:i].
数组初始情况是第一列全部是1Q代表T字符串是IZQS和自己做匚w。实C码如下:
 1 public class DistinctSubsequences {
 2     public int numDistinct(String S, String T) {
 3         int[][] f = new int[S.length() + 1][T.length() + 1];
 4         for (int k = 0; k < S.length(); k++)
 5             f[k][0] = 1;
 6         for (int i = 1; i <= S.length(); i++) {
 7             for (int j = 1; j <= T.length(); j++) {
 8                 if (S.charAt(i - 1) == T.charAt(j - 1)) {
 9                     f[i][j] += f[i - 1][j] + f[i - 1][j - 1];
10                 } else {
11                     f[i][j] += f[i - 1][j];
12                 }
13             }
14         }
15         return f[S.length()][T.length()];
16     }
17 }

Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character

 1 public class EditDistance {
 2     public int minDistance(String word1, String word2) {
 3         if (word1.length() == 0 || word2.length() == 0)
 4             return word1.length() == 0 ? word2.length() : word1.length();
 5         int[][] arr = new int[word2.length() + 1][word1.length() + 1];
 6         for (int i = 0; i <= word1.length(); i++) {
 7             arr[0][i] = i;
 8         }
 9         for (int j = 0; j <= word2.length(); j++) {
10             arr[j][0] = j;
11         }
12         for (int i = 0; i < word1.length(); i++) {
13             for (int j = 0; j < word2.length(); j++) {
14                 if (word1.charAt(i) == word2.charAt(j)) {
15                     arr[j + 1][i + 1] = arr[j][i];
16                 } else {
17                     int dis = Math.min(arr[j][i + 1], arr[j + 1][i]);
18                     arr[j + 1][i + 1] = Math.min(arr[j][i], dis) + 1;
19                 }
20             }
21         }
22         return arr[word2.length()][word1.length()];
23     }
24 }


Meng Lee 2013-12-31 10:21 发表评论
]]>
[Leetcode] 合ƈ区间http://www.aygfsteel.com/menglee/archive/2013/12/26/408066.htmlMeng LeeMeng LeeThu, 26 Dec 2013 06:47:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/26/408066.htmlhttp://www.aygfsteel.com/menglee/comments/408066.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/26/408066.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408066.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408066.html1、给定一l区_表示为[start,end]Q请l出ҎQ将有重叠的区间q行合ƈ。例如:
l定Q[1,3],[2,6],[8,10],[15,18],
合ƈQ[1,6],[8,10],[15,18].
分析Q题目很直观Q首先把区间递增排序Q然后从头合qӞ合ƈ时观察当前区间的start是否于或等于前一个区间的end。代码如下:
 1 public class MergeIntervals {
 2     public class IntervalCmp implements Comparator<Interval> {
 3         @Override
 4         public int compare(Interval i1, Interval i2) {
 5             if (i1.start < i2.start) return -1;
 6             if (i1.start == i2.start && i1.end <= i2.end) return -1;
 7             return 1;
 8         }
 9     }
10     
11     public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
12         ArrayList<Interval> ret = new ArrayList<Interval>();
13         if (intervals.size() == 0) return ret;
14         Interval[] arr = new Interval[intervals.size()];
15         intervals.toArray(arr);
16         Arrays.sort(arr, new IntervalCmp());
17         int start = arr[0].start;
18         int end = arr[0].end;
19         for (int i = 0; i < arr.length; i++) {
20             if (arr[i].start <= end) {
21                 end = Math.max(end, arr[i].end);
22             } else {
23                 ret.add(new Interval(start, end));
24                 start = arr[i].start;
25                 end = arr[i].end;
26             }
27         }
28         ret.add(new Interval(start, end));
29         return ret;
30     }
31 }
2、给定的一l区_区间中的存在的L区间的父区间删除Q例如:
l定Q[1,2] [1,3] [1,4] [5,9] [6,8]
删除后:[1,2] [6,8]
分析Q此题暴力的解法的复杂度为O(N^2)。受上一题排序的启发Q是否有好一点的思\呢?
我们可以按照start递增排序Q若start相等Q则按照end递减排序。考虑排序后的Wi-1 和第i个区_׃start是递增的,所以第i-1个区间的start肯定于{于Wi个区间的start。若Wi-1个区间的end大于{于Wi个区间的endQ则Wi-1个区间就成ؓWi个区间的父区间了?/div>

按照q个思\Q可以试着在排序之后逆向序处理每一个区间。假讑ֽ前处理第i个区_如前所qͼ若第i-1个区间的end大于{于Wi个区间的endQ则Wi-1个区间成为第i个区间的父区_可以保留Wi个区_第i-1个区间删除。由于第i-1个区间是Wi个区间的父区_所以第i-1个区间的父区间也是第i个区间的父区_q种情Ş下删掉第i-1个区_后箋不会漏删Wi-1个区间的父区间。若Wi-1个区间的end于Wi个区间的endQ则可以跌Wi个区_开始处理第i-1个区间。因为按照这U处理的ҎQ在处理到第i个区间时Q该区间不会是Q何区间的父区_若是父区间已l被如前所q的Ҏ删除了)。而且Q在q种情Ş下,后箋可能出现的第i个区间的父区间会是第i-1个区间的父区_所以也不会漏掉Wi个区间的父区间。所以排序之后逆向处理Q只需要O(N)的时_可以解册道问题。整体的旉复杂度ؓO(nlogn)?br />
 1 public class Solution {
 2     public class IntervalCmp implements Comparator<Interval> {
 3         @Override
 4         public int compare(Interval i1, Interval i2) {
 5             if (i1.start < i2.start) return -1;
 6             if (i1.start == i2.start && i1.end >= i2.end) return -1;
 7             return 1;
 8         }
 9     }
10     
11     public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
12         ArrayList<Interval> ret = new ArrayList<Interval>();
13         if (intervals.size() == 0) return ret;
14         Interval[] arr = new Interval[intervals.size()];
15         intervals.toArray(arr);
16         Arrays.sort(arr, new IntervalCmp());
17         int start = arr[arr.length - 1].start;
18         int end = arr[arr.length - 1].end;
19         for (int i = arr.length - 2; i >= 0; i--) {
20             if (arr[i].end < end) {
21                 ret.add(new Interval(start, end));
22                 start = arr[i].start;
23                 end = arr[i].end;
24             }
25         }
26         ret.add(new Interval(start, end));
27         return ret;
28     }
29 }


Meng Lee 2013-12-26 14:47 发表评论
]]>[Leetcode] Trianglehttp://www.aygfsteel.com/menglee/archive/2013/12/25/408006.htmlMeng LeeMeng LeeWed, 25 Dec 2013 03:31:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/25/408006.htmlhttp://www.aygfsteel.com/menglee/comments/408006.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/25/408006.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/408006.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/408006.htmlGiven a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

本题本来的想法是用递归做,实现代码如下Q?br />
 1 public class Solution {
 2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
 3         int row = triangle.size();
 4         return findMinPath(triangle, 0, 0, row);
 5     }
 6 
 7     private int findMinPath(ArrayList<ArrayList<Integer>> triangle, int row,
 8             int col, int totalRow) {
 9         if (row == totalRow - 1) {
10             return triangle.get(row).get(col);
11         } else {
12             return triangle.get(row).get(col) + Math.min(findMinPath(triangle, row + 1, col, totalRow), findMinPath(triangle, row + 1, col + 1, totalRow));
13         }
14     }
15 }
提交之后发现时Q于是考虑到可能是递归的开销问题Q考虑用P代解题。实现如下:
 1 public class Triangle {
 2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
 3         int n = triangle.size() - 1;
 4         int[] path = new int[triangle.size()];
 5         for (int o = 0; o < triangle.get(n).size(); o++) {
 6             path[o] = triangle.get(n).get(o);
 7         }
 8         for (int i = triangle.size() - 2; i >= 0; i--) {
 9             for (int j = 0, t = 0; j < triangle.get(i + 1).size() - 1; j++, t++) {
10                 path[t] = triangle.get(i).get(t)
11                         + Math.min(path[j], path[j + 1]);
12             }
13         }
14         return path[0];
15     }
16 }
q个解法的核心是从叶节点自底向上构造解I间?/div>

Meng Lee 2013-12-25 11:31 发表评论
]]>[Leetcode] Gray Code && Subsetshttp://www.aygfsteel.com/menglee/archive/2013/12/24/407962.htmlMeng LeeMeng LeeTue, 24 Dec 2013 04:06:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/24/407962.htmlhttp://www.aygfsteel.com/menglee/comments/407962.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/24/407962.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407962.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407962.htmlSubsets的解法是从空集开始,依次取每一个元素与子集中的每个集合做ƈ操作。实C码如下:

 1 public class Subsets {
 2     public ArrayList<ArrayList<Integer>> subsets(int[] S) {
 3         Arrays.sort(S);
 4         ArrayList<ArrayList<Integer>> subsets = new ArrayList<ArrayList<Integer>>();
 5         subsets.add(new ArrayList<Integer>());
 6         for (int i = 0; i < S.length; i++) {
 7             int size = subsets.size();
 8             for (int j = 0; j < size; j++) {
 9                 ArrayList<Integer> subset = new ArrayList<Integer>(
10                         subsets.get(j));
11                 subset.add(S[i]);
12                 subsets.add(subset);
13             }
14         }
15         return subsets;
16     }
17 }

Gray Code的算法是初始旉合中只有{0, 1}两个元素Q此后在每个元素的前面附加一?。实C码如下:

 1 public class GrayCode {
 2     public ArrayList<Integer> grayCode(int n) {
 3         ArrayList<Integer> result = new ArrayList<Integer>();
 4         if (n == 0) {
 5             result.add(0);
 6             return result;
 7         }
 8         ;
 9         result.add(0);
10         result.add(1);
11         for (int i = 1; i < n; i++) {
12             ArrayList<Integer> tmp = new ArrayList<Integer>(result);
13             Integer a = 1 << i;
14             for (int k = result.size() - 1; k >= 0; k--) {
15                 tmp.add(result.get(k) + a);
16             }
17             result = tmp;
18         }
19         return result;
20     }
21 }



Meng Lee 2013-12-24 12:06 发表评论
]]>
[Leetcode] Multiply Stringshttp://www.aygfsteel.com/menglee/archive/2013/12/23/407912.htmlMeng LeeMeng LeeMon, 23 Dec 2013 03:59:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/23/407912.htmlhttp://www.aygfsteel.com/menglee/comments/407912.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407912.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407912.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407912.htmlGiven two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.

Ҏ个数字相乘,记录C个数l中Q然后对q个数字的每个元素进行进位检查。主要相乘的时候要分别从两个数字的最后一位开始,q要记录偏移量。实现如下:
 1 public class MultiplyStrings {
 2     public String multiply(String num1, String num2) {
 3         int length1 = num1.length();
 4         int length2 = num2.length();
 5         int[] m = new int[length1 + length2];
 6         for (int k = length2 - 1, offset2 = 0; k >= 0; k--, offset2++) {
 7             for (int i = length1 - 1, offset1 = 0; i >= 0; i--, offset1++) {
 8                 m[length1 + length2 - 1 - offset1 - offset2] += (num1.charAt(i) - '0') * (num2.charAt(k) - '0');
 9             }
10         }
11         int add = 0;
12         for (int t = length1 + length2 - 1; t >= 0; t--) {
13             int value = m[t] + add;
14             add = value / 10;
15             m[t] = value % 10;
16         }
17         StringBuffer sb = new StringBuffer();
18         int w = 0;
19         for (; w < length1 + length2; w++) {
20             if (m[w] != 0) break;
21         }
22         for (int e = w; e < length1 + length2; e++) {
23             sb.append(m[e]);
24         }
25         return sb.length() == 0 ? "0" : sb.toString();
26     }
27 }



Meng Lee 2013-12-23 11:59 发表评论
]]>
[Leetcode] Search for a Rangehttp://www.aygfsteel.com/menglee/archive/2013/12/23/407903.htmlMeng LeeMeng LeeMon, 23 Dec 2013 01:58:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/23/407903.htmlhttp://www.aygfsteel.com/menglee/comments/407903.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407903.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407903.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407903.htmlGiven a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

q个题目有递归和非递归两个解法?br />递归解法Q这个解法比较简z,代码如下Q?br />
 1 public class SearchforaRange {
 2         public int[] searchRange(int[] A, int target) {
 3                 int low = findLow(A, target, 0, A.length - 1);
 4                 int high = findHigh(A, target, 0, A.length - 1);
 5                 int[] ret = new int[2];
 6                 ret[0] = low;
 7                 ret[1] = high;
 8                 return ret;
 9         }
10 
11         private int findLow(int[] A, int target, int l, int r) {
12                 int mid = 0;
13                 int ret = -1;
14                 while (l <= r) {
15                         mid = (l + r) / 2;
16                         if (A[mid] == target) {
17                                 ret = mid;
18                                 int next = findLow(A, target, l, mid - 1);
19                                 if (next != -1) {
20                                         ret = next;
21                                 }
22                                 break;
23                         } else if (A[mid] < target) {
24                                 l = mid + 1;
25                         } else {
26                                 r = mid - 1;
27                         }
28 
29                 }
30                 return ret;
31         }
32 
33         private int findHigh(int[] A, int target, int l, int r) {
34                 int mid = 0;
35                 int ret = -1;
36                 while (l <= r) {
37                         mid = (l + r) / 2;
38                         if (A[mid] == target) {
39                                 ret = mid;
40                                 int next = findHigh(A, target, mid + 1, r);
41                                 if (next != -1) {
42                                         ret = next;
43                                 }
44                                 break;
45                         } else if (A[mid] < target) {
46                                 l = mid + 1;
47                         } else {
48                                 r = mid - 1;
49                         }
50                 }
51                 return ret;
52         }
53 }

非递归解法Q以L左边界ؓ例,q个解法的思\是一直向左进行二分查找,直到扑ֈ最左的目标元素或者最左的目标元素的下一个元素。因此,二分查找l束之后Q需要判断找到的元素到底是目标元素还是他的第一个不满的元素,然后Ҏ情况q回下标。代码实现如下:
 1 public class Solution {
 2     public int[] searchRange(int[] A, int target) {
 3         int left = findLeft(A, target);
 4         int right = findRight(A, target);
 5         return new int[] { left, right };
 6     }
 7 
 8     private int findLeft(int[] A, int target) {
 9         int i = 0, j = A.length - 1;
10         while (i < j) {
11             int mid = (i + j) / 2;
12             if (A[mid] < target) {
13                 i = mid + 1;
14             } else {
15                 j = mid - 1;
16             }
17         }
18         if (A[i] == target) return i;
19         if (i < A.length - 1 && A[i + 1] == target) return i + 1;
20         return -1;
21     }
22 
23     private int findRight(int[] A, int target) {
24         int i = 0, j = A.length - 1;
25         while (i < j) {
26             int mid = (i + j) / 2;
27             if (A[mid] > target) {
28                 j = mid - 1;
29             } else {
30                 i = mid + 1;
31             }
32         }
33         if (j >= 0 && A[j] == target)
34             return j;
35         if (j > 0 && A[j - 1] == target)
36             return j - 1;
37         return -1;
38     }
39 }


Meng Lee 2013-12-23 09:58 发表评论
]]>
[Leetcode] Search Insert Positionhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407896.htmlMeng LeeMeng LeeMon, 23 Dec 2013 01:11:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/23/407896.htmlhttp://www.aygfsteel.com/menglee/comments/407896.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/23/407896.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407896.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407896.htmlGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

本题先对数组q行二分搜烦Q如果找C目标元素p回相应的indexQ如果最l没有找到对应的元素Q则比较最后一个元素与目标元素的大。实C码如下:
 1 public class Solution {
 2     public int searchInsert(int[] A, int target) {
 3         int length = A.length;
 4         if (A.length == 0) return 0;
 5         int i = 0, j = length - 1;
 6         while (i < j) {
 7             int mid = (i + j) / 2;
 8             if (A[mid] == target) return mid;
 9             if (A[mid] < target) {
10                 i = mid + 1;
11             } else {
12                 j = mid - 1;
13             }
14         }
15         return A[i] < target ? i + 1 : i;
16     }
17 }


Meng Lee 2013-12-23 09:11 发表评论
]]>
[Leetcode] Longest Substring Without Repeating Charactershttp://www.aygfsteel.com/menglee/archive/2013/12/22/407877.htmlMeng LeeMeng LeeSun, 22 Dec 2013 12:07:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/22/407877.htmlhttp://www.aygfsteel.com/menglee/comments/407877.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/22/407877.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407877.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407877.htmlGiven a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

本题比较单,需要注意的是左指针右移Ӟ需要将它掠q的元素从map中移除。实C码如下:
 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int length = s.length();
 4         if (length == 0) return 0;
 5         Map<Character, Integer> map = new HashMap<Character, Integer>();
 6         int ret = 0;
 7         int count = 0;
 8         int start = 0;
 9         for (int i = 0; i < length; i++) {
10             char c = s.charAt(i);
11             if (map.containsKey(c)) {
12                 int newStart = map.remove(c).intValue() + 1;
13                 for (int j = start; j < newStart; j++) {
14                     map.remove(s.charAt(j));
15                 }
16                 start = newStart;
17                 ret = ret < count ? count : ret;
18                 count = i - start + 1;
19             } else {
20                 count++;
21             }
22             map.put(c, i);
23         }
24         return ret < count ? count : ret;
25     }
26 }


Meng Lee 2013-12-22 20:07 发表评论
]]>
[Leetcode] Spiral Matrixhttp://www.aygfsteel.com/menglee/archive/2013/12/22/407874.htmlMeng LeeMeng LeeSun, 22 Dec 2013 08:59:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/22/407874.htmlhttp://www.aygfsteel.com/menglee/comments/407874.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/22/407874.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407874.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407874.htmlGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

可以为矩阵设|上下左叛_个边界,每次l着q四个边界打印元素。实C码如下:
 1 public class Solution {
 2     public ArrayList<Integer> spiralOrder(int[][] matrix) {
 3         ArrayList<Integer> ret = new ArrayList<Integer>();
 4         if (matrix.length == 0) return ret;
 5         int upper = 0, bottom = matrix.length - 1;
 6         int left = 0, right = matrix[0].length - 1;
 7         int i = 0, j = 0;
 8         while (true) {
 9             for (i = left; i <= right; i++) {
10                 ret.add(matrix[upper][i]);
11             }
12             if (++upper > bottom) break;
13             for (j = upper; j <= bottom; j++) {
14                 ret.add(matrix[j][right]);
15             }
16             if (--right < left) break;
17             for (i = right; i >= left; i--) {
18                 ret.add(matrix[bottom][i]);
19             }
20             if (--bottom < upper) break;
21             for (j = bottom; j >= upper; j--) {
22                 ret.add(matrix[j][left]);
23             }
24             if (++left > right) break;
25         }
26         return ret;
27     }
28 }


Meng Lee 2013-12-22 16:59 发表评论
]]>
[Leetcode] Longest Valid Parentheseshttp://www.aygfsteel.com/menglee/archive/2013/12/21/407857.htmlMeng LeeMeng LeeSat, 21 Dec 2013 13:28:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/21/407857.htmlhttp://www.aygfsteel.com/menglee/comments/407857.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/21/407857.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407857.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407857.htmlGiven a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

本题的主要思\是标记那些括号是被匚w的?br />我们可以利用一个布数l,如果位置为i的gؓtrueQ则表示Wi个括h被匹配的Q然后我们只需要求q箋为true的元素的个数卛_。实C码如下:
 1 public class LongestValidParentheses {
 2     public int longestValidParentheses(String s) {
 3         int length = s.length();
 4         if (length == 0)
 5             return 0;
 6         int left = 0;
 7         Stack<Integer> indexs = new Stack<Integer>();
 8         boolean[] record = new boolean[length];
 9         for (int i = 0; i < length; i++) {
10             if (s.charAt(i) == '(') {
11                 left++;
12                 indexs.push(i);
13             } else if (left > 0) {
14                 int idx = indexs.pop();
15                 record[idx] = true;
16                 record[i] = true;
17                 left--;
18             }
19         }
20         int ret = 0;
21         int current = 0;
22         for (int k = 0; k < length; k++) {
23             if (record[k]) {
24                 current++;
25             } else {
26                 ret = current > ret ? current : ret;
27                 current = 0;
28             }
29         }
30         return ret > current ? ret : current;
31     }
32 }


Meng Lee 2013-12-21 21:28 发表评论
]]>
[Leetcode] Minimum Depth of Binary Treehttp://www.aygfsteel.com/menglee/archive/2013/12/21/407856.htmlMeng LeeMeng LeeSat, 21 Dec 2013 13:19:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/21/407856.htmlhttp://www.aygfsteel.com/menglee/comments/407856.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/21/407856.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407856.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407856.htmlGiven a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

本题有两U解法?br />W一U解法:对二叉树q行BFSQ由于是按层遍历的,因此如果在某一层发C一个叶子节点,那么找C最深度,此时q回当前深度卛_。实C码如下:
 1 public class Solution {
 2     public int minDepth(TreeNode root) {
 3         if (root == nullreturn 0;
 4         int depth = 1;
 5         int currentLevel = 1;
 6         int nextLevel = 0;
 7         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 8         queue.add(root);
 9         while (!queue.isEmpty()) {
10             TreeNode node = queue.remove();
11             currentLevel--;
12             if (node.left == null && node.right == null) {
13                 return depth;
14             }
15             if (node.left != null) {
16                 queue.add(node.left);
17                 nextLevel++;
18             }
19             if (node.right != null) {
20                 queue.add(node.right);
21                 nextLevel++;
22             }
23             if (currentLevel == 0) {
24                 if (nextLevel != 0) {
25                     depth++;
26                 }
27                 currentLevel = nextLevel;
28                 nextLevel = 0;
29             }
30         }
31         return depth;
32     }
33 }

W二U解法:采用递归的思想Q分别求左右子树的最深度,比较之后q回较小倹{实现如下:
 1 public class MinimumDepthofBinaryTree {
 2     public int minDepth(TreeNode root) {
 3         if (root == null)
 4             return 0;
 5         if (root.left == null && root.right == null)
 6             return 1;
 7         else {
 8             int leftDepth = root.left != null ? minDepth(root.left)
 9                     : Integer.MAX_VALUE;
10             int rightDepth = root.right != null ? minDepth(root.right)
11                     : Integer.MAX_VALUE;
12             return Math.min(leftDepth, rightDepth) + 1;
13         }
14     }
15 }


Meng Lee 2013-12-21 21:19 发表评论
]]>
[Leetcode] Permutations IIhttp://www.aygfsteel.com/menglee/archive/2013/12/20/407814.htmlMeng LeeMeng LeeFri, 20 Dec 2013 07:30:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/20/407814.htmlhttp://www.aygfsteel.com/menglee/comments/407814.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/20/407814.html#Feedback1http://www.aygfsteel.com/menglee/comments/commentRss/407814.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407814.htmlGiven a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

数组全排列题目,基本思想是对每一个字W与后面的字W作交换Q以生成新的序列。ؓ了防止重复,交换之前需要检查之前是否已l和同样的字W串做过交换。代码如下:
 1 public class PermutationsII {
 2     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
 3         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 4         permuteUnique(num, 0, result);
 5         return result;
 6     }
 7 
 8     void permuteUnique(int[] num, int begin,
 9             ArrayList<ArrayList<Integer>> result) {
10         if (begin > num.length - 1) {
11             ArrayList<Integer> item = new ArrayList<Integer>();
12             for (int h = 0; h < num.length; h++) {
13                 item.add(num[h]);
14             }
15             result.add(item);
16         }
17         for (int end = begin; end < num.length; end++) {
18             if (isSwap(num, begin, end)) {
19                 swap(num, begin, end);
20                 permuteUnique(num, begin + 1, result);
21                 swap(num, begin, end);
22             }
23         }
24     }
25 
26     boolean isSwap(int[] arr, int i, int j) {
27         for (int k = i; k < j; k++) {
28             if (arr[k] == arr[j]) {
29                 return false;
30             }
31         }
32         return true;
33     }
34     
35     private void swap(int[] a, int i, int j) {
36         int tmp = a[i];
37         a[i] = a[j];
38         a[j] = tmp;
39     }
40 }


Meng Lee 2013-12-20 15:30 发表评论
]]>
[Leetcode] Unique Binary Search Treeshttp://www.aygfsteel.com/menglee/archive/2013/12/20/407801.htmlMeng LeeMeng LeeFri, 20 Dec 2013 03:58:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/20/407801.htmlhttp://www.aygfsteel.com/menglee/comments/407801.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/20/407801.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407801.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407801.htmlGiven n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
   1          3     3      2      1
    \        /      /       / \       \
     3     2     1       1   3       2
    /     /        \                      \
   2    1          2                     3
本题使用一l线性规划解冟?br />如果n{于0Ӟl果?Q?br />如果n{于1Ӟ只有一个节点,l果?Q?br />如果n{于2Ӟ根节Ҏ两种选择Q结果ؓ2Q?br />如果n大于3Ӟ根节ҎnU选择Q确定根节点后分别计左叛_树的可能情况Q然后相乘就是当前根节点下所有的变ŞU类Q之后在求和卛_。算法实现如下:
 1 public class UniqueBinarySearchTrees {
 2     public int numTrees(int n) {
 3         if (n == 1)
 4             return 1;
 5         if (n == 2)
 6             return 2;
 7         int[] record = new int[n + 1];
 8         record[0] = 1;
 9         record[1] = 1;
10         record[2] = 2;
11         for (int i = 3; i <= n; i++) {
12             int tmp = 0;
13             for (int k = 0; k < i; k++) {
14                 tmp += (record[k] * record[i - k - 1]);
15             }
16             record[i] = tmp;
17         }
18         return record[n];
19     }
20 }


Meng Lee 2013-12-20 11:58 发表评论
]]>
[Leetcode] Palindrome Partitioninghttp://www.aygfsteel.com/menglee/archive/2013/12/19/407778.htmlMeng LeeMeng LeeThu, 19 Dec 2013 09:03:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407778.htmlhttp://www.aygfsteel.com/menglee/comments/407778.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407778.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407778.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407778.htmlGiven a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
    ["aa","b"],
    ["a","a","b"]
]

q个题目考虑用动态规划解题,关键在于构造一个解I间Q确定S的Q意子串S(i, j)是不是对U的。判断标准如下:
1、如果i == jQ则S(i, j)是对U的Q?br />2、如果j - i == 1 && S[i] == S[j]Q则S(i, j)是对U的Q?br />3、如果j - i > 1 && S[i] == S[j] && S(i + 1, j - 1)是对U的Q则S(i, j)也是对称的?br />在构造完q样的解I间后,可以在O(1)旉内判定Q意子串是不是对称的了。算法实现如下:
 1 public class PalindromePartitioning {
 2     public ArrayList<ArrayList<String>> partition(String s) {
 3         ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
 4         ArrayList<String> r = new ArrayList<String>();
 5         int length = s.length();
 6         boolean[][] map = new boolean[length][length];
 7         findPartition(s, 0, ret, r, map);
 8         return ret;
 9     }
10 
11     private void findPartition(String s, int start,
12             ArrayList<ArrayList<String>> ret, ArrayList<String> r,
13             boolean[][] map) {
14         int length = s.length();
15         if (start == length && r.size() != 0) {
16             ArrayList<String> clone = new ArrayList<String>(r);
17             ret.add(clone);
18         } else {
19             for (int j = start; j < length; j++) {
20                 if (start == j
21                         || (j - start > 1 && s.charAt(start) == s.charAt(j) && map[start + 1][j - 1])
22                         || (j - start == 1 && s.charAt(start) == s.charAt(j))) {
23                     map[start][j] = true;
24                     r.add(s.substring(start, j + 1));
25                     findPartition(s, j + 1, ret, r, map);
26                     r.remove(r.size() - 1);
27                 }
28             }
29         }
30     }
31 }


Meng Lee 2013-12-19 17:03 发表评论
]]>
[Leetcode] Clone Graphhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407756.htmlMeng LeeMeng LeeThu, 19 Dec 2013 02:36:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407756.htmlhttp://www.aygfsteel.com/menglee/comments/407756.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407756.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407756.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407756.htmlClone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
2. Second node is labeled as 1. Connect node 1 to node 2.
3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:
       1
      / \
     /   \
    0 --- 2
         / \
         \_/

需要对原图q行BFS搜烦Q其中Set<UndirectedGraphNode> visited对已l访问过的节点进行记录,Map<UndirectedGraphNode, UndirectedGraphNode> map用来记录新老节点的对应关系。代码实现如下:
 1 import java.util.HashMap;
 2 import java.util.HashSet;
 3 import java.util.LinkedList;
 4 import java.util.Map;
 5 import java.util.Queue;
 6 import java.util.Set;
 7 
 8 public class CloneGraph {
 9     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
10         if (node == null)
11             return node;
12         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
13         queue.add(node);
14         Set<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
15         Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
16         while (!queue.isEmpty()) {
17             UndirectedGraphNode n = queue.remove();
18             if (visited.contains(n))
19                 continue;
20             visited.add(n);
21             UndirectedGraphNode clone;
22             if (!map.containsKey(n)) {
23                 clone = new UndirectedGraphNode(n.label);
24                 map.put(n, clone);
25             } else {
26                 clone = map.get(n);
27             }
28             for (UndirectedGraphNode child : n.neighbors) {
29                 queue.add(child);
30                 UndirectedGraphNode cloneChild;
31                 if (!map.containsKey(child)) {
32                     cloneChild = new UndirectedGraphNode(child.label);
33                     map.put(child, cloneChild);
34                 } else {
35                     cloneChild = map.get(child);
36                 }
37                 clone.neighbors.add(cloneChild);
38             }
39         }
40         return map.get(node);
41     }
42 }


Meng Lee 2013-12-19 10:36 发表评论
]]>
[Leetcode] Gas Stationhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407753.htmlMeng LeeMeng LeeThu, 19 Dec 2013 01:29:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407753.htmlhttp://www.aygfsteel.com/menglee/comments/407753.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407753.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407753.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407753.htmlThere are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note: The solution is guaranteed to be unique.

首先Q这个题目要明确如果gas[0] + gas[1] + ... + gas[n] >= cost[0] + cost[1] + .. + cost[n]Q那么这个题目一定有解。因为,Ҏ条gU项可得Q?br />(gas[0] - cost[0]) + (gas[1] - cost[1]) + ... + (gas[n] - cost[n]) >= 0Q由于最l结果大于等于零Q因此一定可以通过加法交换律,得到一个序列,使得中间l果都ؓ非负。因此可以将法实现如下Q?br />
 1 public class GasStation {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         int sum = 0, total = 0, len = gas.length, index = -1;
 4         for (int i = 0; i < len; i++) {
 5             sum += gas[i] - cost[i];
 6             total += gas[i] - cost[i];
 7             if (sum < 0) {
 8                 index = i;
 9                 sum = 0;
10             }
11         }
12         return total >= 0 ? index + 1 : -1;
13     }
14 }


Meng Lee 2013-12-19 09:29 发表评论
]]>
[Leetcode] Word Ladderhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407752.htmlMeng LeeMeng LeeThu, 19 Dec 2013 01:11:00 GMThttp://www.aygfsteel.com/menglee/archive/2013/12/19/407752.htmlhttp://www.aygfsteel.com/menglee/comments/407752.htmlhttp://www.aygfsteel.com/menglee/archive/2013/12/19/407752.html#Feedback0http://www.aygfsteel.com/menglee/comments/commentRss/407752.htmlhttp://www.aygfsteel.com/menglee/services/trackbacks/407752.htmlGiven two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
    1. Only one letter can be changed at a time
    2. Each intermediate word must exist in the dictionary
For example,
Given:
    start = "hit"
    end = "cog"
    dict = ["hot","dot","dog","lot","log"]
    As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
    return its length 5.
Note:
    1. Return 0 if there is no such transformation sequence.
    2. All words have the same length.
    3. All words contain only lowercase alphabetic characters.

W一个思\是遍历dict中的每一个元素,看是不是和当前word只相差一个字W,如果是则作ؓ新的当前wordQ直到当前word与target只相差一个字W。实C码如下:
 1 public class Solution {
 2     public int ladderLength(String start, String end, HashSet<String> dict) {
 3         HashSet<String> trash = new HashSet<String>();
 4         return searchWordLadder(start, end, dict, trash) + 1;
 5     }
 6 
 7     private int searchWordLadder(String start, String end, HashSet<String> dict, HashSet<String> trash) {
 8         if (stringDiff(start, end) == 1) return 1;
 9         if (dict.size() == trash.size()) return 0;
10         int steps = Integer.MAX_VALUE;
11         for (String word : dict) {
12             if (!trash.contains(word) && stringDiff(start, word) == 1) {
13                 trash.add(word);
14                 int lt = searchWordLadder(word, end, dict, trash);
15                 if (lt != 0 && lt < steps) {
16                     steps = lt;
17                 }
18                 trash.remove(word);
19             }
20         }
21         return steps == Integer.MAX_VALUE ? 0 : steps + 1;
22     }
23     
24     private int stringDiff(String s1, String s2) {
25         int diff = 0;
26         int length = s1.length();
27         for (int i = 0; i < length; i++) {
28             if (s1.charAt(i) != s2.charAt(i)) {
29                 diff++;
30             }
31         }
32         return diff;
33     }
34 }
q个法可以通过数据测试,但是在大数据下报时错误。主要问题是法复杂度较高,׃dict中的单词是ؕ序的Q因此最坏情况下需要遍历所有可能的转换路径才能做出判断?br />改变思\Q其实可以通过trie树的BFS搜烦获得l果Q由于BFS是分层遍历的Q因此找C个解之后可以马上返回,复杂度是O(N)QN是原单词的长度。实C码如下:
 1 public class WordLadder {
 2     public int ladderLength(String start, String end, HashSet<String> dict) {
 3         if (dict.size() == 0)
 4             return 0;
 5         int currentLevel = 1;
 6         int nextLevel = 0;
 7         int step = 1;
 8         boolean found = false;
 9         Queue<String> st = new LinkedList<String>();
10         HashSet<String> visited = new HashSet<String>();
11         st.add(start);
12         while (!st.isEmpty()) {
13             String s = st.remove();
14             currentLevel--;
15             if (stringDiff(s, end) == 1) {
16                 found = true;
17                 step++;
18                 break;
19             } else {
20                 int length = s.length();
21                 StringBuffer sb = new StringBuffer(s);
22                 for (int i = 0; i < length; i++) {
23                     for (int j = 0; j < 26; j++) {
24                         char c = sb.charAt(i);
25                         sb.setCharAt(i, (char) ('a' + j));
26                         if (dict.contains(sb.toString())
27                                 && !visited.contains(sb.toString())) {
28                             nextLevel++;
29                             st.add(sb.toString());
30                             visited.add(sb.toString());
31                         }
32                         sb.setCharAt(i, c);
33                     }
34                 }
35             }
36             if (currentLevel == 0) {
37                 currentLevel = nextLevel;
38                 nextLevel = 0;
39                 step++;
40             }
41         }
42         return found ? step : 0;
43     }
44 
45     private int stringDiff(String s1, String s2) {
46         int diff = 0;
47         int length = s1.length();
48         for (int i = 0; i < length; i++) {
49             if (s1.charAt(i) != s2.charAt(i)) {
50                 diff++;
51             }
52         }
53         return diff;
54     }
55 }
其中利用了队列对trie树进行BFS?/div>

Meng Lee 2013-12-19 09:11 发表评论
]]> վ֩ģ壺 ͭ| ʲ| | | | Ϫ| | | | | | Ͽ| | | | Դ| º| | DZɽ| | | Ԫı| | | ¸| ¡| | °| | Ȩ| ׯ| | ̫ԭ| | | | ͼ| Դ| | | ƽ|