leetcode413
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的更多相关文章
- [Swift]LeetCode413. 等差数列划分 | Arithmetic Slices
A sequence of number is called arithmetic if it consists of at least three elements and if the diffe ...
随机推荐
- phpcms v9取消验证码
phpcms/modules/admin/index.php// $code = isset($_POST['code']) && trim($_POST['code']) ? tri ...
- Cannot setup mail box on Android
Error: “You don’t have permission to sync with this server” Solution: “You have 10 phone partnershi ...
- 模块(Modules)
一.引入模块 模块:当编写更大的应用程序时,所有的代码肯定会分成多个文件,这样便于维护,另外已经编写好的函数和对象在被多个程序中使用时,不用把函数和对象拷贝到每个程序中. 模块支持以上功能,在Pyth ...
- javascript的slice()与splice()方法
(1)数组和String对象都有slice()方法. //Array var list = ['A','B','C','D','DS']; console.log(list.slice(,));//截 ...
- Jmeter简单的接口测试
1.新建线程组 2.编辑线程组信息 3.在线程组中添加HTTP信息头管理器 4.配置HTTP信息头管理器 参数格式配置 5.在线程组中添加HTTP请求 6.编辑HTTP请求信息 7.添加响应断言 8. ...
- Python学习-类
类是对象的模板或蓝图,类是对象的抽象化,对象是类的实例化 在python中,一个对象的特征也称为属性(attribute),它所具有的的行为也称为方法(method) 对象 = 属性(特征)+方法(行 ...
- waitKey()
waitKey仅对窗口机制起作用,即namedWindow产生的窗口.若在此之前没有产生窗口,则waitKey相当于未执行. 注:namedWindow产生的窗口: namedWindow()+ims ...
- Python 运行其他程序
10.4 运行其他程序 在Python中可以方便地使用os模块运行其他的脚本或者程序,这样就可以在脚本中直接使用其他脚本,或者程序提供的功能,而不必再次编写实现该功能的代码.为了更好地控制运行的进程, ...
- python ctypes 和windows DLL互相调用
图片项目
- python read txt file
refer to: http://www.jianshu.com/p/d8168034917c http://www.liaoxuefeng.com/wiki/001374738125095c955c ...