返回介绍

solution / 3000-3099 / 3028.Ant on the Boundary / README_EN

发布于 2024-06-17 01:02:57 字数 4299 浏览 0 评论 0 收藏 0

3028. Ant on the Boundary

中文文档

Description

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.

 

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

Solutions

Solution 1: Prefix Sum

Based on the problem description, we only need to calculate how many zeros are in all prefix sums of nums.

The time complexity is $O(n)$, where $n$ is the length of nums. The space complexity is $O(1)$.

class Solution:
  def returnToBoundaryCount(self, nums: List[int]) -> int:
    return sum(s == 0 for s in accumulate(nums))
class Solution {
  public int returnToBoundaryCount(int[] nums) {
    int ans = 0, s = 0;
    for (int x : nums) {
      s += x;
      if (s == 0) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int returnToBoundaryCount(vector<int>& nums) {
    int ans = 0, s = 0;
    for (int x : nums) {
      s += x;
      ans += s == 0;
    }
    return ans;
  }
};
func returnToBoundaryCount(nums []int) (ans int) {
  s := 0
  for _, x := range nums {
    s += x
    if s == 0 {
      ans++
    }
  }
  return
}
function returnToBoundaryCount(nums: number[]): number {
  let [ans, s] = [0, 0];
  for (const x of nums) {
    s += x;
    ans += s === 0 ? 1 : 0;
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文