Leetcode Weekly Contest 176 题解
emmmm,我的拖延症没救了,顺便加上这周沉迷 Kotlin ,这篇本应该周一就写完的题解拖到现在,= =然而这周双周赛,,我又得写两篇题解了。。。
1351. Count Negative Numbers in a Sorted Matrix
题面:
Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.
Return the number of negative numbers in grid.
示例:
1 | Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] |
题面很简单,给定一个矩阵,矩阵横/纵向都是递减的,求这个矩阵中负数的个数,这个题,因为横/纵向的数据规模都是小于100的,那就没啥说的了,,直接暴力,横向遍历,然后遇到负数就停止遍历
1 | from typing import List |
1352. Product of the Last K Numbers
题面:
1 | Implement the class ProductOfNumbers that supports two methods: |
示例
1 | Input |
题面很简单,设计一个数据结构,提供一个 add
方法,让用户能够往里面添加速度,提供一个 getProduct
方法,让用户能求倒数K个数的乘积,这题没啥好说的,直接暴力写,中间加个 hashmap 作为缓存
1 | from typing import List, Dict |
1353. Maximum Number of Events That Can Be Attended
题面:
Given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.
You can attend an event i at any day d where startTimei <= d <= endTimei. Notice that you can only attend one event at any time d.
Return the maximum number of events you can attend.
示例
1 | Input: events = [[1,2],[2,3],[3,4]] |
给定一个数组,数组中每个元素 x 代表一个活动,x[0], x[i] 代表该活动的起始与结束时间,一个用户一天只能参加一个活动,求用户最多能参加多少个活动。经典的一个贪心题目,首先对活动列表以结束时间进行排序,然后依次遍历每个时间,确认具体哪一天可以参加,整体时间复杂度为 O(max(nlogn,n*m))
1 | from typing import List, Dict |
1354. Construct Target Array With Multiple Sums
题面
Given an array of integers target. From a starting array, A consisting of all 1’s, you may perform the following procedure :
- let x be the sum of all elements currently in your array.
- choose index i, such that 0 <= i < target.size and set the value of A at index i to x.
- You may repeat this procedure as many times as needed.
Return True if it is possible to construct the target array from A otherwise return False.
示例:
1 | Input: target = [9,3,5] |
这题算是一个数学题吧,我们首先知道数组中所有的元素的和一定大于数组中每个元素(这不是废话),然后我们假定有这样一个数组 [1,1,9,17,63] ,我们可以往回迭代上一个数组结构是 [1,1,9.17,33] ,然后我们还可以向前迭代一次 [1,1,9,17,5] 然后当前的数字已经不再是数组中最大的数字,于是我们开始寻找下一个数组中最大的数字进行迭代
这里我们也可以发现,数组中最大数字的最原始版本的值是当前数字对其余数字的和的模,于是我们就这样一直迭代就 OK 了
好了,上代码
1 | import heapq |
总结
这次的题还是周赛的常规水平,然而我刷题实在是太少了QAQ
Leetcode Weekly Contest 176 题解
https://manjusaka.blog/posts/2020/02/23/leetcode-weekly-contest-176/