Friday, July 17, 2015

236. Lowest Common Ancestor of a Binary Tree. (M)

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

 

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the tree.
A:


Google 面试题   哎,惨痛~~~~~~~~~~

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || root==p || root==q)
            return root;
        auto L = lowestCommonAncestor(root->left, p, q);
        auto R = lowestCommonAncestor(root->right, p, q);
        if(L&&R)
            return root;
        return L?L:R;
    }
};



Mistakes:

Friday, July 10, 2015

235. Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

 

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [2,1], p = 2, q = 1
Output: 2

 

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the BST.
A:
根据val , 看左边右边

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(p.val > q.val)
            return lowestCommonAncestor(root,q,p);
        return helper(root,p,q);
    }
    private TreeNode helper(TreeNode root, TreeNode p, TreeNode q) {
        if(root.val<p.val)
            return helper(root.right,p,q);
        else if(root.val > q.val)
            return helper(root.left,p,q);
        return root;
    }
}

其实这道题,无关Binary Search Tree ---虽然利用起来,效率会高一些些

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root)
return root;
if(root->val == p->val || root->val == q->val){
return root;
}
auto l = lowestCommonAncestor(root->left, p, q);
auto r = lowestCommonAncestor(root->right, p, q);
if(l&&r){
return root;
}else{
return l?l:r;
}
}
};


Mistakes:




Wednesday, July 8, 2015

Number of Digit One ~~~~~~~~~

Q:
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
A:
就是每一位计算有多少个。
分为高一位 有多少个导致现在重复的。  和现在位有多少个1

public class Solution {
    public int countDigitOne(int n) {
        long num1s = 0;
        for(int i =0;i<32;i++){// for each digit
            long div = (long)Math.pow(10,i);
            if(div > n)
                break;
            num1s +=  n/(div*10)* div + helper(n%(div*10),div); // number of repeats  + at this position
        }
        return (int)num1s;
    }
    private long helper(long x,long powerOf10){// get the number of 1s at x's first digit (x/powerOf10 < 10)
        long res = x/powerOf10;
        if(res==0)
            return 0;
        if(res >1)
            return powerOf10;
        return x - res * powerOf10 + 1; // for case x = 10,
    }
}

 这里的关键点是: 如何分解这个答案:  我们的分解方式是:
1: 从低到高,每一位计算
2: 对数字位 i(i = 0 to 31);
     2.1 )看高于它的数字位, 会导致有多少个重复1(在i位上)的。
     2.2) 看改位置:会有多少个重复的1 出现。    也就是 hepler函数。(这里又分为: 该位是否 为  1.    看1 的位置重复完了没有。   )
 


Mistakes:
1:  刚开始 计算高位重复的,给减了一




Tuesday, July 7, 2015

Power of Two

Q:
Given an integer, write a function to determine if it is a power of two.
A:

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n>0 && (n & (n-1))==0;
    }
}

Mistakes:


232. Implement Queue using Stacks -E

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

  • You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

 

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

 

Constraints:

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.
  • All the calls to pop and peek are valid.

 

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

A:
  -----use two stack to simulate ----------
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
inS.push(x);
}
int pop() {
moveIn2Out();
int res = outS.top();
outS.pop();
return res;
}
int peek() {
moveIn2Out();
return outS.top();
}
bool empty() {
moveIn2Out();
return outS.empty();
}
private:
stack<int> inS, outS;
void moveIn2Out(){
if(outS.empty()){
while( ! inS.empty()){
int tmp = inS.top();
outS.push(tmp);
inS.pop();
}
}
}
};

/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
/** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */
Errors:
    1:  用Stack的时候,用了vector的方法。很SB
    2:  只有当outS为空的时候,才能把inS都倒过去。否则是不对的

Saturday, July 4, 2015

The Skyline Problem

Q:
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).
Buildings Skyline Contour The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .
The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
Notes:
  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].
  • The input list is already sorted in ascending order by the left x position Li.
  • The output list must be sorted by the x position.
  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]
A:
 -----------------------------    divide and conquer  -----------------------







Mistakes: