# 0413. Arithmetic Slices ###### tags: `Leetcode` `Medium` `Bloomberg` `Arithmetic Sequence` Link: https://leetcode.com/problems/arithmetic-slices/ ## 思路 $O(N)$ $O(1)$ sliding window 每次先找到最长的subsequence,如果长度大于等于3,那么就开始计算它包含几个有效的subsequence 计算方法: 假设subsequence长度为a(a>=3),则长度为a的答案有1个,a-1的有2个,..., 3的有(a+1)-3个,所以总共有(a-3+1)(a-3+1+1)个 ## Code ```java= class Solution { public int numberOfArithmeticSlices(int[] nums) { int left = 0; int right = 1; int ans = 0; while(right < nums.length){ int diff = nums[right]-nums[left]; while(right+1<nums.length && nums[right]+diff == nums[right+1]){ right++; } if(right-left+1>=3){ ans += (right-left+1-3+1)*(right-left+1-3+1+1)/2; } left = right; right++; } return ans; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up