给你一个下标从 0 开始的整数数组 nums ,该数组的大小为 n ,请你计算 nums[j] - nums[i] 能求得的 最大差值 ,其中 0 <= i < j < n 且 nums[i] < nums[j] 。
返回 最大差值 。如果不存在满足要求的 i 和 j ,返回 -1 。
法一:暴力(遍历两遍)
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
result = 0
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[j]-nums[i]>result:
result = nums[j]-nums[i]
if result == 0:
return -1
else:
return result
法二:每次加一进行比较
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
small=nums[0]
big=nums[1]-nums[0]
for i in range(1,len(nums)-1):
small = min(small,nums[i])
big= max(big,nums[i+1]-small)
if big <1:
return -1
else:
return big
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
small = abs(nums[0])
big = nums[0]
for i in range(1,len(nums)):
if small == abs(nums[i]): #原来的最近距离和新的距离相等
big = max(nums[i],big) #取原数大的 为最大值
else:
small=min(small,abs(nums[i]))
if small ==abs(nums[i]): #如果新的距离为唯一最近距离
big =nums[i] #取新的原数 为最大值
return big
法一:两个循环遍历(退出)
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
new_prices=[]
for i in range(len(prices)):
count = 0
for j in range(i+1,len(prices)):
if prices[j]<=prices[i]:
count = prices[j]
break
new_prices.append(prices[i]-count)
return new_prices
法二:双指针
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
if len(prices)==1:
result = prices
a,b=0,1
while a<len(prices)-1:
if prices[b]<=prices[a]:
prices[a]-=prices[b]
a+=1
b=a+1
else:
b+=1
if b==len(prices):
a+=1
b=a+1
return prices
class Solution:
def intersection(self, nums: List[List[int]]) -> List[int]:
def f(lst1,lst2):
new=[]
for i in range(len(lst1)):
for j in range(len(lst2)):
if lst1[i]==lst2[j]:
new.append(lst1[i])
return new
if len(nums)==1:
nums[0].sort()
return nums[0]
new = f(nums[0],nums[1])
for i in range(2,len(nums)):
new=f(new,nums[i])
new.sort()
return new