Monday, May 30, 2016

一切move on

没事,给自己几个关于cs career 的目标
1. leetcode
2. system design
3. aws certificate

Thursday, March 24, 2016

非常不开心

我忍不住了,在这里我做的根本就是没用功。。。杀虫用牛刀。。。 我要忍着,要发泄就这里发泄。争取加速换工作

Wednesday, March 2, 2016

总结03.02

1. 之前 有一些烦恼,不应该庸人自扰,什么事是对的 什么事是错的 要清楚,
不能让emotion和冲动战胜理智。要忍和斩断不好的念头。
2. 工作里面 要耐心听讲和不要太agressive, 要感恩别人对自己的帮助 和 耐心

Tuesday, January 12, 2016

[leetcode]Find Minimum in Rotated Sorted Array II

这种题off by one error太容易出了.. 到目前为止除了仔细检查和写好run code找error和记code之外没找到好办法
public class Solution {
    public int findMin(int[] nums) {
        int left = 0;
        int right = nums.length-1;
        while (left < right){
         int mid = (left+right)/2;
            if (nums[right] > nums[mid]){
          right = mid;
         }else if (nums[right] < nums[mid]){
          left = mid+1;
         }else{
          right--;
         }
        }
        return nums[left];
    }
}

Sunday, December 27, 2015

[leetcode]Count of Smaller Numbers After Self



用BST加count就可以解决
public class Solution {
    public List<Integer> countSmaller(int[] nums) {
        LinkedList<Integer> result = new LinkedList<Integer>();
        BinarySearchTree tree = new BinarySearchTree();
        for(int i = nums.length-1; i >= 0; i--){
            result.addFirst(tree.add(nums[i]));
        }
        return result;
    }
}

class BinarySearchTree{
    BSTNode root;
    int add(int value){
        BSTNode visit = root;
        int count = 0;
        if (root == null) root = new BSTNode(value);

        while (visit != null){
            if (visit.value == value){
                visit.dupCount++;
                count += visit.leftCount;
                break;
            }else if (visit.value < value){
                count += (visit.dupCount+visit.leftCount);
                if (visit.right == null){
                    visit.right = new BSTNode(value);
                    break;
                }
                visit = visit.right;
            }else{
                visit.leftCount++;  
                if (visit.left == null){
                    visit.left = new BSTNode(value);
                    break;
                }
                visit = visit.left;
            }
        }
        return count;
    }
}

class BSTNode{
    int dupCount = 1;
    int leftCount;
    int value;
    BSTNode left, right;
    BSTNode(int value){
        this.value = value;
    }
}

Thursday, December 24, 2015

[leetcode] Kth Largest Element in an Array

用Quick Select...其实可以在原array上修改...不过可能code会复杂点。。 直接straight forward 建立新array做
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public int findKthLargest(int[] nums, int k) {
        List<Integer> numsList = new LinkedList<Integer>();
        for (int i = 0; i < nums.length; i++) numsList.add(nums[i]);
        return findKthRec(numsList, k);
    }
    
    private int findKthRec(List<Integer> nums, int k){
        int pivot = nums.get(0);
        int numPivot = 0;
        LinkedList<Integer> left = new LinkedList<Integer>();
        LinkedList<Integer> right = new LinkedList<Integer>();
        while (!nums.isEmpty()){
            int current = nums.remove(0);
            if (current < pivot) right.add(current);
            else if (current > pivot) left.add(current);
            else numPivot++;
        }
        if (left.size() >= k) return findKthRec(left, k);
        else if (left.size()+numPivot >= k) return pivot;
        return findKthRec(right, k-left.size()-numPivot);
    }
}

Wednesday, December 23, 2015

[leetcode]Different Ways to add parentheses

divide and conquer, 总是分成两半...
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        if (input.equals("")) return new LinkedList<Integer>();
        String operand = "";
        List<Integer> result = new LinkedList<Integer>();
        for (int i = 0; i < input.length(); i++){
            if (!Character.isDigit(input.charAt(i))){
                List<Integer> rightSide = diffWaysToCompute(input.substring(i+1));
                List<Integer> leftSide = diffWaysToCompute(input.substring(0, i));
                char operator = input.charAt(i);
                for (Integer left:leftSide){
                    for (Integer right:rightSide){
                        result.add(eval(operator, left, right));
                    }
                }
            }else{
                operand+=input.charAt(i);
            }
        }
        if (result.size() == 0) result.add(Integer.valueOf(operand));
        return result;
    }
    
    int eval(char operator, int operand1, int operand2){
        if (operator == '*') return operand1*operand2;
        else if (operator == '+') return operand1+operand2;
        return operand1-operand2;
    }
}

Tuesday, December 22, 2015

[leetcode]Search a 2D Matrix II

不知是否最优 。。。 从右上角开始搜 大于 向右走 小于向下走
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }
        int row = 0;
        int col = matrix[0].length-1;
        while (row >= 0 && row < matrix.length 
              && col >= 0 && col < matrix[0].length){
            if (matrix[row][col] == target) return true;
            if (matrix[row][col] > target) col--;
            else row++;
        }
        return false;
    }
}

[leetcode] Word Ladder

直接BFS..... 有一处搞了很久 发现原来return是转换过程有多少个word... 而不是换了多少个字母
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Solution {
    public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
   HashSet<String> notVisited = new HashSet<String>(wordList);
   boolean found = false;
   HashSet<String> nextLevel = new HashSet<String>();
   HashSet<String> curLevel = new HashSet<String>();
   curLevel.add(beginWord);
   notVisited.remove(beginWord);
   int level = 1;
   while (!found && !curLevel.isEmpty()){
       if (curLevel.contains(endWord)){
           found = true;
       }else{
           level++;
       }
    for (String cur:curLevel){
     getNextWords(nextLevel, notVisited, cur);
    }
    HashSet<String> inter = nextLevel;
    nextLevel = curLevel;
    curLevel = inter;
    nextLevel.clear();
   }       
        
   return found?level:0;
    }

    public void getNextWords(HashSet<String> nextWord, HashSet<String>notVisited, String current){
     char []possible = current.toCharArray();
     for (int i = 0; i < possible.length; i++){
      char origin = possible[i];
      for (char a = 'a'; a <= 'z'; a++){
       if (a != origin){
        possible[i] = a;
        String temp = String.valueOf(possible);
        if (notVisited.contains(temp)){
            nextWord.add(temp);
            notVisited.remove(temp);
        }
       }
      }
      possible[i] = origin;
     }
    }
}

[leetcode]Word Ladder II

这是条难题(base on time and memory limit) 大概思路就是记录每个字的parents.. 还有用hashset来装next level这样可以避免重复 当整个next level都生成完毕之后...就可以把notVisited里面的next level word 去掉 一举两得..既可以避免重复visit又可以满足同一个word有multiple parents的情况... **有个地方就是注意同样字母的时候 不应该算进possible
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class Solution {
 List<List<String>> result = new ArrayList<List<String>>();
    public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) {
   HashMap<String, List<String>> parents = new HashMap<String, List<String>>();
   HashSet<String> notVisited = new HashSet<String>(wordList);
   
   boolean found = false;
   HashSet<String> nextLevel = new HashSet<String>();
   HashSet<String> curLevel = new HashSet<String>();
   curLevel.add(beginWord);
   notVisited.remove(beginWord);
   while (!found && !curLevel.isEmpty()){
    for (String cur:curLevel){
     getNextWords(parents, nextLevel, notVisited, cur);
    }

    for (String next:nextLevel){
     notVisited.remove(next);
    }

    if (nextLevel.contains(endWord)) found = true;
    HashSet<String> inter = nextLevel;
    nextLevel = curLevel;
    curLevel = inter;
    nextLevel.clear();
   }       
   if (!parents.containsKey(endWord)) return new ArrayList<List<String>>();
   generateResult(parents, beginWord, endWord, new LinkedList<String>());
   return result;
    }

    public void generateResult(HashMap<String, List<String>> parents, String start, String end, List<String> fromPrev){
     if (start == end){
      LinkedList<String> temp = new LinkedList<String>(fromPrev);
      temp.addFirst(start);
      result.add(temp);
      return;
     }
     List<String> parent = parents.get(end);
     ((LinkedList<String>) fromPrev).addFirst(end);
     for (String upper:parent){
      generateResult(parents, start, upper, fromPrev);
     }
     ((LinkedList<String>) fromPrev).removeFirst();
    }

    public void getNextWords(HashMap<String, List<String>> parents, HashSet<String> nextWord, HashSet<String>notVisited, String current){
     char []possible = current.toCharArray();
     for (int i = 0; i < possible.length; i++){
      char origin = possible[i];
      for (char a = 'a'; a <= 'z'; a++){
       if (a != origin){
        possible[i] = a;
        String temp = String.valueOf(possible);
        if (notVisited.contains(temp)) {
         nextWord.add(temp);
         List<String> parent = parents.containsKey(temp)?parents.get(temp):new ArrayList<String>();
         parent.add(current);
         parents.put(temp, parent);
        }
       }
      }
      possible[i] = origin;
     }
    }
}

Monday, December 21, 2015

next topic

divide and conquer

Backtracking

[leetcode]Surrounded Regions

这题leetcode设的memory好紧... 最后把recursion换成iterative做才过.. 还有BFS忘了track visited loop 搞了很久 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Solution {
    public void solve(char[][] board) {
        if (board == null || board.length == 0 || board[0].length == 0) return;
        for (int i = 0; i < board.length; i++){
            if (board[i][0] == 'O') filpEdgeRegionToOne(board, i, 0);
            if (board[i][board[0].length-1] == 'O') filpEdgeRegionToOne(board, i, board[0].length-1);
        }
        for (int i = 0; i < board[0].length; i++){
            if (board[0][i] == 'O') filpEdgeRegionToOne(board, 0, i);
            if (board[board.length-1][i] == 'O') filpEdgeRegionToOne(board, board.length-1, i);
        }
        
        for (int i = 0; i < board.length; i++){
            for (int j = 0; j < board[0].length; j++){
                if (board[i][j] == 'O')
                    board[i][j] = 'X';
                else if (board[i][j] == '1')
                    board[i][j] = 'O';
            }
        }
    }
    
    void filpEdgeRegionToOne(char[][]board, int i, int j){
        int dirs[][] = {{1,0},{-1,0},{0,1},{0,-1}};
        Queue<int[]> queue = new LinkedList<int[]>();
        queue.add(new int[]{i,j});
        while (!queue.isEmpty()){
            int []location = queue.poll();
            if (board[location[0]][location[1]] == 'O'){
                board[location[0]][location[1]] = '1';
                for (int k = 0; k < dirs.length; k++){
                    int x = location[0]+dirs[k][0];
                    int y = location[1]+dirs[k][1];
                    if (checkValid(board, x, y)) queue.add(new int[]{x,y});
                }
            }
        }
    }
    
    boolean checkValid(char[][] board, int i, int j){
        return !(i < 0 || i >= board.length || 
               j < 0 || j >= board[i].length || 
               board[i][j] == 'X' || board[i][j] == '1');
    }
}

[leetcode] Course Schedule II

貌似这是Topological sorting...上网看了下Topological的解释 思路就清晰了....
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] inDegree = new int[numCourses];
        List<HashSet<Integer>> out = new ArrayList<HashSet<Integer>>();
        for (int i = 0; i < numCourses; i++){
            out.add(new HashSet<Integer>());
        }
        for (int i = 0; i < prerequisites.length; i++){
            if (!out.get(prerequisites[i][1]).contains(prerequisites[i][0])){
                inDegree[prerequisites[i][0]]++;
                out.get(prerequisites[i][1]).add(prerequisites[i][0]);
            }
        }

        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i = 0; i < inDegree.length; i++){
            if (inDegree[i] == 0) queue.add(i);
        }
        int result[] = new int[numCourses];
        int curPtr = 0;
        while (!queue.isEmpty()){
            int current = queue.poll();
            result[curPtr++] = current;
            HashSet<Integer> outCourses = out.get(current);
            for (Integer temp:outCourses){
                inDegree[temp]--;
                out.get(temp).remove(current);
                if (inDegree[temp] == 0) queue.add(temp);
            }
        }
        if (curPtr != numCourses) return new int[0];
        return result;
    }
}

Sunday, December 20, 2015

[leetcode]Minimum Height Trees

这条题考的就是对graph和tree的熟悉程度... 记着tree maximum只可能有2个nodes能成为最短path的root... 围绕着这个做文章.. 不停地删leaf..剩下的(小于等于2)的结果就是所要的结果了..
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        int degree[] = new int[n];
        HashMap<Integer, List<Integer>> nodes = new HashMap<Integer, List<Integer>>();
        for (int i = 0; i < edges.length; i++){
            int a = edges[i][0];
            int b = edges[i][1];
            List<Integer> listA = nodes.containsKey(a)?nodes.get(a):new ArrayList<Integer>();
            List<Integer> listB = nodes.containsKey(b)?nodes.get(b):new ArrayList<Integer>();
            listA.add(b);
            listB.add(a);
            nodes.put(a, listA);
            nodes.put(b, listB);
            degree[a]++;
            degree[b]++;
        }
        int remain = n;
        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i = 0; i < n; i++){
            if(degree[i] == 1) queue.add(i);
        }
        while (remain > 2){
            int size = queue.size();
            for (int i = 0; i < size; i++){
                int leaf = queue.poll();
                remain--;
                degree[leaf]--;
                for (Integer neighbor:nodes.get(leaf)){
                    degree[neighbor]--;
                    if (degree[neighbor] == 1) queue.add(neighbor);
                }
            }
        }
        List<Integer> result = new ArrayList<Integer>(queue);
        if (n == 1) result.add(0);
        return result;
    }
}

TO-DO 12/20/2015

REVIEW:
 Dijstra and Bellman-ford algorithm, RIP algorithm
Floyd最短路算法 还有max flow这些基础图论的东西

fibonacci number matrix calculation


http://www.gocalf.com/blog/calc-fibonacci.html

Saturday, December 19, 2015

[leetcode] Clone Graph

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) return null;
        HashMap<UndirectedGraphNode, UndirectedGraphNode> cloneNodes = 
                    new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        mapClone(node, cloneNodes);
        UndirectedGraphNode[] allNodes = cloneNodes.keySet()
                                            .toArray(new UndirectedGraphNode[cloneNodes.size()]);
        for (int i = 0; i < allNodes.length; i++){
            UndirectedGraphNode copyNode = cloneNodes.get(allNodes[i]);
            List<UndirectedGraphNode> neighbors = allNodes[i].neighbors;
            for (int j = 0; j < neighbors.size(); j++){
                copyNode.neighbors.add(cloneNodes.get(neighbors.get(j)));
            }
        }
        
        return cloneNodes.get(node);
    }
    
    
    public void mapClone(UndirectedGraphNode node, 
                HashMap<UndirectedGraphNode, UndirectedGraphNode> cloneNodes){
        if (cloneNodes.containsKey(node)) return;
        cloneNodes.put(node, new UndirectedGraphNode(node.label));
        List<UndirectedGraphNode> neighbors = node.neighbors;
        for (int i = 0; i < neighbors.size(); i++){
            mapClone(neighbors.get(i), cloneNodes);
        }
    }
}

[leetcode]Course Schedule

就是建立有向图 查有没有cycle
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        HashMap<Integer, Node> lookup = new HashMap<Integer, Node>();
        for (int i = 0; i < prerequisites.length; i++){
            Node temp = lookup.containsKey(prerequisites[i][0])?
                        lookup.get(prerequisites[i][0]):new Node(prerequisites[i][0]);
            Node next = lookup.containsKey(prerequisites[i][1])?
                        lookup.get(prerequisites[i][1]):new Node(prerequisites[i][1]);
            temp.addNext(next);
            lookup.put(prerequisites[i][0], temp);
            lookup.put(prerequisites[i][1], next);
        }
        
        Integer[]nodes = (Integer[])lookup.keySet().toArray(new Integer[lookup.size()]);
        for (int i = 0; i < nodes.length; i++){
            if (!lookup.get(nodes[i]).checked && hasCycle(lookup, new HashSet<Integer>(), nodes[i].intValue())){
                return false;
            }
        }
        return true;
    }
    
    public boolean hasCycle(HashMap<Integer, Node> lookup, HashSet<Integer> visited, int current){
        Node curNode = lookup.get(current);
        curNode.checked = true;
        visited.add(current);
        List<Node> neighbors = curNode.nexts;
        for (int i = 0; i < neighbors.size(); i++){
            if (visited.contains(neighbors.get(i).classNum) || hasCycle(lookup, visited, neighbors.get(i).classNum)){
                return true;
            }
        }
        visited.remove(current);
        return false;
    }
}

class Node{
    int classNum;
    boolean checked;
    List<Node> nexts = new ArrayList<Node>();
    Node(int classNum){this.classNum = classNum;}
    void addNext(Node next){nexts.add(next);}
}

[leetcode]Graph Valid Tree

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
    public boolean validTree(int n, int[][] edges) {
        if (n == 1) return true;
        HashMap<Integer, List<Integer>> lookup = new HashMap<Integer, List<Integer>>();
        for (int i = 0; i < edges.length; i++){
            List<Integer> neighbors = lookup.containsKey(edges[i][0])?
                                      lookup.get(edges[i][0]):new ArrayList<Integer>();
            neighbors.add(edges[i][1]);
            List<Integer> neighbors2 = lookup.containsKey(edges[i][1])?
                                      lookup.get(edges[i][1]):new ArrayList<Integer>();
            neighbors2.add(edges[i][0]);
            lookup.put(edges[i][0], neighbors);
            lookup.put(edges[i][1], neighbors2);
        }
        if (lookup.size() != n) return false;
        boolean visited[] = new boolean[n];
        if (hasCycle(lookup, visited, -1, 0)) return false;
        for (int i = 0; i < visited.length; i++){
            if (!visited[i]) return false;
        }
        return true;
    }
    
    public boolean hasCycle(HashMap<Integer, List<Integer>> neighbors, boolean[] visited, int parent, int current){
        if (visited[current]) return true;
        visited[current] = true;
        List<Integer> neighbor = neighbors.get(current);
        for (int i = 0; i < neighbor.size(); i++){
            if (neighbor.get(i) != parent && hasCycle(neighbors, visited, current, neighbor.get(i))){
                return true;
            }
        }
        return false;
    }
}

Sunday, December 13, 2015

[leetcode]Remove Invalid Parentheses

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> result = new ArrayList<String>();
        HashSet<String> lookup = new HashSet<String>();
        Queue<String> queue = new LinkedList<String>();
        queue.add(s);
        queue.add(null);
        while (!queue.isEmpty()){
            String current = queue.poll();
            if (current == null){
                if (result.size() != 0) break;
                queue.add(null);
            }
            if (current != null && !lookup.contains(current)){
                lookup.add(current);
                if (isValid(current)) result.add(current);
                else{
                    for (int i = 0; i < current.length(); i++){
                        char temp = current.charAt(i);
                        if (temp == '(' || temp == ')'){
                            queue.add(current.substring(0,i)+current.substring(i+1));
                        }
                    }
                }
            }
        }
        return result;
    }
    
    
    private boolean isValid(String s){
        int count = 0;
        for (int i = 0; i < s.length(); i++){
            char current = s.charAt(i);
            if (current == '(') count++;
            else if (current == ')') count--;
            if (count < 0) return false;
        }
        
        return count == 0;
    }
}