1 import sys 2 class Solution: 3 def twoSumLessThanK(self, A: 'List[int]', K: int) -> int: 4 A.sort() 5 n = len(A) 6 if n == 1: 7 return -1 8 if n == 2: 9 return A[0] + A[1] if A[0] + A[1] < K else -1 10 i,j = 0,n-1 11 mindiff = sys.maxsize 12 minsum = -1 13 while i < j: 14 cursum = A[i] + A[j] 15 if cursum < K: 16 diff = K - cursum 17 if diff < mindiff: 18 mindiff = diff 19 minsum = cursum 20 i += 1 21 else: 22 j -= 1 23 return minsum
思路:双指针,先将数组排序,在从两边向中间移动,每次计算与K的差值,保存最小的差值时两个数的和。