题目描述
思路:常规思路是遍历两个数组,寻找两个元素之和为目标值,但是难点在于,当数组过大时,此方法耗时太长,因此要找寻一种快速遍历数组的方法。可以先对数组进行排列,在遍历数组,然后运用两个指针,分别指向两个数组,一个指向数组头,一个指向数组尾。
class Solution:
def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int:
count = 0
i, j = 0, len(drinks)-1
staple.sort()
drinks.sort()
while i < len(staple) and j >= 0:
if staple[i]+drinks[j] <= x:
count = count+j+1
i += 1
else:
j = j -1
return count % (10**9+7)
请多多指教!