Friday, July 3, 2015

hackRand problem

Q:  检测一个2D数组  其 x,y坐标的k范围内是否存在重复


import java.util.*;

public class Main {
    public static void main(String args[] ) throws Exception {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        if(n<=0){System.out.print("NO"); return;}
        String str  = sc.nextLine();
        // change str into line
        List<Integer[]> list = new LinkedList();

        int[][] Arr = new int[n][n];

        for(int i =0;i<n;i++) {
            String strArr[] = sc.nextLine().split("\\s+");
            for (int j = 0; j < strArr.length; j++)
                Arr[i][j] = Integer.parseInt(strArr[j]);
        }

        int k = sc.nextInt();
        int m = Arr[0].length;


        Map<Integer,Integer> map = new HashMap();

        //  each position as a center, and find it int the circle/ use k as radius
        for(int i =0;i<n;i++) {
            map.clear();
            // set-up the circle into the map
            for(int row=0; row < Math.min(n,i+k+1);row++){
                for(int col = 0;col<Math.min(n,k+1);col++){
                    if(row == i && col == 0)
                        continue;
                    int key = Arr[row][col];
                    addMap(map, key);
                }
            }
            // mvoe for each i-th position
            for (int j = 0; j < Arr[0].length; j++) {   // not, current i,j is not included
                int val = Arr[i][j];
                if(map.containsKey(val)){
                    System.out.println("YES");
                    return;
                }
                map.put(val,1);
                // remove most left column and add most left row
                if(j+ 1< m)
                    delMap(map,Arr[i][j+1]);
                if( j - k >=0 ){ // delete this 2k column
                    for(int row=Math.max(0,i-k); row < Math.min(n,i+k+1);row++){
                        delMap(map, Arr[row][j-k]);
                    }
                }
                if( j + k +1 < m ){ // add this 2k column
                    for(int row=Math.max(0,i-k); row < Math.min(n,i+k+1);row++){
                        addMap(map, Arr[row][j + k + 1]);
                    }
                }

            }
        }

        System.out.println("NO");
    }

    private static void addMap(Map<Integer,Integer> map, int val){
        int count = 0;
        if(map.containsKey(val))
            count = map.get(val);
        map.put(val,count+1);
    }
    private static void delMap(Map<Integer,Integer> map, int val){
        if(map.containsKey(val)) {
            int count = map.get(val);
            if(count==1){
                map.remove(val);
            }else
                map.put(val, count - 1);
        }
    }

}


Thursday, July 2, 2015

Majority Element II

Q:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
The algorithm should run in linear time and in O(1) space.
A:
最多2个结果。那么每次删除3个即可。   (这道题目有问题,OJ是要求大于等于 ⌊ n/3 ⌋ )
***********下面这个方法思路是有问题的 *********************

public class Solution {
    public List<Integer> majorityElement(int[] nums) {
        List<Integer> list = new LinkedList();
        int n1 = 0,n2 = 0;
        int c1 = 0,c2=0;// count of n1,n2,n3
        for(int i = 0;i<nums.length;i++){
            int val = nums[i];
            if(c1==0){ // if first value is not found
                n1 = val;
                c1=1;
            }else if( c2 ==0){ // if second value is not found
                n2 = val;
                c2=1;
            }else{ // already found two different values
                if(val == n1){
                    c1++;
                }else if(val == n2){
                    c2++;
                }else{ // not equals to previous two val
                    c1--;
                    c2--;
                }
            }
        }
        // now check two possible value, n1 and n2;
        if(c1>0)
            checkValue(list, nums,n1);
        if(c2>0 && n1 != n2) // for po
            checkValue(list, nums,n2);
        return list;
    }
    private void checkValue(List<Integer> list, int[] nums, int value){
        int count = 0;
        for(int i =0;i<nums.length;i++){
            if(nums[i] == value)
                count++;
        }
        if(count > nums.length/3)
            list.add(value);
    }
}



**************这个是正确的解法*******************
public class Solution { 
    public List<Integer> majorityElement(int[] nums) {
        int a = 0,b=0, aCount = 0, bCount = 0;
        for(int val : nums){
            if(aCount==0 || val == a){
                aCount++;
                a = val;
            }else if(bCount==0 || val == b){
                bCount++;
                b = val;
            }else{// found both a, b and c different
                bCount--;
                aCount--;
                if(aCount==0){ // since we always check aCount/a firstly
                    aCount = bCount;
                    a = b;
                    bCount =0;
                }
            }
        }
        List<Integer> res = new LinkedList();
        if(aCount > 0 && isMoreThanThird(nums,a))
            res.add(a);
        if(bCount > 0 && isMoreThanThird(nums,b))
            res.add(b);
        return res ;
    }
    private boolean isMoreThanThird(int[] nums, int a){
        int count = 0;
        for(int x : nums)
            if( x == a)
                count++;
        return count > nums.length/3;
    }
}




Mistakes:
1:  在于for loop中各个 检测语句, 不产生重复。  (因此,当检查c2==0的时候,前面要检查是否已经是n1的值了。
2:  最后n2的时候,要有个if语句



Wednesday, July 1, 2015

230. Kth Smallest Element in a BST -M

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

 

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

 

Constraints:

  • The number of elements of the BST is between 1 to 10^4.
  • You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
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 {
private:
    int getCount(TreeNode* root){
        if(! root){
            return 0;
        }
        return 1 + getCount(root->left) + getCount(root->right);
    }
public:
    int kthSmallest(TreeNode* root, int k) {
        // we can assume root is not NULL
        int lCount = getCount(root->left);
        if(k <= lCount){
            return kthSmallest(root->left, k);
        }else if(k == lCount +1 ){
            return root->val;
        }else{
            return kthSmallest(root->right, k-lCount-1);
        }

    }
};

----------------------------------最多走一遍---------利用了 C++ 的参数 引用------------------
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int res = -1;
helper(root, k, res);
return res;
}

private:
void helper(TreeNode* root, int& k, int& res) { // root is not NULL
if (res >= 0 || !root || k <= 0)
return;
helper(root->left, k, res);
k--; // count the node : root
if (k == 0) {
res = root->val;
return;
}
if (k >= 1)
helper(root->right, k, res);
}
};



************. 第三遍 ********改进:用返回值,代替了一个引用参数  ******
/**
* 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:
int kthSmallest(TreeNode* root, int k) {
return helper(root, k);
}

private:
int helper(TreeNode* root, int& k) { // safely assume root is not NULL
if (!root || k < 0)
return INT_MIN;
int l = helper(root->left, k);
if(l >= 0)
return l;
k--; // count the node : root
if (k == 0) {
return root->val;
}
return helper(root->right, k);
}
};


Mistakes:
1:  如果想通过监控res 是否是nullptr, 那么需要 double Pointer


216. Combination Sum III ------------M. !!!!

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
A:

就是递归

class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
return helper(k, 1, n);
}

private:
vector<vector<int>> helper(int k, int start, int n) {
if (n <= 0 || start > 9 || k <= 0) {
return {};
}
if (start == n && k == 1) {
return {{start}};
}
vector<vector<int>> res = helper(k, start + 1, n);
vector<vector<int>> res2 = helper(k - 1, start + 1, n - start);
for (auto& line : res2) {
line.push_back(start);
}
res.insert(res.end(), res2.begin(), res2.end());
return res;
}
};





Mistakes:
1: 一开始 没有注意限制条件  1---9的意思。
2:  很傻的是,第二遍。错了好几个地方。  主要是截止条件 没有考虑 {{start}}的情况。 反而是考虑了一堆{}的情况, 应该返回个{{}}。 哎。 我是SB


228. Summary Ranges

Q:
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
A:
就是挨个数呗
------------一点小技巧就是每次遇到一个数字的时候,决定前面的。  这样,就需要在for 循环之后再查看一遍----------

public class Solution {
        List<String> res = new LinkedList();
        for(int i =0;i < nums.length ; i++){
            int start = nums[i];
            String str = ""+start;
            while(   i+1< nums.length   && nums[i+1] == nums[i]+1)
                i++;
            if(start != nums[i])
                str += "->"+nums[i];
            res.add(str);
        }
        return res;   
    }
}

--------思路同上,  但是用了递归——————————

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new LinkedList<>();
        helper(nums, res, 0);
        return res;
    }
    public void helper(int[] nums, List<String> res, int i){
        int n = nums.length;
        if(i >= n)
            return;
        int start = nums[i];
        while(i+1<n && nums[i+1] == nums[i] + 1){
            i++;
        }
        int end  = nums[i];
        if(start == end)
            res.add("" + start);
        else
            res.add( "" + start + "->" + end);
        helper(nums,res, i+1);
    }
}
 



Mistakes:





Shortest Palindrome !!!!!!

Q:
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd"
A:
首先用最简单的方法逐个测试。 结果LTE
然后测试Rabin-Karper方法。







Mistakes:




222. Count Complete Tree Nodes (Easy)

Given the root of a complete binary tree, return the number of the nodes in the tree.

According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Design an algorithm that runs in less than O(n) time complexity.

 

Example 1:

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

Example 2:

Input: root = []
Output: 0

Example 3:

Input: root = [1]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5 * 104].
  • 0 <= Node.val <= 5 * 104
  • The tree is guaranteed to be complete.
A:
----------------------Solution 2 ----------------------
如果从某节点一直向左的高度 = 一直向右的高度, 那么以该节点为root的子树一定是complete binary tree. 而 complete binary tree的节点数,可以用公式算出 2^h - 1. 如果高度不相等, 则递归调用 return countNode(left) + countNode(right) + 1.  复杂度为O(h^2)  
 public class Solution {  
    public int countNodes(TreeNode root) {  
        if(root==null) return 0;  
          
        int l = getLeft(root) + 1;  
        int r = getRight(root) + 1;  
          
        if(l==r) {  
            return (2<<(l-1)) - 1;  
        } else {  
            return countNodes(root.left) + countNodes(root.right) + 1;  
        }  
    }  
      
    private int getLeft(TreeNode root) {  
        int count = 0;  
        while(root.left!=null) {  
            root = root.left;  
            ++count;  
        }  
        return count;  
    }  
      
    private int getRight(TreeNode root) {  
        int count = 0;  
        while(root.right!=null) {  
            root = root.right;  
            ++count;  
        }  
        return count;  
    }  
}  


***********上面的是每次查询了最左边和最右边的高度. 还不够好************


********     3rd pass,   每次对比左右子树的高度   如果相等, 则左边的为full bi nary tree **** 否则,右边的也是full binary tree 但是少了一层*****

/**
* 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:
int countNodes(TreeNode* root) {
if(!root)
return 0;
int hLeft = getHeight(root->left);
int hRight = getHeight(root->right);
if( hRight == hLeft){ //right child height == left child height
return (1<< hLeft) + countNodes(root->right);
}else{
return (1 << hLeft-1) + countNodes(root->left);
}
}
private:
int getHeight(TreeNode* root){ // get height for complete tree, just goes down to the left most node
if(!root)
return 0;
return 1 + getHeight(root->left);
}
};


上面的需要计算2次高度, 也是浪费。 因为左边的只需要计算一次就可以了
class Solution {
public:
int countNodes(TreeNode* root) {
return countNodesWithDepth(root, getHeight(root));
}

private:
int countNodesWithDepth(TreeNode* root, int height){
if(!root)
return 0;
if( getHeight(root->right) == height-1){ //right child height == left child height
return (1 << height-1) + countNodesWithDepth(root->right, height-1);
}else{
return (1 << height-2) + countNodesWithDepth(root->left, height-1);
}
}
int getHeight(TreeNode* root){ // get height for complete tree, just goes down to the left most node
if(!root)
return 0;
return 1 + getHeight(root->left);
}
};
但是,理论上是少算了一次,但是LC上并没有速度的改进,反而内存稍微增加了点儿。


Mistakes:
需要用 移位运算, 如果用Math.pow(a,b)的话,会超时