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 by nums[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.
Input: nums =[2,3,-5]Output: 1Explanation: After the first step, the ant is2 steps to the right of the boundary.After the second step, the ant is5 steps to the right of the boundary.After the third step, the ant is on the boundary.So the answer is1.
Example 2:
1
2
3
4
5
6
7
Input: nums =[3,2,-3,-4]Output: 0Explanation: After the first step, the ant is3 steps to the right of the boundary.After the second step, the ant is5 steps to the right of the boundary.After the third step, the ant is2 steps to the right of the boundary.After the fourth step, the ant is2 steps to the left of the boundary.The ant never returned to the boundary, so the answer is0.
The ant’s position after each move is the sum of all previous moves. If the position becomes zero after any move, the ant is back on the boundary. We can track the position step by step and count how many times it returns to zero.
classSolution {
publicintreturnToBoundaryCount(int[] nums) {
int pos = 0, ans = 0;
for (int n : nums) {
pos += n;
if (pos == 0) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funreturnToBoundaryCount(nums: IntArray): Int {
var pos = 0var ans = 0for (n in nums) {
pos += n
if (pos ==0) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defreturnToBoundaryCount(self, nums: list[int]) -> int:
pos: int =0 ans: int =0for n in nums:
pos += n
if pos ==0:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnreturn_to_boundary_count(nums: Vec<i32>) -> i32 {
let (mut pos, mut ans) = (0, 0);
for n in nums {
pos += n;
if pos ==0 {
ans +=1;
}
}
ans
}
}