LeetCode face questions 57 - II and the number of consecutive positive sequence s (punch sixth day).

topic

Interview questions 57 - II and the number of consecutive positive sequence s.
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

Problem-solving ideas

Because the subject is a consecutive number required, it is possible to use a sliding window mechanism to solve the problem
of time complexity is O (target), the spatial complexity is O (1);

Code

class Solution {
    public int[][] findContinuousSequence(int target) {
        //滑动窗口
		List<int[]> ans=new ArrayList<>();
		for(int i=1,j=i+1,sum=i+j;i<=target/2&&j<target;) {
			if(sum==target) {
				int[] a=new int[j-i+1];
				for(int k=i;k<=j;k++)
					a[k-i]=k;
				ans.add(a);
				i++;
				j=i+1;
				sum=i+j;
			}
			else {
				if(sum<target){j++;sum=sum+j;}
				else {
					sum=sum-i;
					i++;
				}
			}
		}
		return ans.toArray(new int[ans.size()][]);
    }
}
Published 11 original articles · won praise 6 · views 1584

Guess you like

Origin blog.csdn.net/qq_41119146/article/details/104699553