Sliding window-find all consecutive subarrays of an array [Learning Algorithm]

Sliding window-find all consecutive subarrays of an array [Learning Algorithm]

Preface

2023-9-24 22:46:27

The following content is from "[Learning Algorithm]"
and is for learning and communication purposes only.

copyright

Delete the following words when publishing on other platforms.
This article was first published on the CSDN platform.
The author is CSDN@日星月云.
The homepage of the blog is https://blog.csdn.net/qq_51625007.
Delete the above words when publishing on other platforms.

recommend

none

Sliding window - find all consecutive subarrays of an array

code

import java.util.ArrayList;
import java.util.Scanner;

/*
3
1 2 3
 */
public class Main2 {
    
    


    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
    
    
            a[i] = scanner.nextInt();
        }

        ArrayList<ArrayList<Integer>> lists = subArr(a);
        System.out.println(lists);

    }

    public static ArrayList<ArrayList<Integer>> subArr(int[] nums) {
    
    
        ArrayList<ArrayList<Integer>> lists=new ArrayList<>();

        //滑动窗口的大小
        for (int k = 1; k <= nums.length; k++) {
    
    
            //左边界
            for (int i = 0; i < nums.length; i++) {
    
    
                if (i+k > nums.length){
    
    
                    continue;
                }
                ArrayList<Integer> list=new ArrayList<>();
                //窗口
                for (int j = i; j < i+k; j++) {
    
    
                    list.add(nums[j]);
                }
                lists.add(list);
            }
        }
        return lists;
    }
}

at last

2023-9-24 22:52:48

We all have a bright future

I wish you all the best in your postgraduate entrance exams, I wish you all success
in your work, I wish you all get what you wish for, like, collect and follow.


Guess you like

Origin blog.csdn.net/qq_51625007/article/details/133255080