zoukankan      html  css  js  c++  java
  • leetcode413

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

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

    补充一个java的实现:

     1 class Solution {
     2     public int numberOfArithmeticSlices(int[] A) {
     3         if (A == null || A.length == 0) {
     4             return 0;
     5         }
     6         int n = A.length;
     7         int[] dp = new int[n];
     8         for (int i = 2; i < n; i++) {
     9             if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
    10                 dp[i] = dp[i - 1] + 1;
    11             }
    12         }
    13         int total = 0;
    14         for (int cnt : dp) {
    15             total += cnt;
    16         }
    17         return total;
    18     }
    19 }

    解释:

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

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

  • 相关阅读:
    css3 3d 转换
    css3 动画序列
    css3 动画
    2d 转换之缩放
    2d 转换中心点
    css3 书写 动画三角形
    2d 旋转
    2D转换
    伪元素 字体图标
    风陵01
  • 原文地址:https://www.cnblogs.com/asenyang/p/6786665.html
Copyright © 2011-2022 走看看