classSolution { public: intnumberOfArithmeticSlices(vector<int>& nums){ int n = nums.size(); if (n == 1) { return0; }
int d = nums[0] - nums[1], t = 0; int ans = 0; // 因为等差数列的长度至少为 3,所以可以从 i=2 开始枚举 for (int i = 2; i < n; ++i) { if (nums[i - 1] - nums[i] == d) { ++t; } else { d = nums[i - 1] - nums[i]; t = 0; } ans += t; } return ans; } };
publicclassSolution { publicintNumberOfArithmeticSlices(int[] nums) { int n = nums.Length; if (n == 1) { return0; }
int d = nums[0] - nums[1], t = 0; int ans = 0; // 因为等差数列的长度至少为 3,所以可以从 i=2 开始枚举 for (int i = 2; i < n; ++i) { if (nums[i - 1] - nums[i] == d) { ++t; } else { d = nums[i - 1] - nums[i]; t = 0; } ans += t; } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defnumberOfArithmeticSlices(self, nums: List[int]) -> int: n = len(nums) if n == 1: return0 d, t = nums[0] - nums[1], 0 ans = 0 # 因为等差数列的长度至少为 3,所以可以从 i=2 开始枚举 for i inrange(2, n): if nums[i - 1] - nums[i] == d: t += 1 else: d = nums[i - 1] - nums[i] t = 0 ans += t return ans
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcnumberOfArithmeticSlices(nums []int) (ans int) { n := len(nums) if n == 1 { return }
d, t := nums[0]-nums[1], 0 // 因为等差数列的长度至少为 3,所以可以从 i=2 开始枚举 for i := 2; i < n; i++ { if nums[i-1]-nums[i] == d { t++ } else { d, t = nums[i-1]-nums[i], 0 } ans += t } return }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
intnumberOfArithmeticSlices(int* nums, int numsSize) { if (numsSize == 1) { return0; }
int d = nums[0] - nums[1], t = 0; int ans = 0; // 因为等差数列的长度至少为 3,所以可以从 i=2 开始枚举 for (int i = 2; i < numsSize; ++i) { if (nums[i - 1] - nums[i] == d) { ++t; } else { d = nums[i - 1] - nums[i]; t = 0; } ans += t; } return ans; }
var numberOfArithmeticSlices = function(nums) { const n = nums.length; if (n === 1) { return0; }
let d = nums[0] - nums[1], t = 0; let ans = 0; // 因为等差数列的长度至少为 3,所以可以从 i=2 开始枚举 for (let i = 2; i < n; ++i) { if (nums[i - 1] - nums[i] === d) { ++t; } else { d = nums[i - 1] - nums[i]; t = 0; } ans += t; } return ans; };