Biweekly Contest 9
1196. How Many Apples Can You Put into the Basket
You have some apples, where
arr[i]
is the weight of thei
-th apple. You also have a basket that can carry up to5000
units of weight.Return the maximum number of apples you can put in the basket.
1
2
3 >Input: arr = [100,200,150,1000]
>Output: 4
>Explanation: All 4 apples can be carried by the basket since their sum of weights is 1450.
解析:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution {
public:
int maxNumberOfApples(vector<int>& arr) {
sort(arr.begin(),arr.end());
int res = 0;
int weight = 5000;
for (auto num : arr)
{
if (weight - num > 0)
{
res++;
weight -= num;
}
else
break;
}
return res;
}
};
1197. Minimum Knight Moves
In an infinite chess board with coordinates from
-infinity
to+infinity
, you have a knight at square[0, 0]
.A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
Return the minimum number of steps needed to move the knight to the square
[x, y]
. It is guaranteed the answer exists.Constraints:
|x| + |y| <= 300
- 解析:到达【x,y】的最小步数,等价于到达 【||x|| ,||y||】,即正值的位置。用图的BFS解。
我的两个答案都超时:
1 | import queue |
这个也错误():
1 | const int MAXL = 302; |
别人的方法:不用queue,直接用list更加方便,改了下个别地方:
1 | class Solution(object): |
1 |
|
这个代码是最concise的了:其他的比较看不懂。。 - -
1 | class Solution { |
1198. Find Smallest Common Element in All Rows
Given a matrix
mat
where every row is sorted in increasing order, return the smallest common element in all rows.If there is no common element, return
-1
.
1
2 >Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
>Output: 5
- 复习下集合操作:
1 | class Solution: |
1199. Minimum Time to Build Blocks
You are given a list of blocks, where
blocks[i] = t
means that thei
-th block needst
units of time to be built. A block can only be built by exactly one worker.A worker can either split into two workers (number of workers increases by one) or build a block then go home. Both decisions cost some time.
The time cost of spliting one worker into two workers is given as an integer
split
. Note that if two workers split at the same time, they split in parallel so the cost would besplit
.Output the minimum time needed to build all blocks.
Initially, there is only one worker.
1
2
3
4
5 >Input: blocks = [1,2,3], split = 1
>Output: 4
>Explanation: Split 1 worker into 2, then assign the first worker to the last block and split the second worker into 2.
>Then, use the two unassigned workers to build the first two blocks.
>The cost is 1 + max(3, 1 + max(1, 2)) = 4.
- workers可以并行分裂,比如 1—->2,需要一次分裂,1——>22, 需要2次分裂,1—>2 n,需要n次分裂。
假设目标blocks数组的大小为M,2个为一段,整个数组被分成小于等于n的小段。
每一个小段拥有一个split值,如【1,2,3】被分为【1,2】还有【3】,【3】带有一个split值,这个值的意思是花时间找人,所以这个split必须用完,才表示新的工人过来开始干活。新的工人过来
1 | class Solution: |
1 | class Solution: |
c++:
1 | class Solution { |