leetcode face questions 57 - II and sliding window consecutive positive sequence s.

leetcode face questions 57 - II and sliding window consecutive positive sequence s.

leetcode 2020 March 1 question daily punch
to prove safety offer

Problem: enter a positive integer target, output of all consecutive positive integers, and the target sequence (containing at least two numbers). The numbers in ascending sequence are arranged in ascending order of different sequences according to the first digit.

Example 1:
Input: target = 9
Output: [[2,3,4], [4,5]]
Example 2:
Input: target = 15
Output: [[1,2,3,4,5], [4 , 5,6], [7,8]]
limit: 1 <= target <= 10 ^ 5

Original title link: https: //leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/

Ideas: PythonSliding window: L is the left edge of the window, r is the right window border. When the digital window and less than target, r right; greater than target, l right; it is equal to obtain a target solution.

Details: The first two cycles solved by violence, Sure exceeds a time limit.

Code:

class Solution(object):
    def findContinuousSequence(self, target):
        """
        :type target: int
        :rtype: List[List[int]]
        """
        # 滑动窗口
        # sum = (start+end)*(end-start+1)/2
        ans=[]

        l=1
        r=2

        while l <= target/2:
            sum = (l+r)*(r-l+1)/2
            if sum == target:
                tem = []
                for i in range(l,r+1):
                    tem.append(i)
                ans.append(tem)
                l+=1
                r=l+1
            elif sum > target:
                l+=1
                r=l+1
            elif sum < target:
                r+=1
            
        return ans

As reproduced, please indicate the source! All Rights Reserved

Published 20 original articles · won praise 1 · views 207

Guess you like

Origin blog.csdn.net/weixin_43973433/article/details/104849069