leetcode face questions 57 - II and the number of consecutive positive sequence s (python).

Here Insert Picture Description
Solution:
This problem can be solved with a sliding window algorithm:
sliding window algorithm first sets two pointers, respectively, left and right, left and rifght pointer Pointer to limit the scope (i.e. alignment scope) sliding window;
sliding window, right and left hand pointers are moved to the right;
find all arranged in the sliding window.

This problem is seeking continuous sequence of positive integers, arrangement thus conceivable to target number is 1 - 1 range;
and target due to the target, a combination which can not be the median of a sequence to a target, and a greater than the median number of compositions;
for example:
the median is 11, ie 6, 6 and the subsequent possible by the arrangement composed of 6;
thus arrayed range in number from 1 to 1 + 2 // target;
left pointer is initialized to 1 , rihgt pointer is also initialized to 1; each range is calculated range (left, right + 1)
If the value is less than the target, then the right + = 1;
if the value is greater than the target, then left + = 1;
if it is equal target value, need to add a left; right hand at the same time also a need to increase;

  1. In the beginning of each element is only arranged in one set, so the need to find the left plus 1;
  2. Current left to right and certainly larger than left to right + 1 and, therefore, add a right, reducing the time complexity, speed up operation;

code show as below:

class Solution:
    def findContinuousSequence(self, target):

    	left = 1
    	right = 1

    	result = []

    	while right <= (target//2 + 1):

    		cur_sum = sum(list(range(left, right + 1)))

    		if cur_sum < target:

    			right += 1

    		elif cur_sum > target:

    			left += 1

    		else:

    			result.append(list(range(left, right + 1)))

    			left += 1

    			right += 1

    	return result
Published 100 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/cy_believ/article/details/104859712