2024.1.23力扣每日一题——最长交替子数组

题目来源

力扣每日一题;题序:2765

我的题解

方法一 枚举

每次都以两个相邻作为满足要求的循环数据,并且以一个布尔变量控制循环的位置

时间复杂度:O(n)
空间复杂度:O(1)

public int alternatingSubarray(int[] nums) {
   
  int n=nums.length;
    int a=nums[0];
    int b=nums[1];
    int res=b-a==1?2:-1;
    int t=res;
    boolean flag=false;
    for(int i=2;i<n;i++){
   
        int c=nums[i];
        int d=!flag?a:b;
        //不仅仅判断是否形成循环,还要判断拟定的循环数据是不是满足要求
        if(c==d&&t!=-1){
   
            flag=!flag;
            t+=1;
        }else{
   
            a=nums[i-1];
            b=c;
            flag=false;
            res=Math.max(res,t);
            t=b-a==1?2:-1;
        }
    }
    res=Math.max(res,t);
    return res;
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

相关推荐

  1. 每日2765交替数组

    2024-01-26 23:54:01       72 阅读
  2. 2024.1.23每日——交替数组

    2024-01-26 23:54:01       61 阅读
  3. 2765-交替数组

    2024-01-26 23:54:01       69 阅读
  4. 每日OJ_回文串dp⑤_516. 回文序列

    2024-01-26 23:54:01       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-26 23:54:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-26 23:54:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-26 23:54:01       87 阅读
  4. Python语言-面向对象

    2024-01-26 23:54:01       96 阅读

热门阅读

  1. 整数反转算法(leetcode第7题)

    2024-01-26 23:54:01       54 阅读
  2. vue3常用代码

    2024-01-26 23:54:01       59 阅读
  3. Oracle中如何把整个表作为参数传递

    2024-01-26 23:54:01       49 阅读
  4. sudo 授权问题

    2024-01-26 23:54:01       55 阅读
  5. Python中写入csv格式文件出现乱码的解决方法

    2024-01-26 23:54:01       54 阅读
  6. Git 对文件名大小写不敏感的问题解决方案

    2024-01-26 23:54:01       59 阅读
  7. 常见的循环结构

    2024-01-26 23:54:01       53 阅读
  8. 温湿度传感器的工作原理

    2024-01-26 23:54:01       53 阅读
  9. ChatGPT AI革命-阅读心得

    2024-01-26 23:54:01       86 阅读