Wednesday, December 9, 2015

LeetCode [315] Count of Smaller Numbers After Self

 315. Count of Smaller Numbers After Self

Hard

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

 

Example 1:

Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

 

Constraints:

  • 0 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
//C++: 680ms  Sort from the end
class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {
        int n = nums.size();
        vector<int> ret(n, 0);
        for(int i=n-2; i>=0; --i){
            int t = nums[i];
            int j;
            for(j = i+1; j<n; ++j){
                if(nums[j]>=t) break;
            }
            nums.insert(nums.begin()+j, t);
            nums.erase(nums.begin()+i);
            ret[i] = j-i-1;
        }
        return ret;
    }
};
]]></script>
<script class="brush: js" type="syntaxhighlighter"><![CDATA[
//C++: 104ms  binary search
class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {     
     int n = nums.size();
     vector<int> ret(n,0);
     for(int i=n-2; i>=0; --i){
         int l = i+1, r = n-1, m;
         while(l<=r){
          m = (l+r)/2;
          if((nums[m]>=nums[i] && nums[m-1]<nums[i])){
              break;
          }else if(nums[m]>=nums[i]){
              r = m-1;
          }else{
              l = m+1;
          }
         }
         if(r<=i) m = i+1;
         if(l>=n) m = n;
         nums.insert(nums.begin()+m, nums[i]);
         nums.erase(nums.begin()+i);
         ret[i] = m-(i+1);
     }
 return ret;
    }
};
]]></script>
<script class="brush: js" type="syntaxhighlighter"><![CDATA[
//C++: 100ms merge sort
class Solution {
    vector<int> numbers;
    vector<int> ret;
public:

    vector<int> merge(vector<int> leftIndices, vector<int> rightIndices){
        int szl = leftIndices.size();
        int szr = rightIndices.size();
        int i = 0, j = 0, cnt = 0;
        vector<int> sortedIndices;
        while(i<szl && j<szr){
            if(numbers[leftIndices[i]]<=numbers[rightIndices[j]]){
                sortedIndices.push_back(leftIndices[i]);
                ret[leftIndices[i]] += cnt;
                i++;
            }else{
                sortedIndices.push_back(rightIndices[j]);
                j++;
                cnt++;
            }
        }
        while(i<szl){
            sortedIndices.push_back(leftIndices[i]);
            ret[leftIndices[i]] += cnt;
            i++;
        }
        while(j<szr){
            sortedIndices.push_back(rightIndices[j]);
            j++;
        }
        return sortedIndices;
    }
    void divide(vector<int> &indices){
        int n = indices.size();
        if(n<2) return;
        int mid = n/2;
        vector<int> left(indices.begin(), indices.begin()+mid);
        vector<int> right(indices.begin()+mid, indices.end());
        divide(left);
        divide(right);
        indices = merge(left, right);
    }

    vector<int> countSmaller(vector<int>& nums) {
        numbers = nums;
        int sz = nums.size();
        ret.resize(sz, 0);
        vector<int> indices(sz);
        for(int i=0; i<sz; ++i){
            indices[i] = i;
        }
        divide(indices);
        return ret;
    }
};
//Java
class Solution {
    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        List<Integer> list = new ArrayList<Integer>();
        for(int v:nums) list.add(v);
        List<Integer> counts = new ArrayList<Integer>(n);
        for(int i=0; i<n; ++i) counts.add(0);
        //sort nums from right to left;
        for(int i=n-2; i>=0; --i){
            int l = i+1, r = n-1;
            while(l<r){
                int m = (l+r)/2;
                if(list.get(m)<list.get(i)){
                    l = m+1;
                }else{
                    r = m;
                }
            }
            if(list.get(l)<list.get(i)){
                l = n;
            }
            list.add(l, list.get(i));
            list.remove(i);
            counts.set(i, l-i-1);
        }
        return counts;
    }
}

Tuesday, December 8, 2015

LeetCode [314] Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Examples 1:
Input: [3,9,20,null,null,15,7]

   3
  /\
 /  \
 9  20
    /\
   /  \
  15   7 

Output:

[
  [9],
  [3,15],
  [20],
  [7]
]
Examples 2:
Input: [3,9,8,4,0,1,7]

     3
    /\
   /  \
   9   8
  /\  /\
 /  \/  \
 4  01   7 

Output:

[
  [4],
  [9],
  [3,0,1],
  [8],
  [7]
]
Examples 3:
Input: [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5)

     3
    /\
   /  \
   9   8
  /\  /\
 /  \/  \
 4  01   7
    /\
   /  \
   5   2

Output:

[
  [4],
  [9,5],
  [3,0,1],
  [8,2],
  [7]
]
 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
/**
 * 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:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        int l = 0, r = 0;
        vector<vector<int>> ret;
        if(!root) return ret;
        
        ret.resize(1);
        queue<pair<TreeNode*, int>> que;//node. column index
        que.push(make_pair(root, 0));
        while(!que.empty())
        {
            TreeNode *node = que.front().first;
            int index = que.front().second;
            que.pop();
            if(index<l)
            {
                l--;
                ret.insert(ret.begin(), vector<int>());
            }
            else if(index>r)
            {
                r++;
                ret.insert(ret.end(), vector<int>());
            }
            ret[index-l].push_back(node->val);
            if(node->left) que.push(make_pair(node->left, index-1));
            if(node->right) que.push(make_pair(node->right, index+1));
        }
        return ret;
    }
};

LeetCode [313] Super Ugly Number

Ref
[1] https://leetcode.com/problems/super-ugly-number/

Sunday, December 6, 2015

LeetCode [312] Burst Balloons

312. Burst Balloons
Hard

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note:

  • You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
  • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

Input: [3,1,5,8]
Output: 167 
Explanation: nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
             coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167

 =============

Eg.
nums = 3  1  5  8
                                     0  1  2  3  4  5
after extended nums = 1  3  1  5  8  1

bottom up

0  1  2  3  4  5
1  3  1  5  8  1
step 1: burst balloon 2 => 3*1*5 = 15 => dp[2][2] = dp[2][1]+dp[3][2]+15 = 15


0  1   3  4  5
1  3  1  5  8  1
step 2: burst balloon 3 => 3*5*8 = 120 => dp[2][3] = dp[2][2]+dp[4][3]+120 = 135


0  1  2  3  4  5
1  3  1  5  8  1
step 1: burst balloon 1 => 1*3*8= 24 => dp[1][3] = dp[1][0]+dp[2][3]+24 = 159

0  1  2  3  4  5
1  3  1  5  8  1
step 1: burst balloon 4 => 1*8*1 = 8 => dp[1][4] = dp[1][3]+dp[5][4]+8 = 167


 Ref
[1] https://leetcode.com/problems/burst-balloons/
[2] https://leetcode.com/discuss/72186/c-dynamic-programming-o-n-3-32-ms-with-comments
 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
//C++: TLE
class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int n = nums.size();
        if(n==0) return 0;
        int ret = 0;
        for(int i=0; i<n; ++i){
            int tmp = (i==0?1:nums[i-1])*nums[i]*(i==n-1?1:nums[i+1]);
            vector<int> nums1 = nums;
            nums1.erase(nums1.begin()+i);
            tmp += maxCoins(nums1);
            ret = max(ret, tmp);
        }
        return ret;
    }
};
class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int n = nums.size();
        nums.insert(nums.begin(), 1);
        nums.insert(nums.end(), 1);
        //can be further optimized by removing all zeros

        //dp[s][e] is max coins by bursting all balloons from s to e
        vector<vector<int>> dp(n+2, vector<int>(n+2, 0));
        for(int s = n; s>0; --s){
            for(int e = s; e<=n; ++e){
                int bestCoins = 0;
                for(int i = s; i<=e; ++i){
                    //coins is the max coins when balloon i is the last balloon 
                    int coins = dp[s][i-1] + dp[i+1][e] + nums[s-1]*nums[i]*nums[e+1];
                    bestCoins = max(bestCoins, coins);
                }
                dp[s][e] = bestCoins;
            }
        }

        return dp[1][n];
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int maxCoins(int[] nums) {
        int n = nums.length;
        int[] numsExt = new int[n+2];
        Arrays.fill(numsExt, 1);
        for(int i=1; i<=n; ++i) numsExt[i] = nums[i-1];

        int[][] dp = new int[n+2][n+2];
        for(int s=n; s>0; --s){
            for(int e = s; e<=n; ++e){
                int bestCoins = 0;
                for(int i=s; i<=e; ++i){
                    int coins = dp[s][i-1] + dp[i+1][e] + numsExt[s-1]*numsExt[i]*numsExt[e+1];
                    bestCoins = Math.max(bestCoins, coins);
                }
                dp[s][e] = bestCoins;
            }
        }
        return dp[1][n];
    }
}

Friday, December 4, 2015

LeetCode [311] Sparse Matrix Multiplication

Given two sparse matrices A and B, return the result of AB.
You may assume that A's column number is equal to B's row number.
Example:
Input:

A = [
  [ 1, 0, 0],
  [-1, 0, 3]
]

B = [
  [ 7, 0, 0 ],
  [ 0, 0, 0 ],
  [ 0, 0, 1 ]
]

Output:

     |  1 0 0 |   | 7 0 0 |   |  7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
                  | 0 0 1 |

 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
class Solution {
public:
    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
        unordered_map<int, unordered_set<int>> A1, B1;
        int ma = A.size(), na = A[0].size();
        int mb = B.size(), nb = B[0].size();

        for(int i=0; i<ma; ++i){
            for(int j=0; j<na; ++j){
                if(A[i][j]){
                    A1[i].insert(j);
                }
            }
        }

        for(int j=0; j<nb; ++j){
            for(int i=0; i<mb; ++i){
                if(B[i][j]){
                    B1[j].insert(i);
                }
            }
        }

        vector<vector<int>> ret(ma, vector<int>(nb, 0));
        for(int i=0; i<ma; ++i){
            for(int j=0; j<nb; ++j){
                int s = 0;
                if(A1.count(i) && B1.count(j)){
                    for(auto k:A1[i]){
                        if(B1[j].count(k)){
                            s += A[i][k]*B[k][j];
                        }
                    }
                }
                ret[i][j] = s;
            }
        }

        return ret;
    }
};
//Java
class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int am = A.length, an = A[0].length;
        int bm = B.length, bn = B[0].length;
        List<Map<Integer, Integer>> mapA = new ArrayList<Map<Integer, Integer>>(am);
        List<Map<Integer, Integer>> mapB = new ArrayList<Map<Integer, Integer>>(bn);

        for(int i=0; i<am; ++i){
            mapA.add(new HashMap<>());
            for(int j=0; j<an; ++j){
                if(A[i][j]!=0){
                    mapA.get(i).put(j, A[i][j]);
                }
            }
        }

        for(int j=0; j<bn; ++j){
            mapB.add(new HashMap<>());
            for(int i=0; i<bm; ++i){
                if(B[i][j]!=0){
                    mapB.get(j).put(i, B[i][j]);
                }
            }
        }

        int[][] ret = new int[am][bn];
        for(int i=0; i<am; ++i){
            for(int j=0; j<bn; ++j){
                int s = 0;
                for(Map.Entry<Integer, Integer> e : mapA.get(i).entrySet()){
                    int k = e.getKey(), v = e.getValue();
                    if(mapB.get(j).containsKey(k)){
                        s += v*mapB.get(j).get(k);
                    }
                }
                ret[i][j] = s;
            }
        }
        return ret;
    }
}

Saturday, November 28, 2015

LeetCode [310] Minimum Height Trees

Ref
[1] https://leetcode.com/problems/minimum-height-trees/
OJ
[2] https://leetcode.com/discuss/71656/c-solution-o-n-time-o-n-space

Tuesday, November 24, 2015

LeetCode [309] Best Time to Buy and Sell Stock with Cooldown

Ref
[1] https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
OJ
[2] https://leetcode.com/discuss/71354/share-my-thinking-process