https://leetcode.com/problems/k-radius-subarray-averages/description/
2090. K Radius Subarray Averages
给你一个整数阵列 nums 和一个数字 k 表示左右间距,返回一个阵列 res,
res[i] = nums[i-k] + nums[i-k+1] + ... + nums[i+k], 若 i >= k 且 i < nums.len
res[i] = -1, 若 i < k 或 i + k > nums.len
Example 1:
https://assets.leetcode.com/uploads/2021/11/07/eg1.png
Input: nums = [7,4,3,9,1,8,5,2,6], k = 3
Output: [-1,-1,-1,5,4,4,-1,-1,-1]
Explanation:
- avg[0], avg[1], and avg[2] are -1 because there are less than k elements
before each index.
- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9
+ 1 + 8 + 5 = 37.
Using integer division, avg[3] = 37 / 7 = 5.
- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2)
/ 7 = 4.
- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6)
/ 7 = 4.
- avg[6], avg[7], and avg[8] are -1 because there are less than k elements
after each index.
Example 2:
Input: nums = [100000], k = 0
Output: [100000]
Explanation:
- The sum of the subarray centered at index 0 with radius 0 is: 100000.
avg[0] = 100000 / 1 = 100000.
Example 3:
Input: nums = [8], k = 100000
Output: [-1]
Explanation:
- avg[0] is -1 because there are less than k elements before and after index
0.
思路:
1.因为题目要求出每个点的左右和平均,而多次求和可以使用prefixSum来快速求和。
2.先把 corner case 排掉,若 k = 0 的话每个点的平均都会是自己所以直接返回 nums
,如果 k * 2 + 1 比 n 大表示每个点求范围和都会越界所以直接返回全为 -1 的解。
3.再来只要求出前缀和,然后找出 k ~ n -k 区间每一个点做为中心的和除以k即可,比
较需要注意的是如果用int会爆掉,要用long才能AC。
Java Code: