LeetCode2020 176 Race Course Week

5340. Statistical orderly matrix of negative

Title Description

Topic Address: https://leetcode-cn.com/problems/count-negative-numbers-in-a-sorted-matrix/

给你一个 m * n 的矩阵 grid,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。 

Please statistics and returns  grid in a negative number.

 

Example 1:

Input: Grid = [[4,3,2, -1], [3,2,1, -1], [1,1, -1, -2], [-. 1, -1, -2, - 3]]
 output: 8
 explanation: matrix has 8 negative.

Example 2:

Input: Grid = [[3,2-], [1,0]]
 Output: 0

Example 3:

Input: Grid = [[. 1, -1], [-. 1, -1]]
 Output: 3

Example 4:

Input: Grid = [[-1]]
 Output: 1

 

prompt:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • -100 <= grid[i][j] <= 100

answer

Traverse the two-dimensional array, you can count the number of negative numbers.
The time complexity is: O ( n 2 ) O (n ^ 2)
space complexity: O ( 1 ) O (1)

Code

class Solution {
public:
    int countNegatives(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        int cnt = 0;
        for(int i = 0; i < m; ++i){
            for(int j = 0; j < n; ++j){
                if(grid[i][j] < 0){//统计负数的个数
                    ++cnt;
                }
            }
        }
        return cnt;
    }
};

Product number 5341. The last K

Title Description

Topic Address: https://leetcode-cn.com/problems/product-of-the-last-k-numbers/

请你实现一个「数字乘积类」ProductOfNumbers,要求支持下述两种方法:

1. add(int num)

  • The numbers  num added to the end face of the current list of numbers.

2. getProduct(int k)

  • Returns the current list of numbers, the final  k product of the digits.
  • You can assume that the current list is always at least contain knumbers.

Title ensure data: any time, any product of a sequence of consecutive numbers are 32-bit integers in the range, does not overflow.

 

Example:

Input:
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]

Output:
[Null, null, null, null, null, null, 20,40,0, zero, 32]

Explanation:
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3);        // [3]
productOfNumbers.add(0);        // [3,0]
productOfNumbers.add(2);        // [3,0,2]
productOfNumbers.add(5);        // [3,0,2,5]
productOfNumbers.add(4);        // [3,0,2,5,4]
productOfNumbers.getProduct (2); // returns 20. The last two digits of the product is 5 * 4 = 20
productOfNumbers.getProduct (3); // returns 40. The last three digits of the product is 2 * 5 * 4 = 40
productOfNumbers.getProduct (4); // returns 0. Last four digits of the product is 2 * 5 * 0 = 0 * 4
productOfNumbers.add(8);        // [3,0,2,5,4,8]
productOfNumbers.getProduct (2); // returns 32. The last two digits of the product is 4 * 8 = 32

 

prompt:

  • addAnd getProduct two operations add up to a total of no more than  40000 twice.
  • 0 <= num <= 100
  • 1 <= k <= 40000

Problem solution 1

When race week did not think, come up with a direct vector to store all the numbers, addfunction with push_backto achieve. Finally, the product of k elements from the beginning of the last element in the vector, will take up to k elements.

Time complexity is: O (n)
space complexity is: O (n)

Code 1

class ProductOfNumbers {
public:
    vector<int>vec;
    ProductOfNumbers() {
        
    }
    
    void add(int num) {
        vec.push_back(num);
    }
    
    int getProduct(int k) {
        int len = vec.size(), res = 1;
        for(int i = len - 1; i >= len - k; --i){
            res = res * vec[i];
        }
        return res;
    }
};

/**
 * Your ProductOfNumbers object will be instantiated and called as such:
 * ProductOfNumbers* obj = new ProductOfNumbers();
 * obj->add(num);
 * int param_2 = obj->getProduct(k);
 */

2 solution to a problem

Referring to LeetCode - circle , for the second question gives a lot of optimization algorithms. Limitations given in the title to be noted.

Title ensure data: any time, any product of a sequence of consecutive numbers are 32-bit integers in the range, does not overflow.
0 <= num <= 100

For a product of any continuous sequence of 32-bit integers are less than the range, only a maximum 31 indicates the sequence number is greater than 1 ( 2 31 1 2^{31} - 1 ), the other numbers are 0 and 1. It is possible to count the number with the prefix and 0-100 of the 101 number that appears in the sequence, where overhead space is 101 * n (n is the total length of the sequence). Calculate the product of the number of the last K, Just have to find out the number of times each number cnt num arise, c n t n u m = v e c [ n ] [ n u m ] v e c [ n k ] [ n u m ] cnt_ = {} Dec. whether [n] [whether] - Dec. [n - k] [num] , 0 appears on the final product is 0, 1 appears, is not a skip. Then to seek other digital product.

Here I introduce the idea of the plot prefix. The product of continuous digital storage array, met 0, clear the array recount. Finally, when the array length is less than K, the product of an 0, otherwise the total product divided by the product of the preceding elements.
Time complexity is: O (1)
the spatial complexity: O (n)

Code 2

class ProductOfNumbers {
public:
    vector<int>vec;
    ProductOfNumbers() {
        vec.clear();
        vec.push_back(1);
    }
    
    void add(int num) {
        if(num == 0){//遇到0,清空前缀积数组
            vec.clear();
            vec.push_back(1);
        }
        else{
            vec.push_back(vec.back() * num);
        }
    }  
    int getProduct(int k) {
        if(vec.size() - 1 < k){//数组长度不足K表示,最后K个数中存在0
            return 0;
        }
        else{
            return vec[vec.size() - 1] / vec[vec.size() - 1 - k];
        }
    }
};

/**
 * Your ProductOfNumbers object will be instantiated and called as such:
 * ProductOfNumbers* obj = new ProductOfNumbers();
 * obj->add(num);
 * int param_2 = obj->getProduct(k);
 */

The number of meetings attended 1353. Up

Topic Address: https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended/

Title Description

给你一个数组 events,其中 events[i] = [startDayi, endDayi] ,表示会议 i 开始于 startDayi ,结束于 endDayi 。

You can meet  one day in any of the   meetings   . Note that only one day to attend a conference.startDayi <= d <= endDayi di

Please return you can participate in  the largest  number of meetings.

 

Example 1:

Input: Events = [[1,2], [2,3], [3,4-]]
 Output: 3
 Explanation: You can participate in all three meetings.
One solution meeting the above arrangement in FIG.
Day 1 to attend a meeting.
The first two days to attend the second meeting.
Day 3 to participate in the third meeting.

Example 2:

Input: Events = [[1,2], [2,3], [3,4-], [1,2]]
 Output: 4

Example 3:

Input: Events = [[l, 4], [4,4 &], [2,2 &], [3,4-], [1,1]]
 Output: 4

Example 4:

Input: Events = [[1,100000]]
 Output: 1

Example 5:

Input: Events = [[1,1], [1,2], [l, 3], [l, 4], [l, 5], [1,6], [l, 7]]
 Output: 7

 

prompt:

  • 1 <= events.length <= 10^5
  • events[i].length == 2
  • 1 <= events[i][0] <= events[i][1] <= 10^5

answer

贪心+优先队列
首先将区间按开始时间进行排序,然后结束时间早的先安排。还需要鼗安排冲突,不合理的去掉。
时间复杂度为:O(nlogn)
空间复杂度为:O(n)

代码

class Solution {
public:
    int maxEvents(vector<vector<int>>& events) {
        priority_queue<int, vector<int>, greater<int>>que;
        int cnt = 0, idx = 1, i = 0;
        //先排序
        sort(events.begin(), events.end());
        while(i < events.size() || que.size() > 0){
            while(i < events.size() && events[i][0] == idx){//开始时间为idx的,均添加到优先队列
                que.push(events[i][1]);
                ++i;
            }
            while(que.size() > 0 && que.top() < idx){//去除安排冲突的
                que.pop();
            }
            if(que.size() > 0){//优先安排结束时间早的
                ++cnt;
                que.pop();
            }
            ++idx;
        }
        return cnt;
    }
};

5343. 多次求和构造目标数组

题目地址: https://leetcode-cn.com/problems/construct-target-array-with-multiple-sums/

题目描述

给你一个整数数组 target 。一开始,你有一个数组 A ,它的所有元素均为 1 ,你可以执行以下操作:

  • 令 x 为你数组里所有元素的和
  • 选择满足 0 <= i < target.size 的任意下标 i ,并让 A 数组里下标为 i 处的值为 x 。
  • 你可以重复该过程任意次

如果能从 A 开始构造出目标数组 target ,请你返回 True ,否则返回 False 。

 

示例 1:

输入:target = [9,3,5]
输出:true
解释:从 [1, 1, 1] 开始
[1, 1, 1], 和为 3 ,选择下标 1
[1, 3, 1], 和为 5, 选择下标 2
[1, 3, 5], 和为 9, 选择下标 0
[9, 3, 5] 完成

示例 2:

输入:target = [1,1,1,2]
输出:false
解释:不可能从 [1,1,1,1] 出发构造目标数组。

示例 3:

输入:target = [8,5]
输出:true

 

提示:

  • N == target.length
  • 1 <= target.length <= 5 * 10^4
  • 1 <= target[i] <= 10^9

题解

正向思考,不知道用所有的数字之和去替换哪一个数字,尝试的话可能性太多,实现难度太大。反向思考的话,数组中最大的数字显然是上一个数组中所有数字之和,而它所替换的数字等于最大的数字减去其它数字之和。如此替换下去,如果最后所有的数字都为1,表示可以构造目标数组,一旦出现数字0或负数,表示不能构造。

代码

class Solution {
public:
    bool isPossible(vector<int>& target) {
        long long int sum = 0;
        int rep_num = 0;
        bool flag = true;
        priority_queue<int>que;
        for(int i = 0; i < target.size(); ++i){
            sum += target[i];
            que.push(target[i]);
        }
        while(que.top() != 1){
            sum = sum - que.top();//除去最大数字其它数字之和
            if(sum == 1){
                flag = true;
                break;
            }
            /*
            这里用除法而不用减法是为了处理像[100000, 1]这样的例子超时的问题
            用除法,直接使当前的最大数字小于其它数字之和,避免多轮最大数字都是同一个。
            */
            if(que.top() / sum == 0 || (que.top() % sum == 0)){//出现负数和0
                flag = false;
                break;
            }
            else{
                que.push(que.top() % sum);
                sum = sum + que.top() % sum;//上一个数组的所有元素之和
                que.pop();
            }
        }
        if(flag){
            return true;
        }
        else{
            return false;
        }
    }
};
发布了169 篇原创文章 · 获赞 35 · 访问量 4万+

Guess you like

Origin blog.csdn.net/happyeveryday62/article/details/104362795