边界上的蚂蚁
难度:
标签:
题目描述
An ant is on a boundary. It sometimes goes left and sometimes right.
You are given an array of non-zero integers nums
. The ant starts reading nums
from the first element of it to its end. At each step, it moves according to the value of the current element:
- If
nums[i] < 0
, it moves left by-nums[i]
units. - If
nums[i] > 0
, it moves right bynums[i]
units.
Return the number of times the ant returns to the boundary.
Notes:
- There is an infinite space on both sides of the boundary.
- We check whether the ant is on the boundary only after it has moved
|nums[i]|
units. In other words, if the ant crosses the boundary during its movement, it does not count.
Example 1:
Input: nums = [2,3,-5] Output: 1 Explanation: After the first step, the ant is 2 steps to the right of the boundary. After the second step, the ant is 5 steps to the right of the boundary. After the third step, the ant is on the boundary. So the answer is 1.
Example 2:
Input: nums = [3,2,-3,-4] Output: 0 Explanation: After the first step, the ant is 3 steps to the right of the boundary. After the second step, the ant is 5 steps to the right of the boundary. After the third step, the ant is 2 steps to the right of the boundary. After the fourth step, the ant is 2 steps to the left of the boundary. The ant never returned to the boundary, so the answer is 0.
Constraints:
1 <= nums.length <= 100
-10 <= nums[i] <= 10
nums[i] != 0
代码结果
运行时间: 21 ms, 内存: 16.0 MB
/*
* 思路:
* 使用Java Stream API处理数组和位置更新。
* 1. 使用Stream遍历数组,每一步更新位置。
* 2. 检查每次移动后的位置,如果在边界上则计数+1。
* 3. 返回最终的边界计数。
*/
import java.util.stream.IntStream;
public class AntOnBoundaryStream {
public static int countBoundaryReturns(int[] nums) {
int[] position = {0}; // 使用数组以便在lambda表达式中修改
return (int) IntStream.of(nums)
.filter(num -> {
position[0] += num;
return position[0] == 0;
})
.count();
}
public static void main(String[] args) {
int[] nums1 = {2, 3, -5};
int[] nums2 = {3, 2, -3, -4};
System.out.println(countBoundaryReturns(nums1)); // 输出: 1
System.out.println(countBoundaryReturns(nums2)); // 输出: 0
}
}
解释
方法:
该题解通过模拟蚂蚁的行进来计算蚂蚁返回到边界的次数。初始化蚂蚁的位置为0(表示边界位置)。遍历数组nums中的每个元素,根据元素的正负值更新蚂蚁的位置(向右或向左移动相应的单位数)。在每次更新位置后,检查蚂蚁是否返回到了边界(位置为0)。如果是,则计数器增加。最终返回计数器的值,即为蚂蚁返回到边界的总次数。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在初始位置被定义为边界(位置0)的情况下,为什么蚂蚁在开始移动前不计算一次返回边界的情况?
▷🦆
在更新蚂蚁位置后立即检查是否为0的逻辑是否会遗漏蚂蚁在移动过程中多次穿越边界的情况?
▷🦆
数组中的每个元素是否都有可能导致蚂蚁返回到边界,还是某些特定的数值或数值组合才有这种可能?
▷