II. And a continuous positive sequence s

Description Title:
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.

Analysis of ideas:

  • Sliding window left margin setting i, the right boundary is j, then the sliding window is framed by a closed left-right open interval [i,
    J). Note that, in order to facilitate programming, typically expressed as a sliding window closing the left and right open interval. In the beginning, i = 1, j = 1 , sequences located leftmost sliding window, the window size is zero.
  • When the right boundary of the sliding window moves to the right, that is, j = j + 1, a digital multi-window j, and the window will also add
    j. When the left edge of the sliding window moves to the right, i.e. i = i + 1, at least one digital window i, and also it will be subtracted window i.
class Solution {
    public int[][] findContinuousSequence(int target) {
        List<int[]> res=new ArrayList<>();
        int i=1;
        int j=1;
        int sum=0;
        while(i<=target/2){
            if(sum<target){
                sum+=j;
                j++;
            }else if(sum>target){
                sum-=i;
                i++;
            }else{
                int[] arr=new int[j-i];
                for(int k=i;k<j;k++){
                    arr[k-i]=k;
                }
                res.add(arr);
                sum-=i;
                i++;
            }
        }
        return res.toArray(new int[res.size()][]);
    }
}
Published 163 original articles · won praise 13 · views 3799

Guess you like

Origin blog.csdn.net/qq_42174669/article/details/104697988