@@ -454,4 +454,118 @@ class Solution:
454
454
res += edge
455
455
456
456
return res
457
+ ```
458
+
459
+ ## 第 9 场双周赛
460
+
461
+ [ 点击前往第 9 场双周赛] ( https://leetcode-cn.com/contest/biweekly-contest-9 )
462
+
463
+ ### 5072. 最多可以买到的苹果数量
464
+
465
+ [ 原题链接] ( https://leetcode-cn.com/contest/biweekly-contest-9/problems/how-many-apples-can-you-put-into-the-basket/ )
466
+
467
+ #### 思路
468
+
469
+ 1 . 排序
470
+ 2 . 遍历排序结果,将苹果重量依次相加:
471
+ - 如果相加和小于 5000,则把这个苹果放入袋子
472
+ - 如果相加和大于 5000,跳出遍历循环
473
+
474
+ ``` python
475
+ class Solution :
476
+ def maxNumberOfApples (self , arr : List[int ]) -> int :
477
+ arr.sort()
478
+ res = 0
479
+ s = 0
480
+ for n in arr:
481
+ s += n
482
+ if s > 5000 :
483
+ break
484
+ else :
485
+ res += 1
486
+ return res
487
+ ```
488
+
489
+ ### 5073. 进击的骑士
490
+
491
+ [ 原题链接] ( https://leetcode-cn.com/contest/biweekly-contest-9/problems/minimum-knight-moves/ )
492
+
493
+ #### 思路
494
+
495
+ BFS,需要进行枝剪,否则会超时。
496
+
497
+ 骑士所走的 8 个方向具有对称性,所以我们只要保留 ` x > 0 && y > 0 ` 方向即可。这里借用了队列来实现 BFS。
498
+
499
+ ``` python
500
+ class Solution :
501
+ def minKnightMoves (self , x : int , y : int ) -> int :
502
+ if x == 0 and y == 0 :
503
+ return 0
504
+
505
+ dx = [2 , 2 , - 2 , - 2 , 1 , 1 , - 1 , - 1 ]
506
+ dy = [1 , - 1 , 1 , - 1 , 2 , - 2 , 2 , - 2 ]
507
+ # 对称性
508
+ x = - x if x < 0 else x
509
+ y = - y if y < 0 else y
510
+
511
+ # 初始化队列
512
+ q = list ()
513
+ mark = dict ()
514
+ mark[0 ] = True
515
+ q.append([0 , 0 ])
516
+ M = 10000
517
+
518
+ res = 0
519
+ while len (q):
520
+ q_length = len (q)
521
+ res += 1
522
+ # 遍历队列现有元素
523
+ while q_length:
524
+ px, py = q[0 ][0 ], q[0 ][1 ]
525
+ # 取出队列头部元素
526
+ del (q[0 ])
527
+ q_length -= 1
528
+
529
+ for i in range (len (dx)):
530
+ pdx = px + dx[i]
531
+ pdy = py + dy[i]
532
+ # 对称性枝剪
533
+ if pdx < 0 or pdy < 0 :
534
+ continue
535
+ if abs (pdx) + abs (pdy) > 300 :
536
+ continue
537
+ # 是否为要求的值
538
+ if pdx == x and pdy == y:
539
+ return res
540
+ # 是否已记录
541
+ tmp = pdx * M + pdy
542
+ if tmp in mark:
543
+ continue
544
+ mark[tmp] = True
545
+ q.append([pdx, pdy])
546
+ ```
547
+
548
+ ### 5071. 找出所有行中最小公共元素
549
+
550
+ [ 原题链接] ( https://leetcode-cn.com/contest/biweekly-contest-9/problems/find-smallest-common-element-in-all-rows/ )
551
+
552
+ #### 思路
553
+
554
+ 1 . 用字典 ` key ` 存储每行中存在的元素,` value ` 值为元素个数
555
+ 2 . 从小到大遍历字典 ` key ` 所代表的元素,若 ` value ` 值等于 ` len(mat) ` (代表每行都出线了这个元素),则返回该元素
556
+
557
+ ``` python
558
+ class Solution :
559
+ def smallestCommonElement (self , mat : List[List[int ]]) -> int :
560
+ mat_num = len (mat)
561
+ mat_map = dict ()
562
+ for nums in mat:
563
+ for num in nums:
564
+ mat_map[num] = mat_map.get(num, 0 ) + 1
565
+
566
+ key_list = sorted ([x for x in mat_map])
567
+ for k in key_list:
568
+ if mat_map.get(k, 0 ) == mat_num:
569
+ return k
570
+ return - 1
457
571
```
0 commit comments