Thursday, July 11, 2019

LeetCode [374] Guess Number Higher or Lower

We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
You call a pre-defined API guess(int num) which returns 3 possible results (-11, or 0):
-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!
Example :
Input: n = 10, pick = 6
Output: 6
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        long long l = 1, r = n;
        while(l<=r){
            long long m = (l+r)/2;
            int g = guess(m);
            if(g==0) return m;
            if(g<0) r = m-1;
            if(g>0) l = m+1;
        }
        return -1;
    }
};

Wednesday, July 10, 2019

LeetCode [292] Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
Example:
Input: 4
Output: false 
Explanation: If there are 4 stones in the heap, then you will never win the game;
             No matter 1, 2, or 3 stones you remove, the last stone will always be 
             removed by your friend.
1
2
3
4
5
6
class Solution {
public:
    bool canWinNim(int n) {
        return n % 4 != 0 ;
    }
};

Tuesday, July 9, 2019

LeetCode_Summary [Stack]

LeetCode [975] Odd Even Jump

You are given an integer array A.  From some starting index, you can make a series of jumps.  The (1st, 3rd, 5th, ...) jumps in the series are called odd numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps.
You may from index i jump forward to index j (with i < j) in the following way:
  • During odd numbered jumps (ie. jumps 1, 3, 5, ...), you jump to the index j such that A[i] <= A[j] and A[j] is the smallest possible value.  If there are multiple such indexes j, you can only jump to the smallest such index j.
  • During even numbered jumps (ie. jumps 2, 4, 6, ...), you jump to the index j such that A[i] >= A[j] and A[j] is the largest possible value.  If there are multiple such indexes j, you can only jump to the smallest such index j.
  • (It may be the case that for some index i, there are no legal jumps.)
A starting index is good if, starting from that index, you can reach the end of the array (index A.length - 1) by jumping some number of times (possibly 0 or more than once.)
Return the number of good starting indexes.

Example 1:
Input: [10,13,12,14,15]
Output: 2
Explanation: 
From starting index i = 0, we can jump to i = 2 (since A[2] is the smallest among A[1], A[2], A[3], A[4] that is greater or equal to A[0]), then we can't jump any more.
From starting index i = 1 and i = 2, we can jump to i = 3, then we can't jump any more.
From starting index i = 3, we can jump to i = 4, so we've reached the end.
From starting index i = 4, we've reached the end already.
In total, there are 2 different starting indexes (i = 3, i = 4) where we can reach the end with some number of jumps.
Example 2:
Input: [2,3,1,1,4]
Output: 3
Explanation: 
From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:

During our 1st jump (odd numbered), we first jump to i = 1 because A[1] is the smallest value in (A[1], A[2], A[3], A[4]) that is greater than or equal to A[0].

During our 2nd jump (even numbered), we jump from i = 1 to i = 2 because A[2] is the largest value in (A[2], A[3], A[4]) that is less than or equal to A[1].  A[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3.

During our 3rd jump (odd numbered), we jump from i = 2 to i = 3 because A[3] is the smallest value in (A[3], A[4]) that is greater than or equal to A[2].

We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.

In a similar manner, we can deduce that:
From starting index i = 1, we jump to i = 4, so we reach the end.
From starting index i = 2, we jump to i = 3, and then we can't jump anymore.
From starting index i = 3, we jump to i = 4, so we reach the end.
From starting index i = 4, we are already at the end.
In total, there are 3 different starting indexes (i = 1, i = 3, i = 4) where we can reach the end with some number of jumps.
Example 3:
Input: [5,1,3,4,2]
Output: 3
Explanation: 
We can reach the end from starting indexes 1, 2, and 4.
 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
class Solution {
public:
    int oddEvenJumps(vector<int>& A) {
        int N = A.size();
        if (N==0) return true;
        vector<int> upper(N, 0);//upper[i] = 1 if the first step from i jumps to a greater (or equal) number can reach the end eventually
        vector<int> lower(N, 0);//lower[i] = 1 if the first step from i jumps to a smaller (or equal) number can reach the end eventually
        upper[N-1] = lower[N-1] = 1;
        int ret = 1;

        //maintains the processes numbers in A from the end
        map<int, int> hash;//number, index
        hash[A[N-1]] = N-1;

        for(int i=N-2; i>=0; --i)
        {
            int k = A[i];
            auto itUpper = hash.lower_bound(k);
            auto itLower = hash.upper_bound(k);

            //found a number (itLower->first) greater than or equal to k
            if(itUpper != hash.end())
            {
                upper[i] = lower[itUpper->second];
                if(upper[i]) ret++;//first step must go upward.
            }

            //found a number (itLower->first) greater than k
            //(--itLower->first) must be smaller than or equal to k
            if(itLower != hash.begin())
            {
                lower[i] = upper[(--itLower)->second];
            }

            hash[A[i]] = i;
        }

        return ret;
    }
};

LeetCode [907] Sum of Subarray Minimums

Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
Since the answer may be large, return the answer modulo 10^9 + 7.

Example 1:
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.  Sum is 17.

Note:
  1. 1 <= A.length <= 30000
  2. 1 <= A[i] <= 30000
 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
class Solution
{
    const int mod = 1e9+7;
  public:
    int sumSubarrayMins(vector<int> &A)
    {
        stack<pair<int, int>> stk; //val, count(#subset(ending at val) with min(subset)==val)
        int sum = 0;
        int partialSum = 0;//sum of min(B) ending at a
        for (auto a : A)//consider all subsets ending at 'a'
        {
            int count = 1;//min({a})==a, so count = 1 
            while (!stk.empty() && a < stk.top().first)
            {
                pair<int, int> vc = stk.top();
                stk.pop();
                partialSum -= vc.first * vc.second;
                count += vc.second;
            }
            stk.push(pair<int, int>(a, count));
            partialSum += a * count;
            sum += partialSum;
            sum %= mod;
        }
        return sum;
    }
};

LeetCode [772] Basic Calculator III

Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .
The expression string contains only non-negative integers, +-*/operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].
Some examples:
"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12

 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
45
46
47
48
49
50
51
52
53
typedef long long ll;
class Solution {
    stack<int> nums;
    stack<char> ops;
    ll eval(){
        int op = ops.top();
        ops.pop();
        ll v2 = nums.top();
        nums.pop();
        ll v1 = nums.top();
        nums.pop();
        switch(op){
            case '+': return v1+v2;
            case '-': return v1-v2;
            case '*': return v1*v2;
            case '/': return v1/v2;
        }
        return 0;
    }
    bool op1first(char op1, char op2){
        return (op1=='*'||op1=='/')&&(op2=='+'||op2=='-');
    }
public:
    int calculate(string s) {
        ll val = 0;
        int n = s.size();
        for(int i=0; i<n; ++i){
            char c = s[i];
            if (c==' ') continue;
            if (isdigit(c)){
                val = val*10+(c-'0');
                if(i==n-1 || !isdigit(s[i+1])) {nums.push(val); val = 0;}
            }else{
                if(c=='(') ops.push(c);
                else if(c==')'){
                    while(!ops.empty() && ops.top()!='('){
                        nums.push(eval());
                    }
                    ops.pop();
                }else{//+-*/
                    while(!ops.empty() && op1first(ops.top(), c)){
                        nums.push(eval());
                    }
                    ops.push(c);
                }
            }
        }
        while(!ops.empty()){
            nums.push(eval());
        }
        return nums.top();
    }
};

Monday, July 8, 2019

LeetCode [739] Daily Temperatures

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
 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
class Solution {
    stack<int> stk;//index of decreasing temp
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        vector<int> ret(T.size());
        for(int i=0; i<T.size(); ++i){
            if(stk.empty()) stk.push(i);
            else{
                if(T[stk.top()]>=T[i]) stk.push(i);
                else{
                    while(!stk.empty() && T[stk.top()]<T[i]){
                        int t = stk.top();
                        stk.pop();
                        ret[t] = i-t;
                    }
                    stk.push(i);
                }
            }
        }
        while(!stk.empty()){
            ret[stk.top()] = 0;
            stk.pop();
        }
        return ret;
    }
};

Sunday, July 7, 2019

LeetCode [394] Decode String

Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
 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
class Solution {
    stack<int> stkk;
    stack<string> stks;
public:
    string decodeString(string s) {
        string cur;//inner-most string
        int n = s.size(), i = 0;
        while(i<n){
            char c = s[i];
            if(isdigit(c)){
                int k = 0;
                while(i<n && isdigit(s[i])){k = k*10+(s[i++]-'0');}
                stkk.push(k);
            }else if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
                i++;
                cur += c;
            }else if(c=='['){
                i++;
                stks.push(cur);
                cur = "";
            }else{//']'
                i++;
                int cnt = stkk.top();
                stkk.pop();
                string prev = stks.top();
                stks.pop();
                for(int j=0; j<cnt; ++j) prev+=cur;
                cur = prev;
            }
        }
        return cur;
    }
};

 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
//Java
class Solution {
    public String decodeString(String s) {
        int i = 0, n = s.length();
        Stack<String> stkW = new Stack<>();
        Stack<Integer> stkI = new Stack<>();
        int k = 0;
        StringBuilder w = new StringBuilder();
        while (i < n) {
            if (Character.isDigit(s.charAt(i))) {
                while (i < n && Character.isDigit(s.charAt(i))) {
                    k = k * 10 + (s.charAt(i++) - '0');
                }
                stkI.add(k);
                k = 0;
            } else if (Character.isAlphabetic(s.charAt(i))) {
                w.append(s.charAt(i++));
            } else if (s.charAt(i) == '[') {
                stkW.push(w.toString());
                w.setLength(0);
                i++;
            } else {//']'
                i++;
                int l = stkI.pop();
                String cur = w.toString();
                w = new StringBuilder(stkW.pop());
                for(int j=0; j<l; ++j){
                    w.append(cur);
                }
            }
        }
        return w.toString();
    }
}