LeetCode 题解工作台
边界上的蚂蚁
边界上有一只蚂蚁,它有时向 左 走,有时向 右 走。 给你一个 非零 整数数组 nums 。蚂蚁会按顺序读取 nums 中的元素,从第一个元素开始直到结束。每一步,蚂蚁会根据当前元素的值移动: 如果 nums[i] ,向 左 移动 -nums[i] 单位。 如果 nums[i] > 0 ,向 右 移…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
根据题目描述,我们只需要计算 的所有前缀和中有多少个 即可。 时间复杂度 ,其中 为 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
边界上有一只蚂蚁,它有时向 左 走,有时向 右 走。
给你一个 非零 整数数组 nums 。蚂蚁会按顺序读取 nums 中的元素,从第一个元素开始直到结束。每一步,蚂蚁会根据当前元素的值移动:
- 如果
nums[i] < 0,向 左 移动-nums[i]单位。 - 如果
nums[i] > 0,向 右 移动nums[i]单位。
返回蚂蚁 返回 到边界上的次数。
注意:
- 边界两侧有无限的空间。
- 只有在蚂蚁移动了
|nums[i]|单位后才检查它是否位于边界上。换句话说,如果蚂蚁只是在移动过程中穿过了边界,则不会计算在内。
示例 1:
输入:nums = [2,3,-5] 输出:1 解释:第 1 步后,蚂蚁距边界右侧 2 单位远。 第 2 步后,蚂蚁距边界右侧 5 单位远。 第 3 步后,蚂蚁位于边界上。 所以答案是 1 。
示例 2:
输入:nums = [3,2,-3,-4] 输出:0 解释:第 1 步后,蚂蚁距边界右侧 3 单位远。 第 2 步后,蚂蚁距边界右侧 5 单位远。 第 3 步后,蚂蚁距边界右侧 2 单位远。 第 4 步后,蚂蚁距边界左侧 2 单位远。 蚂蚁从未返回到边界上,所以答案是 0 。
提示:
1 <= nums.length <= 100-10 <= nums[i] <= 10nums[i] != 0
解题思路
方法一:前缀和
根据题目描述,我们只需要计算 的所有前缀和中有多少个 即可。
时间复杂度 ,其中 为 的长度。空间复杂度 。
class Solution:
def returnToBoundaryCount(self, nums: List[int]) -> int:
return sum(s == 0 for s in accumulate(nums))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluating the candidate's ability to simulate processes step-by-step and handle edge cases.
- question_mark
Looking for clarity in explaining the logic behind tracking the ant's position.
- question_mark
Assessing the candidate's ability to optimize the solution using prefix sums or similar techniques.
常见陷阱
外企场景- error
Forgetting to reset the boundary count when the ant returns to position 0 multiple times.
- error
Overcomplicating the problem by using unnecessary data structures or algorithms.
- error
Not properly handling edge cases like arrays with only one element or extreme values.
进阶变体
外企场景- arrow_right_alt
Handling arrays where all elements are positive or negative.
- arrow_right_alt
Returning the final position of the ant instead of counting boundary returns.
- arrow_right_alt
Simulating multiple ants with different movement patterns on the same array.