程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Sword finger offer python:58 Continuous positive sequence with sum s

編輯:Python

subject : Xiao Ming likes mathematics very much , One day when he was doing his math homework , Require calculation 9~16 And , He immediately wrote out the correct answer is 100. But he is not satisfied with it , He was thinking about how many consecutive positive sequences sum up to 100( Include at least two numbers ). It didn't take long , And he gets another set of consecutive positive numbers 100 Sequence :18,19,20,21,22. Now leave it to you , Can you also quickly find out all the sum for S Continuous positive sequence of ?

Ideas : Speed pointer . The qualification is , The sum of these sequences will not exceed s Half of ,s/2 + (s/2 +1) Must be greater than s, So the end condition of the cycle is : Less than s/2.

1) When the sum of this sequence <s when , Quick pointer +1;

2) When the sequence and <=s when (=s when , Record the sequence and ), Let the current sum minus the minimum value approach slowly s.

Code :

class Solution:
def func(self , s):
end = s // 2
lo , hi , cur_sum = 1 ,2 ,3
res = []
while lo < end:
if cur_sum < s:
hi += 1
cur_sum += hi
else:
if cur_sum == s:
res.append(list(range(lo , hi+1)))
cur_sum -= lo
lo += 1


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved