python实现:
# -*- coding:utf-8 -*- class Solution: MAXINT = 2**31-1 def FindNumbersWithSum(self, array, tsum): # write code here n = len(array) if n==0: return [] i, j = 0, n-1 tmpProd = Solution.MAXINT small, big = None, None while i<j: if array[i]+array[j] < tsum: i += 1 elif array[i]+array[j] > tsum: j -= 1 else: if array[i]*array[j]<tmpProd: tmpProd = array[i]*array[j]#重要! small, big = i, j i += 1#易忘,重要! j -= 1 if small is None: return [] return [array[small], array[big]]python实现:
# -*- coding:utf-8 -*- class Solution: #two pointers def FindContinuousSequence(self, tsum): # write code here if tsum<=0: return [] start, end = 1, 2 tmpSum = start+end result = [] while start<=tsum/2: if tmpSum<tsum: end += 1 tmpSum += end elif tmpSum>tsum and start<=tsum/2: tmpSum -= start start+=1 else: result.append([x for x in range(start, end+1)]) tmpSum -= start start += 1 return result