剑指Offer 57
Posted asenyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指Offer 57相关的知识,希望对你有一定的参考价值。
和为S的两个数字:
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def FindNumbersWithSum(self, array, tsum): 4 n = len(array) 5 i,j = 0,n-1 6 while i<j: 7 cur = array[i] + array[j] 8 if cur == tsum: 9 return [array[i],array[j]] 10 if cur < tsum: 11 i += 1 12 else: 13 j -= 1 14 return [] 15 # write code here
和为S的连续正数序列:
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def FindContinuousSequence(self, tsum): 4 start,end,cursum = 1,2,3 5 result = [] 6 while end < tsum: 7 if cursum > tsum: 8 cursum -= start 9 start += 1 10 elif cursum < tsum: 11 end += 1 12 cursum += end 13 else: 14 l = [] 15 for i in range(start,end+1): 16 l.append(i) 17 result.append(l) 18 cursum -= start 19 start += 1 20 end += 1 21 cursum += end 22 return result 23 # write code here
以上是关于剑指Offer 57的主要内容,如果未能解决你的问题,请参考以下文章