Iterator Interface

Binary Search Tree Iterator

https://leetcode.com/problems/binary-search-tree-iterator/

public class BSTIterator {
    Stack<TreeNode> st=new Stack<TreeNode>();
    TreeNode cur=null;
    
    public BSTIterator(TreeNode root) {
        cur=root;
        while(cur!=null){ 
                st.push(cur);
                cur=cur.left; 
        }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !st.empty();
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode tmp=st.pop(); 
        cur=tmp;
        if (cur.right!=null){
               cur=cur.right;
               while(cur!=null){
                   st.push(cur);
                   cur=cur.left;
               }
        } 
        return tmp.val;   
    }
}

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */

Peeking Iterator
https://leetcode.com/problems/peeking-iterator/

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
    private Iterator<Integer> it;
    boolean flag=false;
    Integer nextElement=null;
	public PeekingIterator(Iterator<Integer> iterator) {
	    // initialize any member here.
	    this.it=iterator;
	}

    // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
	     if (!flag){
	         nextElement=it.next();
	         flag=true; 
	     } 
	     return nextElement;
	     
	}

	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
	     if (flag){
	         flag=false;
	         Integer res=nextElement;
	         nextElement=null;
	         return res;
	     }else{
	         
	         return it.next();
	     }
	}

	@Override
	public boolean hasNext() {
	    return flag||it.hasNext();
	}
}

Zigzag Iterator

Given two 1d vectors, implement an iterator to return their elements alternately.
For example, given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].
Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?
Clarification for the follow up question – Update (2015-09-18):
The “Zigzag” order is not clearly defined and is ambiguous for k > 2 cases. If “Zigzag” does not look right to you, replace “Zigzag” with “Cyclic”. For example, given the following input:
[1,2,3]
[4,5,6,7]
[8,9]
It should return [1,4,8,2,5,9,3,6,7].
[思路]
iterator都放到一个list里, 用一个count循环,

public class zigZagIterator {
	private List<Iterator<Integer>> list=new ArrayList<Iterator<Integer>>();
	int count=0;
	
	public zigZagIterator(Iterator<Integer> v1, Iterator<Integer> v2) {  
		list.add(v1);
		list.add(v2);
	}
	
	public int next(){
		int ret=list.get(count).next();
		if (!list.get(count).hasNext()) list.remove(count);
		else count++;
		if (list.size()>0) count%=list.size();
		return ret;
	}
	public boolean hasNext(){
		return !list.isEmpty();
	}
}
Iterator Interface

Repeated DNA Sequence

public class repeatedDNASequence {
public List findRepeatedDnaSequences(String s) {
List res=new ArrayList();
if (s.length()<10) return res;
HashMap map=new HashMap();
HashMap dict=new HashMap();
dict.put(‘A’, 0);
dict.put(‘C’, 1); dict.put(‘G’, 2); dict.put(‘T’, 3);
for(int i=0;i<s.length()-9;i++){
String tmp=s.substring(i,i+10);
int temp=0;
for(int j=i;j<i+10;j++){
temp= (temp<<2)| dict.get(s.charAt(j));
}
if (map.containsKey(temp)){
if (map.get(temp)==1){
res.add(convertString(temp));
map.put(temp,-1);
}
}else{
map.put(temp,1);
}
}
return res;

}

public String convertString(int x){
StringBuilder sb=new StringBuilder();
for(int i=0;i>2;
}
return sb.toString();
}
}

Repeated DNA Sequence

SQL – Summary

JOIN

INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables

Return nth highest salary from table
+—-+——–+
| Id | Salary |
+—-+——–+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+—-+——–+
Select max(Salary) from Employee emp1
where (N-1)=(select count(DISTINCT(emp2.Salary)) from Employee emp2
where emp2.Salary>emp1.Salary)

Duplicate Email

SELECT Email FROM Person GROUP BY Email HAVING COUNT(*) > 1;
select distinct(p.Email) from Person p, Person q where p.Id!=q.Id and p.Email=q.Email;

Highest Salary In Department
select d.Name Department, e.Name Employee, s.Salary from (
select MAX(e.Salary) Salary, e.DepartmentId from Employee e, Department d where e.DepartmentId=d.Id group by e.DepartmentId
) s, Employee e, Department d where s.Salary=e.Salary and e.DepartmentId=d.Id and e.DepartmentId=s.DepartmentId;

Top N Salary in Depmartemnt
Select d1.Name as Department, e1.Name as Employee, e1.Salary
From Employee e1 ,
Department d1
Where d1.Id=e1.DepartmentId
And (select count(Distinct(Salary)) From Employee e2 where e2.Salary>e1.Salary and e2.DepartmentId=e1.DepartmentId)<N
order by d1.Name ASC, e1.Salary DESC

Delete duplicate Emails
DELETE FROM p1 USING Person p1 INNER JOIN Person p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id;

TO_DAYS — date conversion
TO_DAYS(today)=TO_DAYS(yesterday)+1

SQL – Summary

Word Break I && II

Word Break I
DP, 用boolean array解决

  public boolean wordBreak(String s, Set<String> dict) {
       if (s==null||s.length()==0) return true;
       boolean[] res=new boolean[s.length()+1];
       res[0]=true;
       int maxLen=0;
       for(String w:dict){
          maxLen=Math.max(w.length(),maxLen);
       }
       for(int i=1;i<=s.length();i++){
           
          for(int j=1;j<=maxLen&&j<=i;j++){
             
               res[i]=res[i-j]&&dict.contains(s.substring(i-j,i));
               if (res[i]) break;
          }
       }
       return res[s.length()];
    }

Word Break I
1)和word break I一样,DP,先用boolean array 判断是否存在result
2)再用recursive得出结果

     public List<String> wordBreak(String s, Set<String> wordDict) {
        List<String> res=new ArrayList<String>();
        if (s==null||s.length()==0) return res;
        boolean[] b=new boolean[s.length()+1];
        b[0]=true;
        for(int i=1;i<=s.length();i++){
            for(int j=1;j<=maxLen(wordDict)&&j<=i;j++){
                String tmp=s.substring(i-j,i);
                if (wordDict.contains(tmp)){
                    b[i]=b[i-j];
                }
            }
        }
        if (!b[s.length()]) return res;
        helper(s,wordDict,res,new ArrayList<String>());
        return res;
    }
    
    public int maxLen(Set<String> dict){
        int maxLen=0;
        for(String s:dict){
            maxLen=Math.max(maxLen,s.length());
        }
        return maxLen;
    }
    public void helper(String s,Set<String> wordDict, List<String> res,ArrayList<String> curSol){
        if (s.length()==0){
            String tmp="";
            for(String w:curSol){
                tmp+=" "+w;
            }
            res.add(tmp.trim());
            return;
        }
        int len=Math.min(s.length(), maxLen(wordDict));
        for(int i=1;i<=len;i++){
            String tmp=s.substring(0,i);
            if (wordDict.contains(tmp)){
                curSol.add(tmp);
                helper(s.substring(i),wordDict,res,curSol);
                curSol.remove(curSol.size()-1);
            }
        }
    }
 
Word Break I && II

Simplify Path – lintcode/leetcode

ref: http://www.cnblogs.com/springfor/p/3869666.html
题解:

这是一道简化路径的题,路径简化的依据是:

当遇到“/../”则需要返回上级目录,需检查上级目录是否为空。

当遇到”/./”则表示是本级目录,无需做任何特殊操作。

当遇到”//”则表示是本级目录,无需做任何操作。

当遇到其他字符则表示是文件夹名,无需简化。

当字符串是空或者遇到”/../”,则需要返回一个”/”。

当遇见”/a//b”,则需要简化为”/a/b”。

根据这些要求,我需要两个栈来解决问题。

先将字符串依”/”分割出来,然后检查每个分割出来的字符串。

当字符串为空或者为”.”,不做任何操作。

当字符串不为”..”,则将字符串入栈。

当字符串为”..”, 则弹栈(返回上级目录)。

当对所有分割成的字符串都处理完后,检查第一个栈是否为空,如果栈为空,则证明没有可以重建的目录名,返回”/”即可。

当第一个栈不为空时,这时候我们需要还原path。但是不能弹出栈,因为按照要求栈底元素应该为最先还原的目录path。

例如:原始path是 /a/b/c/,栈里的顺序是:a b c,如果依次弹栈还原的话是:/c/b/a(错误!),正确答案为:/a/b/c

所以这里我应用了第二个栈,先将第一个栈元素弹出入栈到第二个栈,然后再利用第二个栈还原回初始path。

Simplify Path – lintcode/leetcode

Remove Duplicates from Sorted Array I&II, List I&II – Lintcode, leetcode

1. From Sorted Array I

  public int removeDuplicates(int[] nums) {
        if (nums==null || nums.length==0) return 0;
        int pre=0;
        int curr=1;
      for(int i=0;i<nums.length;i++){
          if (nums[i]!=nums[pre]){
              nums[++pre]=nums[i];
          }
      }
        return pre+1;
    }

From Sorted Array II

    public int removeDuplicates(int[] nums) {
         if (nums.length==0){return 0;}
        int prev=2;
        
       
        for(int i=2;i<=nums.length-1;i++){
           if (nums[i]==nums[prev-1]&&nums[i]==nums[prev-2]){ 
               continue;
           }else{
               nums[prev++]=nums[i];
           }
           
        }
       return prev;
    }

2. from Sorted List I

  public static ListNode deleteDuplicates(ListNode head) { 
        if (head==null) return head;
        ListNode prev=head;
        ListNode curr=head.next;
        while(curr!=null){
            if (prev.val==curr.val){
                curr=curr.next;
            }else{
                prev.next=curr;
                prev=prev.next;
           
                curr=curr.next;
            }
        }
        prev.next=null;
        return head;
    }  

from Sorted List II

   public static ListNode deleteDuplicates(ListNode head) {
         if (head==null||head.next==null) return head;
         ListNode prev=new ListNode(0);
         prev.next=head; 
         ListNode curr=prev;
         while(curr.next!=null){
            ListNode n1=curr.next;
            while(n1!=null&&n1.next!=null&&n1.next.val==n1.val){
                n1=n1.next;
            }
            if (n1!=curr.next){
                curr.next=n1.next;
            }else{
                curr=curr.next;
            }
         }
         return prev.next;
         
    }
Remove Duplicates from Sorted Array I&II, List I&II – Lintcode, leetcode

Recover Binary Search Tree — Leetcode

https://leetcode.com/problems/recover-binary-search-tree/

1. need O(n) extra space

  public void recoverTree(TreeNode root) {
        if (root==null) return;
        ArrayList<TreeNode> list=new ArrayList<TreeNode>(); 
        inorder(root, list);
        int i=0;
        int j=list.size()-1;
        while(i<list.size()-1&&list.get(i).val<list.get(i+1).val){
            i++;
        }
        while(j>0&&list.get(j).val>list.get(j-1).val){
            j--;
        }
        TreeNode r1=list.get(i);
        TreeNode r2=list.get(j);
        int tmp=list.get(i).val;
        r1.val=r2.val;
        r2.val=tmp;
        
    }
    
    public void inorder(TreeNode cur,ArrayList<TreeNode> list){
        if (cur==null) return;
        inorder(cur.left,list);
        list.add(cur);
        inorder(cur.right,list); 
    }

2. constant space — need two points
reference: http://blog.sina.com.cn/s/blog_eb52001d0102v1z3.html

  TreeNode first=null;
    TreeNode second=null;
    TreeNode prev=null;
    public void recoverTree(TreeNode root) {
        if (root==null) return; 
        inorder(root);
        int tmp=first.val;
        first.val=second.val;
        second.val=tmp;
        
    }
    
    public void inorder(TreeNode cur ){
        if (cur==null) return;
        inorder(cur.left);
        if (prev!=null&&cur.val<prev.val){
            if (first==null){
                first=prev;
            }
            second=cur;
        }
        prev=cur;
        inorder(cur.right); 
    }
Recover Binary Search Tree — Leetcode

Permutations I && II – lintcode

1. Permutation I

  public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> nums) {
        ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
        if (nums==null||nums.size()==0) return res;
        helper(res,new ArrayList<Integer>(),nums);
        return res;
    }
    
    public void helper( ArrayList<ArrayList<Integer>> res,ArrayList<Integer> sol,ArrayList<Integer> nums){
        if (nums.size()==sol.size()){
            res.add(new ArrayList<Integer>(sol));
            return;
        }
        for(int i=0;i<nums.size();i++){
            if (sol.contains(nums.get(i))){
                continue;
            }
            sol.add(nums.get(i));
            helper(res,sol,nums);
            sol.remove(sol.size()-1); 
        }
    }

Iterative

   public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> nums) {
        ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
        if (nums==null||nums.size()==0) return res;
        
        res.add(new ArrayList<Integer>());
        for(int i=0;i<nums.size();i++){
            ArrayList<ArrayList<Integer>> cur= new ArrayList<ArrayList<Integer>>();
            for(ArrayList<Integer> l:res){
                for(int j=0;j<l.size()+1;j++){
                    ArrayList<Integer> tmp=new ArrayList<Integer>(l);
                    tmp.add(j,nums.get(i));
                    cur.add(tmp);
                }
            }
            res=new ArrayList<ArrayList<Integer>>(cur);
        }  
        return res;
    }

2. Permutation II
1) Iterative

  public ArrayList<ArrayList<Integer>> permuteUnique(ArrayList<Integer> nums) {
         ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
        if (nums==null||nums.size()==0) return res;
        Collections.sort(nums);
        helper(res,new ArrayList<Integer>(),nums);
        return res;
    }
    
    public void helper( ArrayList<ArrayList<Integer>> res,ArrayList<Integer> sol,ArrayList<Integer> nums){
        if (nums.size()==0){
            res.add(new ArrayList<Integer>(sol));
            return;
        }
        for(int i=0;i<nums.size();i++){
            if ((i==0)||(i>0&&nums.get(i)!=nums.get(i-1))){
                int tmp=nums.get(i); 
                sol.add(nums.get(i));
                nums.remove(i);
                helper(res,sol,nums);
                sol.remove(sol.size()-1);
                nums.add(i,tmp);
            }  
        } 
    }

2) Iterative– same as Permutation I, but use hashset to avoid duplication
http://www.mkyong.com/java/how-to-convert-list-to-set-arraylist-to-hastset/

  public ArrayList<ArrayList<Integer>> permuteUnique(ArrayList<Integer> nums) {
        ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
        if (nums==null||nums.size()==0) return res;
        Collections.sort(nums);
        res.add(new ArrayList<Integer>());
        for(int i=0;i<nums.size();i++){
            Set<ArrayList<Integer>> cur= new HashSet<ArrayList<Integer>>();
            for(ArrayList<Integer> l:res){
                for(int j=0;j<l.size()+1;j++){
                    ArrayList<Integer> tmp=new ArrayList<Integer>(l);
                    tmp.add(j,nums.get(i));
                    cur.add(tmp);
                }
            }
            res=new ArrayList<ArrayList<Integer>>(cur);
        }  
        return res;
    }
Permutations I && II – lintcode

merge k lists – lintcode

用priority Queue

 public ListNode mergeKLists(List<ListNode> lists) {  
        if (lists==null|| lists.size()==0) return null;
        ListNode prev=new ListNode(0);
        ListNode res=prev;
        PriorityQueue<ListNode> p=new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
            
            public int compare(ListNode l1,ListNode l2){
                return l1.val - l2.val;
            }
        });
        
        for(ListNode l:lists){
            if (l!=null) p.add(l);
        }
        
        while(!p.isEmpty()){
            ListNode head=p.poll();
            if(head!=null){
              res.next=head;
              res=res.next; 
                head=head.next;
                if (head!=null) p.add(head);
            }
        }
        return prev.next;
    }
merge k lists – lintcode