leet-code/src/main/java/leetcode/editor/cn/ArithmeticSlices.java

75 lines
1.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//如果一个数列 至少有三个元素 ,并且任意两个相邻元素之差相同,则称该数列为等差数列。
//
//
// 例如,[1,3,5,7,9]、[7,7,7,7] 和 [3,-1,-5,-9] 都是等差数列。
//
//
//
//
// 给你一个整数数组 nums ,返回数组 nums 中所有为等差数组的 子数组 个数。
//
// 子数组 是数组中的一个连续序列。
//
//
//
// 示例 1
//
//
//输入nums = [1,2,3,4]
//输出3
//解释nums 中有三个子等差数组:[1, 2, 3]、[2, 3, 4] 和 [1,2,3,4] 自身。
//
//
// 示例 2
//
//
//输入nums = [1]
//输出0
//
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 5000
// -1000 <= nums[i] <= 1000
//
//
//
// Related Topics 数组 动态规划
// 👍 309 👎 0
package leetcode.editor.cn;
//413:等差数列划分
class ArithmeticSlices {
public static void main(String[] args) {
//测试代码
Solution solution = new ArithmeticSlices().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int numberOfArithmeticSlices(int[] nums) {
if (nums.length < 3) {
return 0;
}
int sub = nums[0] - nums[1], count = 0;
int sum = 0;
for (int i = 2; i < nums.length; i++) {
if (nums[i - 1] - nums[i] == sub) {
count++;
} else {
sub = nums[i - 1] - nums[i];
count = 0;
}
sum += count;
}
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}