返回介绍

solution / 0400-0499 / 0413.Arithmetic Slices / README_EN

发布于 2024-06-17 01:04:00 字数 3681 浏览 0 评论 0 收藏 0

413. Arithmetic Slices

中文文档

Description

An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

  • For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.

Given an integer array nums, return _the number of arithmetic subarrays of_ nums.

A subarray is a contiguous subsequence of the array.

 

Example 1:

Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

Example 2:

Input: nums = [1]
Output: 0

 

Constraints:

  • 1 <= nums.length <= 5000
  • -1000 <= nums[i] <= 1000

Solutions

Solution 1

class Solution:
  def numberOfArithmeticSlices(self, nums: List[int]) -> int:
    ans, cnt = 0, 2
    d = 3000
    for a, b in pairwise(nums):
      if b - a == d:
        cnt += 1
      else:
        d = b - a
        cnt = 2
      ans += max(0, cnt - 2)
    return ans
class Solution {
  public int numberOfArithmeticSlices(int[] nums) {
    int ans = 0, cnt = 0;
    int d = 3000;
    for (int i = 0; i < nums.length - 1; ++i) {
      if (nums[i + 1] - nums[i] == d) {
        ++cnt;
      } else {
        d = nums[i + 1] - nums[i];
        cnt = 0;
      }
      ans += cnt;
    }
    return ans;
  }
}
class Solution {
public:
  int numberOfArithmeticSlices(vector<int>& nums) {
    int ans = 0, cnt = 0;
    int d = 3000;
    for (int i = 0; i < nums.size() - 1; ++i) {
      if (nums[i + 1] - nums[i] == d) {
        ++cnt;
      } else {
        d = nums[i + 1] - nums[i];
        cnt = 0;
      }
      ans += cnt;
    }
    return ans;
  }
};
func numberOfArithmeticSlices(nums []int) (ans int) {
  cnt, d := 0, 3000
  for i, b := range nums[1:] {
    a := nums[i]
    if b-a == d {
      cnt++
    } else {
      d = b - a
      cnt = 0
    }
    ans += cnt
  }
  return
}
function numberOfArithmeticSlices(nums: number[]): number {
  let ans = 0;
  let cnt = 0;
  let d = 3000;
  for (let i = 0; i < nums.length - 1; ++i) {
    const a = nums[i];
    const b = nums[i + 1];
    if (b - a == d) {
      ++cnt;
    } else {
      d = b - a;
      cnt = 0;
    }
    ans += cnt;
  }
  return ans;
}

Solution 2

class Solution:
  def numberOfArithmeticSlices(self, nums: List[int]) -> int:
    ans = cnt = 0
    d = 3000
    for a, b in pairwise(nums):
      if b - a == d:
        cnt += 1
      else:
        d = b - a
        cnt = 0
      ans += cnt
    return ans

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

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

发布评论

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