[Leetcode Weekly Contest]180

Links: LeetCode

[Leetcode] 5356. Lucky number in the matrix

To a \ (m * n \) matrix, the digital matrix varies. Please return all lucky number in the matrix in any order.
Fortunately, the number of elements simultaneously refers to two of the following conditions are satisfied in the matrix:

  • The smallest of all the elements in the same row
  • All elements in the same column the maximum
     
    Example 1:
    Input: matrix = [[3,7,8], [9,11,13], [15,16,17]]
    Output: [15]
    Explanation: 15 is the only the lucky number, because it is the minimum of its row and column is the maximum value lies.

Solutions to this problem of violence, cyclic judgment matrix rows (columns) of the minimum (large) value.

class Solution:
    def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
        n,m = len(matrix),len(matrix[0])
        res1 = set()
        res2 = set()
        for i in range(n):
            min_num = min(matrix[i])
            res1.add(min_num)
        for j in range(m):
            nums = [x[j] for x in matrix]
            max_num = max(nums)
            res2.add(max_num)
        res = list(res1 & res2)
        return res

[Leetcode] 1381. Designed to support a stack increment operation

You design a stack of the following operating support.

  • Implement a custom stack class CustomStack:
  • CustomStack (int maxSize): maxSize initialized with the object, the number of elements is maxSize stack can accommodate up of, after the growth of the stack is not supported in maxSize Push.
  • void push (int x): If the stack is not yet grown to maxSize, x will be added to the top of the stack.
  • int pop (): returns the value -1 if the top of the stack, or a stack is empty.
  • void inc (int k, int val): bottom of the stack of k elements have increased val. If the total number of elements in the stack is less than k, then all elements in the stack are increased val.
     

Example:
Input:
\ ([ "CustomStack", "Push", "Push", "POP", "Push", "Push", "Push", "INCREMENT", "INCREMENT", "POP", "POP" , "POP", "POP"] \)
\ ([[. 3], [. 1], [2], [], [2], [. 3], [. 4], [5,100], [2,100], [ ], [], [], []] \)
output:
\ ([null, null, null, 2, null, null, null, null, null, 103,202,201, -1] \)
explained:
CustomStack customStack = new new CustomStack (3); // stacks are empty []
customStack.push (. 1); // stack becomes [. 1]
customStack.push (2); // stack becomes [. 1, 2]
customStack.pop (); // returns 2 -> 2 returns the top of the stack, the stack becomes [1]
customStack.push (2); // stack becomes [1, 2]
customStack.push (. 3); // stack becomes [1 , 2, 3]
customStack.push (. 4); // stack is again [1, 2, 3], can add other elements to make the stack size becomes. 4
customStack.increment (5, 100); // stack becomes [101, 102, 103]
customStack.increment (2, 100); // stack becomes [201, 202, 103]
customStack.pop (); // Returns 103 -> 103 returns the top of the stack, the stack becomes [201, 202]
customStack. pop (); // returns 202 -> 202 returns the top of the stack, the stack becomes [201]
customStack.pop (); // returns 201 -> 201 returns the top of the stack, the stack becomes []
customStack.pop (); // -1 -> stack is empty, -1

After find out the rules, simple idea is to create a stack, each increment of time to traverse the stack can be accumulated. A better method, in fact, not all of the accumulated number of the k only needs to record the number of k-1, simultaneously in the pop accumulated when the accumulated value will be recorded before an element . This can greatly reduce the complexity of the accumulated time.
Finally, note that k may be greater than the size of the stack, it is necessary to judge k.

class CustomStack:
    def __init__(self, maxSize: int):
        self.stack = []
        self.maxSize = maxSize
        self.size = 0


    def push(self, x: int) -> None:
        if self.size ==self.maxSize:
            return
        else:
            self.stack.append([x,0])
            self.size += 1


    def pop(self) -> int:
        if not self.size:return -1
        val,inc = self.stack.pop()
        self.size -= 1
        if self.size:
            self.stack[-1][1] += inc
        return val+inc


    def increment(self, k: int, val: int) -> None:
        k = min(k,self.size)
        # 防止k为0
        if k:
            self.stack[k-1][1] += val



# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)```

[Leetcode] 1382. The balanced binary search tree becomes

Give you a binary search tree, please return after a balanced binary search tree, the newly generated tree node should have the same value as the original tree.
If a binary search tree, the two sub-tree for each node height difference of not more than 1, we say tree binary search tree is balanced. If there are multiple constructors, please return any.

Gets an array traversal through the sequence, and then rebuild the balanced binary search tree can be.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def balanceBST(self, root: TreeNode) -> TreeNode:
        nums = []
        self.dfs(root,nums)
        return self.reBuildBST(nums)

    def dfs(self,root,nums):
        if not root:
            return
        self.dfs(root.left,nums)
        nums.append(root.val)
        self.dfs(root.right,nums)

    def reBuildBST(self,nums):
        if not nums:return
        mid = len(nums)//2
        root = TreeNode(nums[mid])
        root.left,root.right = self.reBuildBST(nums[:mid]),self.reBuildBST(nums[mid+1:])
        return root

[Leetcode] 1383. The maximum value of team performance

Companies are numbered from 1 to n, n engineer, you two arrays Efficiency and speed, where \ (speed [i] \) and \ (Efficiency [i] \) representing the speed and efficiency of the i-th engineers. Please return the maximum value of team performance most k engineers, because the answer may be large, please return the results to \ (10 ^ 9 + 7 \) the result of more than take.
Team performance value is defined as: a team "All engineers speed and" multiplied by their "minimum efficiency values."

Example 1:
Input: \ (n-=. 6, Speed = [2,10,3,1,5,8], Efficiency = [5,4,3,9,7,2], K = 2 \)
Output: 60
explains:
we choose engineers 2 (speed = 10 and efficiency = 4) and engineers 5 (speed = 5 and efficiency = 7). Their performance is team performance = (10 + 5) * min (4, 7) = 60.
Example 2:
Input: \ (n-=. 6, Speed = [2,10,3,1,5,8], Efficiency = [5,4,3,9,7,2], K =. 3 \)
Output: 68
explanation:
this example is the same as the first example, except that k = 3. We can choose an engineer, two engineers and a team of engineers to 5 maximum performance value. Performance value performance = (2 + 10 + 5 ) * min (5, 4, 7) = 68.
Example 3:
Input: \ (n-=. 6, Speed = [2,10,3,1,5,8], Efficiency = [5,4,3,9,7,2], K =. 4 \)
Output: 72

A trick is to require a certain value by a maximum (minimum) value can be the best time to optimize the time complexity by partial decomposition. The difficulty is how to traverse the array solution locally optimal solution. Here, we can be considered to be a local solution: seek must take the current element and the current element is the minimum value of the case, the optimal solution is. Finally, find the maximum value of the local solution, i.e., a global optimal solution.
So the core idea is: first, to make efficiency for all engineers descending order, one at a time efficiency value selected as \ (the X-\) , from an efficiency greater than (x \) \ engineers (ie engineers on the left side) to find speed the largest up to \ (K-1 \) engineer to calculate the value of their team performance.
In order to easily find the efficiency is greater than \ (X \) is the maximum speed \ (K-1 \) engineers, using a capacity \ (K-1 \) small to maintain the top of the stack.

import heapq
class Solution:
    def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
        nums = list(zip(speed,efficiency))
        nums.sort(key = lambda x:-x[1])
        res = sum_ = 0
        min_heap = []
        for i in range(len(nums)):
            eff,spp = nums[i]
            res = max(res,(eff+sum_)*spp)
            if i<k-1:
                heapq.heappush(min_heap,eff)
                sum_ += eff
            elif min_heap and eff > min_heap[0]:
                num = heapq.heapreplace(min_heap,eff)
                sum_ += eff-num
        return res%(10**9+7)

Guess you like

Origin www.cnblogs.com/hellojamest/p/12503073.html