LeetCode 题解工作台

好数字之和

给定一个整数数组 nums 和一个整数 k ,如果元素 nums[i] 严格 大于下标 i - k 和 i + k 处的元素(如果这些元素存在),则该元素 nums[i] 被认为是 好 的。如果这两个下标都不存在,那么 nums[i] 仍然被认为是 好 的。 返回数组中所有 好 元素的 和 。 示例…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们可以遍历数组 ,对于每个元素 ,检查是否满足条件: - 如果 $i \ge k$ 且 $\textit{nums}[i] \le \textit{nums}[i - k]$,则 不是好数字;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数数组 nums 和一个整数 k,如果元素 nums[i] 严格 大于下标 i - ki + k 处的元素(如果这些元素存在),则该元素 nums[i] 被认为是 的。如果这两个下标都不存在,那么 nums[i] 仍然被认为是 的。

返回数组中所有 元素的

 

示例 1:

输入: nums = [1,3,2,1,5,4], k = 2

输出: 12

解释:

好的数字包括 nums[1] = 3nums[4] = 5nums[5] = 4,因为它们严格大于下标 i - ki + k 处的数字。

示例 2:

输入: nums = [2,1], k = 1

输出: 2

解释:

唯一的好数字是 nums[0] = 2,因为它严格大于 nums[1]

 

提示:

  • 2 <= nums.length <= 100
  • 1 <= nums[i] <= 1000
  • 1 <= k <= floor(nums.length / 2)
lightbulb

解题思路

方法一:遍历

我们可以遍历数组 nums\textit{nums},对于每个元素 nums[i]\textit{nums}[i],检查是否满足条件:

  • 如果 iki \ge knums[i]nums[ik]\textit{nums}[i] \le \textit{nums}[i - k],则 nums[i]\textit{nums}[i] 不是好数字;
  • 如果 i+k<len(nums)i + k < \textit{len}(\textit{nums})nums[i]nums[i+k]\textit{nums}[i] \le \textit{nums}[i + k],则 nums[i]\textit{nums}[i] 不是好数字。
  • 否则,nums[i]\textit{nums}[i] 是好数字,我们将其累加到答案中。

遍历结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nn 是数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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).

help

常见问题

外企场景

好数字之和题解:数组·driven | LeetCode #3452 简单