public class Solution {
public int NumberOfArithmeticSlices(int[] A) {
int curr = , sum = ;
for (int i = ; i < A.Length; i++)
if (A[i] - A[i - ] == A[i - ] - A[i - ])
{
curr += ;
sum += curr;
}
else
{
curr = ;
}
return sum;
}
}

https://leetcode.com/problems/arithmetic-slices/#/description

补充一个java的实现:

 class Solution {
public int numberOfArithmeticSlices(int[] A) {
if (A == null || A.length == ) {
return ;
}
int n = A.length;
int[] dp = new int[n];
for (int i = ; i < n; i++) {
if (A[i] - A[i - ] == A[i - ] - A[i - ]) {
dp[i] = dp[i - ] + ;
}
}
int total = ;
for (int cnt : dp) {
total += cnt;
}
return total;
}
}

解释:

dp[i] 表示以 A[i] 为结尾的等差递增子区间的个数。

因为递增子区间不一定以最后一个元素为结尾,可以是任意一个元素结尾,因此需要返回 dp 数组累加的结果。

leetcode413的更多相关文章

  1. [Swift]LeetCode413. 等差数列划分 | Arithmetic Slices

    A sequence of number is called arithmetic if it consists of at least three elements and if the diffe ...

随机推荐

  1. 【剑指offer】04A二维数组中的查找,C++实现

    1.题目 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数数组和一个整数,判断数组中是否含有该整数. 2.思路 首先选取数 ...

  2. HDU - 2973:YAPTCHA (威尔逊定理)

    The math department has been having problems lately. Due to immense amount of unsolicited automated ...

  3. BZOJ1014 JSOI2008 火星人prefix 【非旋转Treap】*

    BZOJ1014 JSOI2008 火星人prefix Description 火星人最近研究了一种操作:求一个字串两个后缀的公共前缀.比方说,有这样一个字符串:madamimadam,我们将这个字符 ...

  4. LeetCode 549. Binary Tree Longest Consecutive Sequence II

    原题链接在这里:https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/description/ 题目: G ...

  5. Cocos2d-x学习笔记1

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/u014734779/article/details/26077453 1.创建新的cocos2d-x ...

  6. Arrays--codility

    lesson 2: Arrays exercise: Problem: Given array A consisting of N integers, return the reversed arra ...

  7. websphere删除概要文件(profiles)的方式

    [b]删除概要文件:[/b]方案一:1.找到profileRegistry.xml,在目录IBM\WebSphere\AppServer\properties里,去掉想删除的profile的配置即可. ...

  8. golang回调函数的例子

    package main import "fmt" type TestStruct struct { } func (object *TestStruct) test(msg st ...

  9. 【Leetcode 167】Two Sum II - Input array is sorted

    问题描述:给出一个升序排列好的整数数组,找出2个数,它们的和等于目标数.返回这两个数的下标(从1开始),其中第1个下标比第2个下标小. Input: numbers={2, 7, 11, 15}, t ...

  10. bc显示小数点前的0

    bc是强大而常用的计算工具.不过在除法运算时,如果得到的结果值小于1,得到的小数前面的0不存.本篇提供几个常用小数点前缺0的解决方法. [root@maqing ~]# bc bc Copyright ...