Old Wei wins the offer to take you to learn --- Brush title series (41 and continuous positive number sequence S)

41. In a continuous and positive sequence S

problem:

Xiao Ming is very fond of mathematics, one day when he was doing math homework, required to calculate and 9 to 16, he immediately wrote the correct answer is 100. But he was not satisfied with this, he wondered how many kinds of continuous positive number sequence is 100 (including at least two numbers). Before long, he got another set of consecutive positive number and a sequence of 100: 18,19,20,21,22. Now the question to you, you can also quickly identify all positive and continuous sequence S? Good Luck!

solve:

thought:

Find an answer in the answer sheet, said, well, called the two-hand technique, which is equivalent to a window, the window left and right sides are two pointers, we have to determine the location and width of the window in the window based on the sum. An incredibly prolific ideas, although two-pointer or a so-called sliding window technique is still quite common, but the question really can not think of this idea.

python code:

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        low=1   #两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小
        high=2
        result=[]   ##存放结果
        while(high>low):
            csum=((low+high)*(high-low+1)//2)  #由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2
            tmp_list=[]
            if(csum==tsum):   #相等,那么就将窗口范围的所有数添加进结果集
                for i in range(low,high+1):
                    tmp_list.append(i)
                result.append(tmp_list)
                low+=1
            elif(csum<tsum):   #如果当前窗口内的值之和小于sum,那么右边窗口右移一下
                high+=1
            else:
                low+=1    #如果当前窗口内的值之和大于sum,那么左边窗口右移一下
                
        return result

Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/105051995