Wednesday, November 11, 2015

308. Range Sum Query 2D - Mutable --------H

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10

Note:

  1. The matrix is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRegion function is distributed evenly.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.
A:

就是建立一个2D数组。保存从原点到该位置的和
 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
class NumMatrix {
public:
    NumMatrix(vector<vector<int>>& matrix) {
        m = matrix.size();
        if(m==0){
            return;
        }
        n = matrix[0].size();
        M = vector<vector<long>>(m+1,vector<long>(n+1,0));
        for(int i =1;i<=m;i++){
            for(int j = 1; j<=n; j++){
                M[i][j] = matrix[i-1][j-1] + M[i-1][j]+M[i][j-1] - M[i-1][j-1];
            }
        }
    }
    
    void update(int row, int col, int val) {
        long orig = M[row+1][col+1] - M[row][col+1] - M[row+1][col] + M[row][col];
        long diff = val - orig;
        for(int i = row+1; i<=m;i++){
            for(int j = col+1; j<=n; j++){
                M[i][j] += diff;
            }
        }
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        long downRight = M[row2+1][col2+1];
        long topRight = M[row1][col2+1];
        long downLeft = M[row2+1][col1];
        long topLeft = M[row1][col1];
        return int( downRight - topRight - downLeft + topLeft  );
    }
private:
    vector<vector<long>> M;
    int m=0, n = 0;
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * obj->update(row,col,val);
 * int param_2 = obj->sumRegion(row1,col1,row2,col2);
 */

Note:
注意的一点是:求的row1 -1 , col-1的交叉
因为在constructor中没有检测matrix == null,耽误了1个小时,╮(╯▽╰)╭



Bulls and Cows

Q:
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
For example:
Secret number:  "1807"
Friend's guess: "7810"
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 01 and 7.)
Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return "1A3B".
Please note that both secret number and friend's guess may contain duplicate digits, for example:
Secret number:  "1123"
Friend's guess: "0111"
In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B".
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

A:
 就是简单的对比,数即可(首先数出完全匹配的)再用HashMap,找到所有的secret中出现的 。 再便利guess,确认即可

public class Solution {
    public String getHint(String secret, String guess) {
        int A = 0,AB =0;
        Map<Character,Integer> map = new HashMap();
        for(int i =0;i<secret.length();i++){
            char ch1 = secret.charAt(i);
            if( ch1==guess.charAt(i))
                A++;
            if(map.containsKey(ch1)){
                map.put(ch1,map.get(ch1)+1);
            }else{
                map.put(ch1,1);
            }
        }
        // check guess string for new 
        for(int i =0;i<secret.length();i++){
            char ch = guess.charAt(i);
            if(map.containsKey(ch)){
                AB++;
                map.put(ch,map.get(ch)-1);
                if(map.get(ch)==0)
                    map.remove(ch);
            }
        }
        return ""+A+"A"+(AB-A)+"B";
    }
}



*************************利用0-9这个特性,创建2个数组*****************

public class Solution {
    public String getHint(String secret, String guess) {
        int A = 0, AB=0;
        int C1[] = new int[10];
        int C2[] = new int[10];
        for(int i =0;i<secret.length();i++){
            char ch1 = secret.charAt(i);
            char ch2 = guess.charAt(i);
            if(ch1==ch2)
                A++;
            C1[ch1-'0']++;
            C2[ch2-'0']++;
        }
        for(int i =0;i<10;i++)
            AB+= Math.min(C1[i],C2[i]);
        return ""+A+"A"+(AB-A)+"B";
    }
}












303. Range Sum Query - Immutable -E

Q:
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.
A:

class NumArray {
public:
    NumArray(vector<int>& nums) {
        int sum = 0;
        for(auto v: nums)
        {
            sum += v;
            V.push_back(sum);
        }
    }
    
    int sumRange(int i, int j) {
        int pre = i>0? V[i-1] : 0;
        return V[j] - pre;
    }
private:
    vector<int> V; // assume no overflow on int 
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * int param_1 = obj->sumRange(i,j);
 */

Tuesday, November 10, 2015

Add Digits

Q:
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
             Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?

A:

----------递归+循环
class Solution {
public:
    int addDigits(int num) {
       
        while(num >= 10)
        {
            int res = 0;
            while(num > 0)
            {
                res += num %10;
                num /= 10;
            }
            num = res;
        }
        return num;
    }
};
-----------------每次进位的时候,其实都是在下次的值上增加了1—————————

public class Solution {
    public int addDigits(int num) {
        int s = 0;
        while(num !=0){
            s += num%10;
            if(s>=10)
                s = s%10  +1;
            num /= 10;
        }
        return s;
    }
}

***********************一行代码,的解法 *******************************
class Solution {
public:
    int addDigits(int num) {
       return 1+((num-1)%9);
    }
};
下面这个也是:

public int addDigits(int num) {
    return num == 0 ? 0 : (num % 9 == 0 ? 9 : num % 9);
}