Leetcode 1630. Arithmetic Subarrays
- 题目
- 解法1:sort
- 解法2:利用set
题目
解法1:sort
class Solution:def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:def check(array):array.sort()dis = array[1]-array[0]for i in range(2,len(array)):if array[i]-array[i-1] != dis:return Falsereturn Trueans = []for i in range(len(l)):if len(nums[l[i]:r[i]+1])<=1:ans.append(True)else:if check(nums[l[i]:r[i]+1]):ans.append(True)else:ans.append(False)return ans
解法2:利用set
复杂度跟sort是一样的
这边要注意对于step是不是0的判断是必须的,因为for loop的step不能是0
class Solution:def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:def check(array):_max,_min,_st = max(array),min(array),set(array)if (_max - _min)%(len(array)-1) != 0:return Falsestep = (_max-_min)//(len(array)-1)if not step: return Truefor num in range(_min,_max,step):if num not in _st:return Falsereturn Trueans = [False]*len(l)for i in range(len(l)):if check(nums[l[i]:r[i]+1]):ans[i] = Truereturn ans