您的位置:首页 > 娱乐 > 明星 > 网站制作公司挣钱吗_廊坊自助建站定制_关键词优化有哪些作用_新站点seo联系方式

网站制作公司挣钱吗_廊坊自助建站定制_关键词优化有哪些作用_新站点seo联系方式

2025/7/21 7:43:54 来源:https://blog.csdn.net/navicheung/article/details/142933522  浏览:    关键词:网站制作公司挣钱吗_廊坊自助建站定制_关键词优化有哪些作用_新站点seo联系方式
网站制作公司挣钱吗_廊坊自助建站定制_关键词优化有哪些作用_新站点seo联系方式

413. Arithmetic Slices

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

From: LeetCode
Link: 413. Arithmetic Slices


Solution:

Ideas:

1. Initial Setup:

  • We check if the array has fewer than 3 elements since at least 3 elements are required to form an arithmetic slice. If there are fewer than 3, we return 0.

2. Main Logic:

  • We loop through the array starting from the third element (i = 2).
  • For each triplet (nums[i-2], nums[i-1], nums[i]), we check if the difference between consecutive elements is the same (i.e., if nums[i] - nums[i-1] == nums[i-1] - nums[i-2]).
  • If they form an arithmetic sequence, we increment the currentStreak (which tracks how many consecutive arithmetic slices we have encountered). The total count is updated by adding the value of currentStreak.
  • If the triplet does not form an arithmetic sequence, we reset the currentStreak to 0.

3. Return the Result:

  • The total number of arithmetic slices is stored in count, which we return.
Code:
int numberOfArithmeticSlices(int* nums, int numsSize) {if (numsSize < 3) {return 0; // An arithmetic subarray needs at least 3 elements}int count = 0;  // Total count of arithmetic slicesint currentStreak = 0;  // The length of the current arithmetic slice streak// Loop through the array and check for arithmetic slicesfor (int i = 2; i < numsSize; i++) {// Check if the current subarray of 3 elements forms an arithmetic sequenceif (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {// If the current element continues an arithmetic slice, extend the current streakcurrentStreak++;count += currentStreak; // Add the current streak count to the total} else {// Reset the streak if the difference is not the samecurrentStreak = 0;}}return count;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com