题目链接:https://leetcode.cn/contest/weekly-contest-335/
# 第一题:模拟
# 解题思路
简单的按题意模拟即可
# 提交结果
# 代码
class Solution { | |
public int passThePillow(int n, int time) { | |
int cur = 1; | |
int dir = 1; | |
while (--time >= 0) { | |
cur += dir; | |
if (cur > n) { | |
cur = n - 1; | |
dir = -1; | |
} else if (cur < 1) { | |
cur = 2; | |
dir = 1; | |
} | |
} | |
return cur; | |
} | |
} |
# 第二题:BFS
# 解题思路
- BFS 一遍记录每一层的和
- 对每一层和进行排序后,就能直接得到第 k 大的层和
# 提交结果
# 代码
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode() {} | |
* TreeNode(int val) { this.val = val; } | |
* TreeNode(int val, TreeNode left, TreeNode right) { | |
* this.val = val; | |
* this.left = left; | |
* this.right = right; | |
* } | |
* } | |
*/ | |
class Solution { | |
public long kthLargestLevelSum(TreeNode root, int k) { | |
List<Long> list = new ArrayList<>(); | |
Queue<TreeNode> que = new LinkedList<>(); | |
que.offer(root); | |
while (!que.isEmpty()) { | |
long sum = 0; | |
for (int i = que.size(); i > 0; --i) { | |
root = que.poll(); | |
sum += root.val; | |
if (root.left != null) que.offer(root.left); | |
if (root.right != null) que.offer(root.right); | |
} | |
list.add(sum); | |
} | |
Collections.sort(list); | |
return list.size() < k ? -1 : list.get(list.size() - k); | |
} | |
} |
# 第三题:
暂时没想到好方法