Cattle off network - to prove safety office- and continuous positive number sequence S

Topic : 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?
Thinking : We use two variables, small and big sequences were recorded minimum and maximum values, and the two are initialized to 1 and 2, with the cursum recorded from small to big, and number range, when cursum equal sum, from small to big output sequence. If less than cursum sum, increased big, if greater than cursum sum, increased small. Small until the sum is greater than or equal to half.

class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum) {
        if(sum<2) return {};
        vector<vector<int> > ans;
        int small = 1;
        int big =2;
        int mid=(small+sum)/2;
        int cursum=small+big;
        while(small<mid)
        {
            if (cursum ==sum)
                ans.push_back(result(small,big));
            while(cursum>sum&&small<mid)
            {
                cursum-=small;
                ++small;
                if (cursum ==sum)
                ans.push_back(result(small,big));
            }
            ++big;
            cursum+=big;
        }
        return ans;
    }
    vector<int> result(int small,int big)
    {
        vector<int> ans;
        for(int i=small;i<=big;++i)
            ans.push_back(i);
        return ans;
    }
};

python's solution:

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        if tsum <= 2:
            return []
        ans = []
        small = 1
        big = 2
        mid = int((small + tsum) / 2)
        cursum = small + big
        while small < big and small < mid:
            if cursum == tsum:
                ans.append(self.result(small, big))
            while cursum > tsum and small < mid:
                cursum -= small
                small += 1
                if cursum == tsum:
                    ans.append(self.result(small, big))
            big += 1
            cursum += big
        return ans

    def result(self, small, big):
        ans = []
        while (small <= big):
            ans.append(small)
            small += 1
        return ans


Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91345905