Wednesday, March 5, 2014

LeetCode: Simplify Path


Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:

  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".

Solution


Not a difficult problem, but caution needs to be exercised.
Clarify:

  1. see ".", stay in the same folder
  2. see ".." go back to previous folder
Use a stack to hold folder names and their relationship




Java Queue in LeetCode Minimum Depth of Binary Tree


Given 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.

Solution:

The problem itself is not difficult at all. I would like to summarize the usage of queue in java.

Unlike Stack<E> which is can be used directly(empty(), peek(), pop(), push(E item), search(Object) 0), Queue<E>  (isEmpty(), add()/offer(), remove()/poll(), peek()/element()) is an interface in java.

Simply use LinkedList<E> because LinkedList has methods to support queue behavior and it implements the Queue interface, so a LinkedList can be used as a Queue implmentation by upcasting a LinkedList to a Queue, i.e., 

Queue<TreeNode> queue = LinkedList<TreeNode>();

For this problem, use BFS and an special node to indicate the end of a level (nullNode). The code passed leetcode with only one try.

The most simple method to solve this problem is using recursion, as follows:

Leetcode: Largest Rectangle in Histogram


Given 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.

Solution:

最容易和直接的解法是穷举法,对于直方图的每一个右边界,穷举所有的左边界。将面积最大的那个值记录下来。时间复杂度为O(n^2). 单纯的穷举在LeetCode上面过大集合时会超时。
优化解法:选择合适的右边界,skip没有意义的右边界。观察发现当height[k+1] >= height[k]时,无论左边界是什么值,选择height[k+1]总会比选择height[k]所形成的面积大。因此,在选择右边界的时候,首先找到一个height[k] > height[k+1 ],然后取k 作为右边界,穷举所有左边界,找最大面积。值得注意的一点是一些特殊情况 such as 所有直方图是升序。此解法可以通过leetcode all test cases.


最后一个解法,时间复杂度为O(n),利用一个stack存储高度递增的下标。这个方法的核心是:不仅选择合适的右边界,同时也选择合适的左边界,skip不必要的边界选择
对于每一个直方图高度,分两种情况。1:当栈空或者当前高度大于栈顶下标所指示的高度时,当前下标入栈。否则,2:当前栈顶出栈,并且用这个下标所指示的高度计算面积。而这个方法为什么只需要一个栈呢?因为当第二种情况时,for循环的循环下标回退,也就让下一次for循环比较当前高度与新的栈顶下标所指示的高度,注意此时的栈顶已经改变由于之前的出栈。


还有一个注意的点就是 width = stack.empty() ? i : i - stack.peek() - 1

Reference: http://blog.csdn.net/abcbc/article/details/8943485
                  http://www.geeksforgeeks.org/largest-rectangle-under-histogram/

Tuesday, March 4, 2014

Create a DLL shared by projects with asp.net and C#

Background

After having finished several projects for Graduate School, I noticed that there are a lot of duplicate code, especially the code for operating the database. The following is a typical code segment for inquiring a table in the database:




My Solution

To reduce the duplicate code, I created a DLL named DatabaseOperation which serves as a middle layer and encapsulates all the details of operating a database. The only thing users need is to provide correct sql and pass the sql to DBOperation. Example code is as follows:

 

The way to create a DLL and use it from a project

In Visual Studio 2012, File->New->Project  Choose Template/Visual C# on the left hand side, then select "Class Library" from all the project types listed at the right hand side.

Add .cs files into the project. Build the project. In the local find, locate a folder with the name "bin", you will find the dll file within the debug folder.

Open the project in VS 2012, open a project, right click on the project full name, choose "Add Reference" and browse the dll file at local drive. The dll will be integrated with the project and be uploaded to the "Bin" folder in the server.

Monday, March 3, 2014

LeetCode: Subset I&II


Given a set of distinct integers, 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,3], a solution is:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]


Solution:

For S=[1,2,3] only two possibilities: A subset contains S[0] or A subset doesn't contain S[0]

Caution should be exercised when using ArrayList

Note1: [] is dealt with separately
Note2: firstly used S[i] = S[i+1]. Wrong. The length of S has not be reduced by 1 thus affects the next recursive computation.
Note3: forgot to new an ArrayList<Integer> object. It's wrongto use ArrayList<Integer> withElement = sol.




public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        
        if(S == null || S.length == 0) return ret;
        
        ret = subsetsRec(S);
        
        ret.add(new ArrayList<Integer>());////////Note1
        
        return ret;
        
    }
    
    
    public ArrayList<ArrayList<Integer>> subsetsRec(int[] S) {
        
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        
        if(S.length==1){
            ArrayList<Integer> element = new ArrayList<Integer>();
            element.add(S[0]);
            ret.add(element);
            return ret;
        }
        
        Arrays.sort(S);
        int curInt = S[0];
        ArrayList<Integer> cur = new ArrayList<Integer>();
        cur.add(curInt);
        ret.add(cur);
        
        int[] nextS = new int[S.length-1];
        for(int i=0; i<S.length-1; i++)
        {
            nextS[i] = S[i+1];/////////////Note2
        }
        
        
        for(ArrayList<Integer> sol : subsetsRec(nextS)){
            ret.add(sol);
            ArrayList<Integer> withElement = new ArrayList<Integer>();/////////Note3
            withElement.addAll(sol);
            withElement.add(0, curInt);
            ret.add(withElement);
        }
    
        return ret;
    }
}  
 

Inspired by the discussion, I came up with the following pretty solution:

set [a,b,c], write the binary numbers of length 3.
000    []
001    [a]
010    [b]
011    [ab]
100    [c]
101    [ac]
110    [bc]
111    [abc]




public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        
                ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
  if(S == null || S.length == 0) return ret;
  
  int len = S.length;
  
  Arrays.sort(S);
  
  for(int i=0; i<Math.pow(2,len); i++){
   ArrayList<Integer> sol = new ArrayList<Integer>();
   
   int n=i;
   int m=0;
   while(n !=0 && m<=len)
   {
    if((n&1) == 1) sol.add(S[m]);
    n=n>>1;
    m++;
   }
   
   ret.add(sol);
  }
        
        return ret;
    }
 





SubsetII

Given 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],
  []
]

Solution:


When adding a subset, see whether a same one has already been contained in the result. Only need to add code at three places to solve this:

         if(!ret.contains(cur))
            ret.add(cur);

LeeCode: Merge Intervals


Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].


Solution:
Caution should be exercised when using customized sort function.

The Key Point: two ways to implement user-defined comparator. Similar rule applies to Collections.sort() and Arrays.sort()

For exampe:


 import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return ((Integer) o2[0]).compareTo(o1[0]);
            }
        });

        System.out.println(Arrays.deepToString(twoDim));
    }
}



Reference: int compare(T ol, T or)
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.


My Solution:


public ArrayList merge(ArrayList intervals) {
        
    if(intervals==null) return intervals;
        
    Collections.sort(intervals, new IntervalComparator());
        
    for(int i=0; i< intervals.size()-1; ){
            
        Interval a = intervals.get(i);
        Interval b = intervals.get(i+1);
            
        if(a.end >= b.start){
            int newEnd = a.end<=b.end? b.end : a.end;
            Interval newIntv = new Interval(a.start, newEnd);
            intervals.remove(i);//removeRange(i, i+1) also works
            intervals.remove(i);//!!!!!intervals.remove(i+1);
            intervals.add(i, newIntv);
        }
        else//no overlap
            i++;
    }
        
    return intervals;
}


class IntervalComparator implements Comparator{
    @Override
    public int compare(Interval a, Interval b){
        if(a.start<b.start)
            return -1;
        if(a.start == b.start&&a.end<b.end)
            return -1;
            
        if(a.start == b.start&&a.end==b.end)
            return 0;
            
        return 1;
    }
    
} 
The Second way to create a new Comparator object by overriding
int compare(....)! Nice~~~~~
 Collections.sort(intervals, new Comparator<Interval>(){
        public int compare(Interval int1, Interval int2) {
            if (int1.start < int2.start) {
                return -1;
            }
            if (int1.start == int2.start && int1.end <= int2.end) {
                return -1;
            }
            return 1;
        }
    });
  

LeetCode: N-Queens I&II

八皇后问题是十九世纪著名数学家高斯于1850年提出的。问题是:在8*8的棋盘上摆放8个皇后,使其不能互相攻击,即任意的两个皇后不能处在同意行,同一列,或同意斜线上。可以把八皇后问题拓展为n皇后问题,即在n*n的棋盘上摆放n个皇后,使其任意两个皇后都不能处于同一行、同一列或同一斜线上。


This is a typical recursive problem.

不难,有几点注意的问题:

1.关于数组的问题
2.容易出错的点:用临时变量 tempForRec 消除下一层递归所带来的影响
3.判断两个点是否在同一斜线上 Math.abs(x1-x2) == Math.abs(y1-y2)
4.有其他节省空间的算法:用一个数组来记录有效位置比如j=A[i] means row i and column j has been placed a queen.

My Solution:


  public ArrayList solveNQueens(int n) {
        
        ArrayList ret = new ArrayList();
        String[] tempResult = new String[n];
        
        if(n<=0) return ret;
        
        findPossibleResultNextRow(n, 0, tempResult, ret);
        
        return ret;
    }
    
    
    void findPossibleResultNextRow(int totalNum, int curRow, String[] tempResult, ArrayList ret){
        
        if(curRow == totalNum){//find a solution
            //String[] oneSolution = tempResult.toArray(); 
            ret.add(tempResult);
            return;
        }
        
        for(int col=0; col<totalNum; col++){
            
            if(isValidPosition(curRow, col, tempResult)){
                
                StringBuilder sb = new StringBuilder(totalNum);
                
                for(int i =0; i<totalNum; i++){
                    
                    if(i==col) 
                        sb.append('Q');
                    else
                        sb.append('.');
                }
                tempResult[curRow] = sb.toString();
                
                String[] tempForRec = new String[totalNum];
                
                for(int j = 0; j<=curRow; j++)
                    tempForRec[j] = tempResult[j];
                
                findPossibleResultNextRow(totalNum, curRow+1, tempForRec, ret);
 
            }
        }
        
    }
    
    boolean isValidPosition(int curRow, int curCol, String[] tempResult){
        
        for(int i =0; i< curRow; i++){
            String str = tempResult[i];
            int col = str.indexOf('Q');
            if(Math.abs(curRow-i)==Math.abs(curCol-col) || curCol == col)// Math.abs(curRow-i)/Math.abs(curCol-col)==1 /by zeor exception
                return false;
        }
        return true;
    
    }