leetcode每日一题题解—— 413. 等差数列划分——2021年8月10日

413. 等差数列划分

Title Description

An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.

A subarray is a contiguous subsequence of the array.

Example 1:

Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

Example 2:

Input: nums = [1]
Output: 0

Constraints:

1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000

题目描述

如果一个数列 至少有三个元素 ,并且任意两个相邻元素之差相同,则称该数列为等差数列。

例如,[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

解题思路

  1. 观察发现当整个数组为(1, 2, 3, 4, 5, 6)的时候,我们先取出前三个,(1, 2, 3)的等差数列的个数为1,(1, 2, 3, 4)的等差数列的个数为3,(1, 2, 3, 4, 5)的等差数列的个数为6,(1, 2, 3, 4, 5, 6)的等差数列个数为10
  2. 在一个等差数列中加入一个数字,如果还保持着等差数列的特性,每次的增量都会加1
  3. 如果刚加进来的数字与原先的序列构不成等差数列,就将增量置为0,接下来继续循环

代码

/**

 * @param {number[]} nums

 * @return {number}

 */

var numberOfArithmeticSlices = function (nums) {


    // 如果数组的长度小于3直接返回0

    if (nums.length < 3) {

        return 0

    }


    // 显示等差数列长度

    var dengcha = 2;
    

    // 要返回的等差数组的子数组个数

    var ret = 0;


    // 随等差数列的长度增加而增加的组合情况(根据数学规律得出)

    var jiashu = 1;

    for (var i = 0; i < nums.length - 2; i++) {

        // for循环三个数中满足等差,变量变化情况

        if (nums[i] - nums[i + 1] == nums[i + 1] - nums[i + 2]) {

            dengcha++

            ret += jiashu;

            jiashu++
        }

        // 若循环到一个不满足的数,数列长度和增加的组合情况,回到最初始的状态,准备迎接下一个等差数列
        else {
            dengcha = 2;
            jiashu = 1;
        }
    }
    return ret
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值