• 等差数列划分


    题目:

    如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。
    例如,以下数列为等差数列:
    1, 3, 5, 7, 9
    7, 7, 7, 7
    3, -1, -5, -9
    以下数列不是等差数列。
    1, 1, 2, 5, 7
    数组 A 包含 N 个数,且索引从0开始。数组 A 的一个子数组划分为数组 (P, Q),P 与 Q 是整数且满足 0<=P<Q<N 。
    如果满足以下条件,则称子数组(P, Q)为等差数组:
    元素 A[P], A[p + 1], ..., A[Q - 1], A[Q] 是等差的。并且 P + 1 < Q 。
    函数要返回数组 A 中所有为等差数组的子数组个数。

    示例:

    A = [1, 2, 3, 4]
    返回: 3, A 中有三个子等差数组: [1, 2, 3], [2, 3, 4] 以及自身 [1, 2, 3, 4]。
     

    代码:

    public class EaquealQueue {
    public static int countOfArithmetic(int[] A) {
    int count = 0;
    if(A.length<3){
    return 0;
    }
         //重点:判断等差数列

    for(int i=0; i<A.length-2; i++){
    for(int j=i+1; j<A.length-1; j++){
    if(A[j + 1] - A[j] == A[i + 1] -A[i]){
    count++;
    }else{
    break;
    }
    }
    }
    return count;
    }

    public static void main(String[] args){
    int[] A = {1,2,3,4,5,9,10,11,12};
    System.out.print(countOfArithmetic(A));
    }
    }

    //优化一下时间复杂度后:
    public class EaquealQueue {
    public static int countOfArithmetic(int[] A) {
    int count = 0;
    int lianXu = 0;
    if(A.length<3){
    return 0;
    }
         //重点:判断等差数列
    for(int i=1; i<A.length-1; i++){
    if (A[i] - A[i-1] == A[i+1] - A[i]){
    lianXu ++;
    }else {
    lianXu = 0;
    }
    count += lianXu;
    }
    return count;
    }

    public static void main(String[] args){
    int[] A = {1,2,3,4};
    System.out.print(countOfArithmetic(A));
    }
    }


     
  • 相关阅读:
    .Net Core小技巧
    调用Kubernetes API操作Kubernetes
    在CentOS 7+ 安装Kubernetes入门(单Master)
    Linux命令行基础
    使用wireshark学习TCP
    Redis原子性写入HASH结构数据并设置过期时间
    Vue使用小结
    JAVA & .NET创建对象构造函数调用顺序
    .NET 中的序列化 & 反序列化
    ASP.NET Core中使用Graylog记录日志
  • 原文地址:https://www.cnblogs.com/cdlyy/p/12081101.html
Copyright © 2020-2023  润新知