Sunday, June 14, 2015

226. Invert Binary Tree (easy)

Given the root of a binary tree, invert the tree, and return its root.

 

Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
A:
递归

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root)
return root;
invertTree(root->left);
invertTree(root->right);
auto tmp = root->left;
root->left = root->right;
root->right = tmp;
return root;
}
};




211. Add and Search Word - Data structure design ----M

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.


A:
思路很直接,就是 用 Trie 解决。  (这里,仍然需要自己定义TrieNode)

*********** Solution 1: Trie *******************

class WordDictionary {
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        root = new TrieNode('2',true);
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        auto runner = root;
        for(int i =0;i<word.length();i++){
            char ch = word[i];
            if(runner->map.find(ch) == runner->map.end()){
                TrieNode * tmp = new TrieNode(ch, i == word.length()-1);
                runner->map[ch] = tmp;
            }
            runner = runner->map[ch];
        }
        runner->isEnd = true;
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    bool search(string word) {
        return searchHelper(word, root);
    }
private:
    struct TrieNode{
        char ch;
        bool isEnd;
        unordered_map<char, TrieNode*> map;
        TrieNode(char curChar, bool end){
            ch = curChar;
            isEnd = end;
        }
    };
    bool searchHelper(string word, const TrieNode* node){        
        if(word.length() ==0)
            return node->isEnd;
        auto runner = root;
        char ch = word[0];
        if(ch == '.'){
            auto iter = node->map.begin();
            while(iter != node->map.end()){
                int subResult = searchHelper(word.substr(1), iter->second );
                if(subResult)
                    return true;
                iter++;
            }
        }
        if(node->map.find(ch) == node->map.end()){
            return false;
        }else{
            return searchHelper(word.substr(1), node->map.find(ch)->second);
        }
    }

    TrieNode *root;
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */
Mistakes:


第二次  Trie Node 用的array,而非HashMap

public class WordDictionary {
    TrieNode root = new TrieNode();
    // Adds a word into the data structure.
    public void addWord(String word) {
        aHelper(word,root);
    }
    private void aHelper(String word, TrieNode root){
        if(word.length()==0){
            root.isLeaf = true;
            return;
        }
        char ch = word.charAt(0);
        if(root.child[ch-'a'] ==null)
            root.child[ch-'a'] = new TrieNode();
        aHelper(word.substring(1),root.child[ch-'a']);
    }
    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    public boolean search(String word) {
        return sHelper(root,word);
    }
    private boolean sHelper(TrieNode root, String word){
        if(root == null)
            return false;
        if(word.length()==0)
            return root.isLeaf;
        char ch = word.charAt(0);
        word = word.substring(1);
        if(ch != '.'){
            return sHelper(root.child[ch-'a'], word);
        }else{
            for(int i =0;i< 26;i++){
                if( sHelper(root.child[i], word))
                    return true;
            }
            return false;
        }
    }
}
class TrieNode{
    public boolean isLeaf;
    TrieNode child[] ;
    public TrieNode(){
        child = new TrieNode[26];
        isLeaf = false;
    }
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");




Saturday, June 13, 2015

Course Schedule II

Q:
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.


A:
仍然用了BSF

---------------初始解法-----------把constrain放到List中,以便删除---------


public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int n = prerequisites.length;
        int result[] = new int[numCourses];
        int lastIndex = 0;
        List<int[]> list = new LinkedList();
        for(int i =0;i<n;i++)
            list.add(new int[]{prerequisites[i][0],prerequisites[i][1]});
        Set<Integer> findSet = new HashSet();

        boolean isFoundOne = true;
        while(isFoundOne && lastIndex < numCourses){
            isFoundOne = false;
            for(int i = 0;i<numCourses;i++){
                if(findSet.contains(i))
                    continue;
                boolean hasConstrain = false;
                for(int j = 0;j<list.size();j++){
                    int[] tmp = list.get(j);
                    if(findSet.contains(tmp[1])){
                        list.remove(j);
                        j--;
                        continue;
                    }else if(tmp[0] == i){
                        hasConstrain = true;
                        break;
                    }
                }
                if( ! hasConstrain){
                    findSet.add(i);
                    result[lastIndex++] = i;
                    isFoundOne = true;
                    break;
                }
            }
        }
        if( lastIndex == numCourses)
            return result;
        else
            return new int[]{};
    }
}

上面的解法超时。原因是不需要每次遍历所有的constrain,而只需要查看相应 class i 的constrain即可。

*************下面 是雷同于 I 的解法*************

public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int result[] = new int[numCourses];
        int lastIndex = 0;
        Map<Integer, List<Integer>> map = new HashMap();
        for(int i = 0;i<numCourses;i++)
            map.put(i, new LinkedList<Integer>());

        for(int i =0;i<prerequisites.length;i++)
            map.get(prerequisites[i][0]).add(prerequisites[i][1]);

        Set<Integer> findSet = new HashSet();
    
        boolean isFoundOne = true;
        while(isFoundOne && lastIndex < numCourses){
            isFoundOne = false;
            for(Integer i : map.keySet()){
                List<Integer> constrainList = map.get(i);
                for(int j = 0;j< constrainList.size();j++){
                    if(findSet.contains(constrainList.get(j))){
                        constrainList.remove(j);
                        j--;
                    }else
                        break;
                }
                if( constrainList.isEmpty() ){
                    findSet.add(i);
                    map.remove(i);
                    result[lastIndex++] = i;
                    isFoundOne = true;
                    break;
                }
            }
        }
        return lastIndex == numCourses? result: new int[]{};
    }
}


Mistakes:
1: 上面的第二个解法中,忘记   map.remove(i)了。



Friday, June 12, 2015

Minimum Size Subarray Sum

Q:
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

A:
two pointer


public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if(nums == null || nums.length==0)
            return 0;
        int p1 =0,p2= -1; // both are inclusive
        int minLen = Integer.MAX_VALUE;
        long sum = 0;
        while(p2<nums.length){
            if(sum < s){
                p2++;
                if(p2<nums.length)
                    sum += nums[p2];
            }else{
                minLen = Math.min(minLen, p2-p1+1);
                sum -= nums[p1++]; // do not need to check if p1<=p2, coz they s is positive
            }
        }
        return minLen==Integer.MAX_VALUE?0:minLen;
    }
}





Mistakes:
 这道题的2大错误在于。
1: 刚开始用了 以前的双层循环的解法。  虽然复杂的没有变,但是写起来复杂了。 不好
2: 核心错误:  一开始p2没有确定是inclusive的,因此,开始没有设p2= -1;



***********第二遍*********

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int res = Integer.MAX_VALUE, pre = -1, sum = 0;
        for(int i =0;i<nums.length;i++){
            sum+= nums[i];
            if(sum<s)
                continue;
            while( sum-nums[pre+1] >= s){
                pre++;
                sum -= nums[pre];
            }
            res = Math.min(i-pre,res);
            sum = sum - nums[++pre];
        }
        return res == Integer.MAX_VALUE? 0 : res;
    }
}
 



208. Implement Trie (Prefix Tree) --M

Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true
Note:
  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

A:

不要搞得太复杂,就是每个character一个节点就行了了。(外加HashMap)
( empty String “”  是所有 字符串的前缀。~~~即使还没有开始存)

class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new Node();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        Node *cur = root;
        for(int i =0;i<word.length();++i)
        {
            char ch = word[i];
            if(cur->chmap.find(ch) == cur->chmap.end())
            {
                Node* tmp = new Node();
                cur->chmap[ch] = tmp;
            }             
            cur = cur->chmap.at(ch);
        }
        cur->isLeaf = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Node *cur = root;        
        for(int i =0;i<word.length();++i)
        {
            char ch = word[i];
            if(cur->chmap.find(ch)==cur->chmap.end())
            {
                return false;
            }
            cur = cur->chmap.find(ch)->second;
        }
        return cur->isLeaf;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
                Node *cur = root;        
        for(int i =0;i<prefix.length();++i)
        {
            char ch = prefix[i];
            if(cur->chmap.find(ch)==cur->chmap.end())
            {
                return false;
            }
            cur = cur->chmap.find(ch)->second;
        }
        return true;
    }
private:
    struct Node{
        unordered_map<char,Node*> chmap;
        bool isLeaf=false;
    };
    Node * root; // root contains no char to reach it
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */



Mistakes:
1:  一开始加上了,如果该节点后面没有,就自己保存一个string,搞得太复杂
2: 这道题,最容易错的地方是,search和 startWith中,最后要检查是否是null节点。








Wednesday, June 10, 2015

207. Course Schedule ----M !!!

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.

  • For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.

Return true if you can finish all courses. Otherwise, return false.

 

Example 1:

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take. 
To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take. 
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

 

Constraints:

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • 0 <= ai, bi < numCourses
  • All the pairs prerequisites[i] are unique.
A:
就是topological sort (CLIS上的经典代码)
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> Color(numCourses, 0); //0 for white, 1 for gray, and 2 for black
unordered_map<int, vector<int>> M;
for (auto pre : prerequisites) {
M[pre[0]].push_back(pre[1]);
}
for (int i = 0; i < numCourses; i++) {
if (not dfs(M, Color, i))
return false;
}
return true;
}

private:
bool dfs(unordered_map<int, vector<int>>& M, vector<int>& Color, int i) {
if (Color[i] == 2) {
return true;
}
if (Color[i] == 1) {
return false;
}
Color[i] = 1; // mark gray now,
for (int val : M[i]) {
auto res = dfs(M, Color, val);
if (not res)
return false;
}
Color[i] = 2;
return true;
}
};

-------------old---------每次traversal的同时,还可以在限制条件里  删去已经满足的class ----------
public class Solution {
        public boolean canFinish(int numCourses, int[][] prerequisites) {
        Set<Integer> set = new HashSet();
        Map<Integer, List<Integer>>  map = new HashMap();
        for(int i =0; i<numCourses; i++)  // initialize
            map.put(i,new LinkedList<Integer>());

        for(int j =0; j<prerequisites.length;j++)  // build the set
            map.get(prerequisites[j][0]).add(prerequisites[j][1]);

        boolean foundOne = true;
        while( !map.isEmpty() && foundOne){
            foundOne = false;
            for(int key : map.keySet()){
                boolean allTaken = true;
                List constrainList = map.get(key);
                for(int k = 0;k< constrainList.size();k++) // k is the constrain class
                    if( !set.contains(constrainList.get(k))){ // get the pre-requirement for class  key
                        allTaken = false;
                        break;
                    }else{ // this constrain class (k) is already found
                        constrainList.remove(k); // delete this constrains
                        k--;
                    }
                if(allTaken){
                    foundOne = true;
                    set.add(key);
                    map.remove(key);
                    break;
                }
            }
        }
        return map.isEmpty();
    }
}
 
注意,这里,最后一个break没有加的时候,仍然会超时。


Mistakes:
 1:  当 input 为1 [] 的时候, 陷入了死循环。    原因在于忘记找到可以先上的课后,把它放到set里的同时, 还要 map.remove()了

2:   第一遍解法的时候,如果 最后一个break没有加的时候,仍然会超时。   按理说不应该呀???




Saturday, May 9, 2015

206. Reverse Linked List (easy). !!

Q:

Given the head of a singly linked list, reverse the list, and return the reversed list.

 

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

 

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000


Follow up:
 A linked list can be reversed either iteratively or recursively. Could you implement both?

A:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
用dummy header
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode header;
while (head) {
auto tmp = head;
head = head->next;
tmp->next = header.next;
header.next = tmp;
}
return header.next;
}
};



或者把 新的head,不用 dummy header, 而是指向最新的head. 只是尽量晚赋值
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* newHead = nullptr;
while (head) {
ListNode* nextNode = head->next;
head->next = newHead;
newHead = head;
head = nextNode;
}
return newHead;
}
};


**********Mistakes*************

ListNode *header(0);  ---------> this grammar is WRONG. 

It initializes header as a null pointer (nullptr) because:

  • header is a pointer (ListNode*).
  • 0 is an integer literal, which implicitly converts to nullptr in C++ when assigned to a pointer.
Thus header is equivalent to
ListNode* header = nullptr; // Explicitly setting it to nullptr

This means header->next is an invalid operation because header is nullptr.



Correct Way to Create a Dummy Node

If you meant to create an actual ListNode object, you should write:

ListNode dummy(0); // Correct: Creates an actual ListNode
or use dynamic allocation:
      ListNode* header = new ListNode(0); // Allocates a real ListNode on the heap