Leetcode 1630. Arithmetic Subarrays
题目链接: Arithmetic Subarrays
难度:Medium
题目大意:
根据题目要求构建子数组,判断子数组是否是Arithmetic数组。
思路:
写一个函数来判断一个数组是否是Arithmetic数组。然后按照题目要求依次构造子数组,进行判断即可。
代码
class Solution {
public List<Boolean> checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {
int m=l.length;
List<Boolean> res=new ArrayList<>();
for(int i=0;i<m;i++){
Boolean item=isArithmetic(Arrays.copyOfRange(nums,l[i],r[i]+1));
res.add(item);
}
return res;
}
public Boolean isArithmetic(int[] nums){
Arrays.sort(nums);
int len=nums.length;
int d=nums[1]-nums[0];
for(int i=2;i<=len-1;i++){
if(nums[i]-nums[i-1]!=d){
return false;
}
}
return true;
}
}