413. 等差数列划分
dp[i]表示以nums[i]结尾的等差数列的个数
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
dp = [0]*len(nums)
for i in range(2,len(nums)):
if nums[i]-nums[i-1] == nums[i-1]-nums[i-2]:
dp[i] = dp[i-1]+1
else:
dp[i] = 0
return sum(dp)
18. 四数之和
两层循环+双指针
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
ans=[]
n = len(nums)
if n<=3:
return ans
nums.sort()
for i in range(n-3):
if i>0 and nums[i]==nums[i-1]: # 跳过重复的数字
continue
if nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target: # 如果最小的四个数字和都大于target说明无解,直接退出本层循环
break
if nums[i]+nums[n-1]+nums[n-2]+nums[n-3]<target: #如果nums[i]当前数字加最大三个数字还是小于target说明当前数字太小,无解直接跳到i+1
continue
for j in range(i+1,n-2):
if j > i+1 and nums[j]==nums[j-1]:
continue
if nums[i]+nums[j]+nums[j+1]+nums[j+2]>target:
break
if nums[i]+nums[j]+nums[n-1]+nums[n-2]<target:
continue
left = j+1
right = n-1
while left<right:
if nums[i]+nums[j]+nums[left]+nums[right]==target:
ans.append([nums[i],nums[j],nums[left],nums[right]])
while left<right and nums[left] == nums[left+1]: #跳过重复的数字
left+=1
left+=1
while left<right and nums[right] == nums[right-1]:#跳过重复的数字
right-=1
right-=1
elif nums[i]+nums[j]+nums[left]+nums[right]<target:
left +=1
else:
right -=1
return ans