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;
}
有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~