LeetCode 题解工作台
好数字之和
给定一个整数数组 nums 和一个整数 k ,如果元素 nums[i] 严格 大于下标 i - k 和 i + k 处的元素(如果这些元素存在),则该元素 nums[i] 被认为是 好 的。如果这两个下标都不存在,那么 nums[i] 仍然被认为是 好 的。 返回数组中所有 好 元素的 和 。 示例…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们可以遍历数组 ,对于每个元素 ,检查是否满足条件: - 如果 $i \ge k$ 且 $\textit{nums}[i] \le \textit{nums}[i - k]$,则 不是好数字;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给定一个整数数组 nums 和一个整数 k,如果元素 nums[i] 严格 大于下标 i - k 和 i + k 处的元素(如果这些元素存在),则该元素 nums[i] 被认为是 好 的。如果这两个下标都不存在,那么 nums[i] 仍然被认为是 好 的。
返回数组中所有 好 元素的 和。
示例 1:
输入: nums = [1,3,2,1,5,4], k = 2
输出: 12
解释:
好的数字包括 nums[1] = 3,nums[4] = 5 和 nums[5] = 4,因为它们严格大于下标 i - k 和 i + k 处的数字。
示例 2:
输入: nums = [2,1], k = 1
输出: 2
解释:
唯一的好数字是 nums[0] = 2,因为它严格大于 nums[1]。
提示:
2 <= nums.length <= 1001 <= nums[i] <= 10001 <= k <= floor(nums.length / 2)
解题思路
方法一:遍历
我们可以遍历数组 ,对于每个元素 ,检查是否满足条件:
- 如果 且 ,则 不是好数字;
- 如果 且 ,则 不是好数字。
- 否则, 是好数字,我们将其累加到答案中。
遍历结束后,返回答案即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def sumOfGoodNumbers(self, nums: List[int], k: int) -> int:
ans = 0
for i, x in enumerate(nums):
if i >= k and x <= nums[i - k]:
continue
if i + k < len(nums) and x <= nums[i + k]:
continue
ans += x
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates a solid understanding of array manipulation and boundary condition handling.
- question_mark
Candidate efficiently checks the conditions without unnecessary recomputation.
- question_mark
Candidate demonstrates the ability to handle edge cases like the array boundaries correctly.
常见陷阱
外企场景- error
Not properly handling boundary elements, causing out-of-bounds errors.
- error
Inefficient checking of neighbors for each element, leading to unnecessary complexity.
- error
Not considering the array length limits or invalid inputs which might cause runtime issues.
进阶变体
外企场景- arrow_right_alt
Increase the complexity by adding more complex boundary conditions or larger values for k.
- arrow_right_alt
Optimize the approach for larger arrays with higher values of k.
- arrow_right_alt
Modify the problem to include elements with different types of neighboring conditions (e.g., divisibility instead of strict greater).