Friday, September 4, 2020

LeetCode [950] Reveal Cards In Increasing Order

 950. Reveal Cards In Increasing Order

Medium

In a deck of cards, every card has a unique integer.  You can order the deck in any order you want.

Initially, all the cards start face down (unrevealed) in one deck.

Now, you do the following steps repeatedly, until all cards are revealed:

  1. Take the top card of the deck, reveal it, and take it out of the deck.
  2. If there are still cards in the deck, put the next top card of the deck at the bottom of the deck.
  3. If there are still unrevealed cards, go back to step 1.  Otherwise, stop.

Return an ordering of the deck that would reveal the cards in increasing order.

The first entry in the answer is considered to be the top of the deck.

 

Example 1:

Input: [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation: 
We get the deck in the order [17,13,11,2,3,5,7] (this order doesn't matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom.  The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom.  The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom.  The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom.  The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom.  The deck is now [13,17].
We reveal 13, and move 17 to the bottom.  The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.

 

Note:

  1. 1 <= A.length <= 1000
  2. 1 <= A[i] <= 10^6
  3. A[i] != A[j] for all i != j
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public int[] deckRevealedIncreasing(int[] deck) {
        Arrays.sort(deck);
        int n = deck.length;
        Queue<Integer> q = new LinkedList<>();
        for(int i=0; i<n; ++i) q.add(i);
        int[] ret = new int[n];
        int cur = 0;

        while(!q.isEmpty()){
            ret[q.poll()] = deck[cur++];
            if(!q.isEmpty()) q.add(q.poll());
        }

        return ret;
    }
}

LeetCode [1007] Minimum Domino Rotations For Equal Row

 1007. Minimum Domino Rotations For Equal Row

Medium

In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino.  (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

We may rotate the i-th domino, so that A[i] and B[i] swap values.

Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.

If it cannot be done, return -1.

 

Example 1:

Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation: 
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.

Example 2:

Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
Output: -1
Explanation: 
In this case, it is not possible to rotate the dominoes to make one row of values equal.

 

Note:

  1. 1 <= A[i], B[i] <= 6
  2. 2 <= A.length == B.length <= 20000
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int minDominoRotations(int[] A, int[] B) {
        int n = A.length;
        int ret = n+1;;
        for(int i=1; i<=6; ++i)
        {
            int countA = 0, countB = 0, countAB = 0;
            for(int j=0; j<n; ++j){
                if(A[j]==i) countA++;
                if(B[j]==i) countB++;
                if(A[j]==i && B[j]==i) countAB++;
                if(countA + countB - countAB == n){
                    ret = Math.min(ret, Math.min(n-countA, n-countB));
                }
            }
        }
        return ret == n+1 ? -1 : ret;
    }
}

LeetCode [1011] Capacity To Ship Packages Within D Days

 1011. Capacity To Ship Packages Within D Days

Medium

A conveyor belt has packages that must be shipped from one port to another within D days.

The i-th package on the conveyor belt has a weight of weights[i].  Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.

 

Example 1:

Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation: 
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10

Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. 

Example 2:

Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation: 
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4

Example 3:

Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation: 
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1

 

Constraints:

  • 1 <= D <= weights.length <= 50000
  • 1 <= weights[i] <= 500
 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 {
    public int shipWithinDays(int[] weights, int D) {
        int l = 0, r = 0;
        for(int w:weights)
        {
            l = Math.max(l, w);
            r += w;
        }

        while(l<r){
            int cap = l+(r-l)/2;//
            int need = 1;
            int cur = 0;
            for(int w:weights)
            {
                if(cur+w<=cap)
                {
                    cur += w;
                }else{
                    need++;
                    cur = w;
                }
            }
            if(need>D){
                l = cap+1;
            }else{
                r = cap;
            }
        }

        return l;
    }
}

LeetCode [1021] Remove Outermost Parentheses

 1021. Remove Outermost Parentheses

Easy

A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.  For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

 

Example 1:

Input: "(()())(())"
Output: "()()()"
Explanation: 
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".

Example 2:

Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation: 
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".

Example 3:

Input: "()()"
Output: ""
Explanation: 
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".

 

Note:

  1. S.length <= 10000
  2. S[i] is "(" or ")"
  3. S is a valid parentheses string
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public String removeOuterParentheses(String S) {
        StringBuilder s = new StringBuilder();
        int opened = 0;
        for(char c: S.toCharArray())
        {
            if(c=='(' && opened++>0) s.append(c);
            if(c==')' && opened-->1) s.append(c);
        }
        return s.toString();
    }
}

LeetCode [1031] Maximum Sum of Two Non-Overlapping Subarrays

 1031. Maximum Sum of Two Non-Overlapping Subarrays

Medium

Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M.  (For clarification, the L-length subarray could occur before or after the M-length subarray.)

Formally, return the largest V for which V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) and either:

  • 0 <= i < i + L - 1 < j < j + M - 1 < A.length, or
  • 0 <= j < j + M - 1 < i < i + L - 1 < A.length.

 

    Example 1:

    Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
    Output: 20
    Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
    

    Example 2:

    Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
    Output: 29
    Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.
    

    Example 3:

    Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
    Output: 31
    Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with length 3.
    

     

    Note:

    1. L >= 1
    2. M >= 1
    3. L + M <= A.length <= 1000
    4. 0 <= A[i] <= 1000
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    class Solution {
        public int maxSumTwoNoOverlap(int[] A, int L, int M) {
            int n = A.length;
            for(int i=1; i<n; ++i) A[i] += A[i-1];
    
            int ret = A[L+M-1], Lmax = A[L-1], Mmax = A[M-1];
            for(int i=L+M; i<n; ++i)
            {
                Lmax = Math.max(Lmax, A[i-M] - A[i-L-M]);
                Mmax = Math.max(Mmax, A[i-L] - A[i-L-M]);
                ret = Math.max(ret, Math.max(Lmax + A[i] - A[i-M], Mmax + A[i] - A[i-L]));
            }
            return ret;
        }
    }
    

    LeetCode [1099] Two Sum Less Than K

     1099. Two Sum Less Than K

    Easy

    Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1.

     

    Example 1:

    Input: A = [34,23,1,24,75,33,54,8], K = 60
    Output: 58
    Explanation: 
    We can use 34 and 24 to sum 58 which is less than 60.
    

    Example 2:

    Input: A = [10,20,30], K = 15
    Output: -1
    Explanation: 
    In this case it's not possible to get a pair sum less that 15.
    

     

    Note:

    1. 1 <= A.length <= 100
    2. 1 <= A[i] <= 1000
    3. 1 <= K <= 2000
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Solution {
        public int twoSumLessThanK(int[] A, int K) {
            Arrays.sort(A);
            int l = 0, r = A.length-1, max = -1;
    
            while(l<r)
            {
                int res = A[l] + A[r];
                if(res<K){
                    max = Math.max(max, res);
                    l++;
                }else{
                    r--;
                }
            }
            return max;
        }
    }
    

    LeetCode [1110] Delete Nodes And Return Forest

     1110. Delete Nodes And Return Forest

    Medium

    Given the root of a binary tree, each node in the tree has a distinct value.

    After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

    Return the roots of the trees in the remaining forest.  You may return the result in any order.

     

    Example 1:

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

     

    Constraints:

    • The number of nodes in the given tree is at most 1000.
    • Each node has a distinct value between 1 and 1000.
    • to_delete.length <= 1000
    • to_delete contains distinct values between 1 and 1000.
     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
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        Set<Integer> deleted;
        List<TreeNode> ret;
        public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
            deleted = new HashSet<>();
            ret = new ArrayList<>();
            for(int i : to_delete){
                deleted.add(i);
            }
            helper(root, true);
            return ret;
        }
        
        TreeNode helper(TreeNode node, boolean isRoot){
            if(node==null){
                return null;
            }
            
            boolean isDeleted = deleted.contains(node.val);
            if(isRoot && !isDeleted){
                ret.add(node);
            }
            
            node.left = helper(node.left, isDeleted);
            node.right = helper(node.right, isDeleted);
            
            return isDeleted ? null : node;
        }
    }