Wednesday, January 14, 2015

Numerics

Numerics
large number addition







large number multiply

Sunday, January 11, 2015

Day 90, ##, Binary Tree Upside Down, Read N Characters Given Read4, Read N Characters Given Read4 II - Call multiple times


Binary Tree Upside Down


Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
    1
   / \
  2   3
 / \
4   5
return the root of the binary tree [4,5,2,#,#,3,1].

   4
  / \
 5   2
    / \
   3   1  
----------------------------------------------------------------
Solution #1, recursive
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *helper(TreeNode *root, TreeNode *left, TreeNode *right) {
        if (root == NULL) return right;
        TreeNode *tempLeft = root->left;
        TreeNode *tempRight = root->right;
        root->right = right;
        root->left = left;

        return helper(tempLeft,tempRight,root);
    }

    TreeNode *upsideDownBinaryTree(TreeNode *root) {
        return helper(root,NULL,NULL);
    }
};
Solution #2, iterative, with a stack containing all left children


Read N Characters Given Read4


The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function will only be called once for each test case.
------------------------------------------------------------------
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        int count = 0;
        while (count < n) {
            int curRead = read4(buf);
            if (curRead < 4) {
                return min(count + curRead,n);
            }
            count += curRead;
            buf += 4;
        }
        return n;
    }
};

Java
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    public int read(char[] buf, int n) {
        int count = 0; 
        while (count < n) {
            char[] temp = new char[4];
            int curRead = read4(temp);
            for (int i = 0; i < curRead && count < n; i++) {
                buf[count++] = temp[i];
            }
            if (curRead < 4) break;
        }
        
        return count;
    }
}

Read N Characters Given Read4 II - Call multiple times


The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function may be called multiple times.
----------------------------------------------------------------
Note: char *buf is the destination buffer

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    Solution() {
        bufferSize = 0;
        offset = 0;
    }

    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        int readChar = 0;
        bool eof = false;
        while (!eof && readChar < n) {
            if (bufferSize == 0) {
                bufferSize = read4(buffer);
                if (bufferSize < 4) {
                    eof = true;
                }
            }
            int len = min(n - readChar,bufferSize);
            memcpy(buf,buffer + offset,len);
            bufferSize -= len;
            offset = (offset + len) % 4;
            readChar += len;
            buf += len;
        }
        
        return readChar;
    }
    
private:
    char buffer[4];
    int offset;
    int bufferSize;
};

Java, 有若干种实现方式,关键在于先把本地的缓存读完,再调用read4
/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    
    private char[] local = new char[4];
    private int index = 0;
    private int size = 0;
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    public int read(char[] buf, int n) {
        int count = 0;
        boolean eof = false;
        while (count < n && !eof) {
            if (size == 0) {
                size = read4(local);
                index = 0;
                if (size < 4) eof = true;
            }

            while (size > 0 && count < n) {
                buf[count] = local[index];
                count++;
                index++;
                size--;
            }            
        }
        
        return count;
    }
}

Saturday, January 10, 2015

Day 89, ##, Min Stack


Min Stack


Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
--------------------------------------------------
with two stacks
class MinStack {
public:
    MinStack() {
        minElem = INT_MAX;
    }

    void push(int x) {
        st.push(x);
        if (x <= minElem) {
            minSt.push(x);
            minElem = x;
        }
    }

    void pop() {
        if (st.empty()) return;
        if (st.top() == minElem) {
            minSt.pop();
            if (!minSt.empty()) {
                minElem = minSt.top();
            }else {
                minElem = INT_MAX;
            }
        }
        st.pop();
    }

    int top() {
        if (st.empty()) return -1;
        return st.top();
    }

    int getMin() {
        return (int)minElem;
    }
    
private:
    stack<int> st;
    stack<int> minSt;
    long minElem;
};
with one stack
class MinStack {
public:
    MinStack() {
        minElem = INT_MAX;
    }

    void push(int x) {
        if (x <= minElem) {
            st.push(minElem);
            minElem = x;
        }
        st.push(x);
    }

    void pop() {
        if (st.empty()) return;
        
        if (st.top() == minElem) {
            st.pop();
            if (!st.empty()) {
                minElem = st.top();
                st.pop();
            }else {
                minElem = INT_MAX;
            }
        }else
            st.pop();
    }

    int top() {
        if (st.empty()) return -1;
        return st.top();
    }

    int getMin() {
        return (int)minElem;
    }
    
private:
    stack<int> st;
    long minElem;
};

Thursday, January 8, 2015

Day 88, ##, Find Minimum in Rotated Sorted Array, Find Minimum in Rotated Sorted Array II


Find Minimum in Rotated Sorted Array


Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
---------------------------------------------------------------
binary search
class Solution {
public:
    int findMin(vector<int> &num) {
        if (num.size() == 1) return num[0];
        if (num[0] < num.back()) return num[0];
        
        int left = 0;
        int right = num.size() - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (num[mid] < num[mid - 1]) {
                return num[mid];
            }
            
            if (num[mid] > num[right]) {
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        
        return -1;
    }
};

Find Minimum in Rotated Sorted Array II


Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array may contain duplicates.
--------------------------------------------------------
if num[mid] == num[right], then num[left] must equal to num[mid] as well
class Solution {
public:
    int findMin(vector<int> &num) {
        if (num.size() == 1) return num[0];
        if (num[0] < num.back()) return num[0];
         
        int left = 0;
        int right = num.size() - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (num[mid] < num[mid - 1]) {
                return num[mid];
            }
            if (num[mid] == num[right]) {
                right--;
            }else if (num[mid] > num[right]) {
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
         
        return num[0];
    }
};

Wednesday, January 7, 2015

Day 87, ##, Reverse Words in a String, Maximum Product Subarray


Reverse Words in a String


Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
---------------------------------------------------------
另外可以用三步翻转法
class Solution {
public:
    void reverseWords(string &s) {
        string rt = "";
        
        for (int i = 0; i < s.length(); i++) {
            string word = "";
            while (i < s.length() && !isspace(s[i])) {
                word += s[i];
                i++;
            }
            if (word == "") continue;
            
            if (rt == "") {
                rt = word;
            }else {
                rt = word + " " + rt;
            }
            word = "";
            i--;
        }
        
        s = rt;
    }
};

Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
---------------------------------------------------------------
DP,dp[i] has the max(min) product subarray that ends at i
#1 can be optimized with two max and min variables
#2 can get rid of if condition, minDp = min(A[i],A[i] * minDp,A[i] * maxDp)
class Solution {
public:
    int maxProduct(int A[], int n) {
        vector<int> maxDp(n);
        vector<int> minDp(n);
        maxDp[0] = A[0];
        minDp[0] = A[0];
        
        int maxP = maxDp[0];
        int i = 1;
        while (i < n) {
            if (A[i] < 0) {
                minDp[i] = min(A[i],A[i] * maxDp[i - 1]);
                maxDp[i] = max(A[i],A[i] * minDp[i - 1]);
            }else {
                minDp[i] = min(A[i],A[i] * minDp[i - 1]);
                maxDp[i] = max(A[i],A[i] * maxDp[i - 1]);
            }
            maxP = max(maxP,maxDp[i]);
            i++;
        }
        
        return maxP;
    }
};

O(1) space
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int high = 1, low = 1;
        int maxSub = INT_MIN;
        
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] > 0) {
                high = max(nums[i],nums[i] * high);
                low = min(nums[i],nums[i] * low);
            }else {
                int th = high;
                high = max(nums[i],nums[i] * low);
                low = min(nums[i],nums[i] * th);
            }
            maxSub = max(maxSub,high);
        }
        
        return maxSub;
    }
};

Sunday, January 4, 2015

Day 86, ##, LRU Cache

LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
-----------------------------------------------------------------
a few improvement
#1 design a doublely-linked list class
#2 have a de-constructor
#3 code re-factory
用了2个dummy, head跟tail
struct LinkedNode {
    int key;
    int val;
    LinkedNode *pre;
    LinkedNode *next;
    LinkedNode(int key,int val) {
        this->key = key;
        this->val = val;
        pre = NULL;
        next = NULL;
    }
};

class LRUCache{
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
        size = 0;
        head = new LinkedNode(-1,-1);
        tail = new LinkedNode(-1,-1);
        head->next = tail;
        tail->pre = head;
    }
    
    int get(int key) {
        if (dic.find(key) == dic.end()) {
            return -1;
        }
        LinkedNode *node = removeNode(dic[key]);
        insertToFront(node);
        return node->val;
    }
    
    LinkedNode* removeNode(LinkedNode *node) {
        LinkedNode *preNode = node->pre;
        LinkedNode *nextNode = node->next;
        preNode->next = nextNode;
        nextNode->pre = preNode;
        return node;
    }
    
    void insertToFront(LinkedNode *node) {
        LinkedNode *temp = head->next;
        head->next = node;
        temp->pre = node;
        node->next = temp;
        node->pre = head;
    }
    
    void set(int key, int value) {
        if (dic.find(key) == dic.end()) {
            LinkedNode *temp = head->next;
            LinkedNode *add = new LinkedNode(key,value);
            head->next = add;
            add->pre = head;
            add->next = temp;
            temp->pre = add;
            dic[key] = add;
            size++;
        }else {
            LinkedNode *catched = removeNode(dic[key]);
            insertToFront(dic[key]);
            dic[key]->val = value;
        }
        
        if (size > capacity) {
            LinkedNode *catched = removeNode(tail->pre);
            dic.erase(catched->key);
            delete catched;
            size--;
        }
    }
private:
    int capacity;
    int size;
    LinkedNode *head;
    LinkedNode *tail;
    unordered_map<int,LinkedNode*> dic;
};

Java, updated on Jun-30th-2018
class LRUCache {
    private int capacity;
    private DoublyLinkedNode head;
    private DoublyLinkedNode tail;
    private Map<Integer, DoublyLinkedNode> map;
    
    public LRUCache(int capacity) {
        this.capacity = capacity;
        head = new DoublyLinkedNode(-1, -1);
        tail = new DoublyLinkedNode(-1, -1);
        head.next = tail;
        tail.pre = head;
        map = new HashMap<>();
    }
    
    public int get(int key) {
        if (map.containsKey(key)) {
            DoublyLinkedNode node = pickupAndReturn(key);
            insertFront(node);
            return node.val;
        }
        
        return -1;
    }
    
    public void put(int key, int value) {
        DoublyLinkedNode node = null;
        if (!map.containsKey(key)) {
            node = new DoublyLinkedNode(key, value);
            map.put(key, node);
        }else {
            node = pickupAndReturn(key);
            node.val = value;
        }
        
        insertFront(node);
        
        if (map.size() > capacity) {
            removeLast();
        }
    }
    
    private void removeLast() {
        int key = tail.pre.key;
        tail.pre.pre.next = tail;
        tail.pre = tail.pre.pre;
        map.remove(key);
    }
    
    private void insertFront(DoublyLinkedNode node) {
        head.next.pre = node;
        node.next = head.next;
        head.next = node;
        node.pre = head;
    }
    
    private DoublyLinkedNode pickupAndReturn(int key) {
        DoublyLinkedNode node = map.get(key);
        node.pre.next = node.next;
        node.next.pre = node.pre;

        return node;
    }
}

class DoublyLinkedNode{
    public DoublyLinkedNode pre;
    public DoublyLinkedNode next;
    public int key;
    public int val;
    
    public DoublyLinkedNode(int key, int val) {
        this.key = key;
        this.val = val;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

Friday, January 2, 2015

Note: 九章算法

第2章
search in a range: 找的是2分法分别查找first position and last position

 做lintcode上binary search的题

search insert position

解释find K-th element里为何返回无穷大

rotated sorted array里如何找分割点,lgn

3步翻转: recover sorted array, rotate string, reverse words in a string(2步)

merge sort a linked list
------------------------------------------------------------------------------------
第3章 
partition array
merge sort, quick sort
lowest common ancestor
bfs, 3种方法
validate bfs,用divide and conquer
implement iterator for bfs(stack)
------------------------------------------------------------------------------------
第4章
sort list,可以用 partition list(from quick sort)
copy list with random pointer
convert sorted list to bst, bottom up
非递归考点: pre, in, post order tree traversal, permutation, subset
------------------------------------------------------------------------------------
第5章