You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java按顺序检查数组是否包含指定子数组问题求助

Hey there! Let's work through this problem where you need to check if your input array arr2 appears in arr1 in the correct order—either as a consecutive subarray (which matches your example where [21,19] returns false) or just as a subsequence (order matters but elements don't have to be adjacent). Here's how to fix your code:

First, Let's Clarify the Two Scenarios

Based on your examples:

  • When arr1 = [45,21,1,19,8,90,21,2] and arr2 = [21,1,19], you want true (this works as both a consecutive subarray and subsequence)
  • When arr1 = [45,21,1,19,8,90,21,2] and arr2 = [21,19], you want false—this means you're looking for consecutive elements, not just ordered ones.

Solution 1: Check for Consecutive Subarray

This method verifies if arr2 exists as a continuous block in arr1 with the exact order.

import java.util.Random;
import java.util.Scanner;

public class Main {
    private static int[] array1;

    // Initialize arr1 with random numbers
    public static int[] list() {
        array1 = new int[10];
        Random random = new Random();
        for (int i = 0; i < array1.length; i++) {
            array1[i] = random.nextInt(100); // Generate random numbers between 0-99
        }
        return array1;
    }

    // Check if arr2 is a consecutive subarray of arr1
    public static boolean isConsecutiveSubarray(int[] arr2) {
        // Edge cases: empty arr2 is considered a match, or adjust if needed
        if (arr2 == null || arr2.length == 0) {
            return true;
        }
        // If arr2 is longer than arr1, it can't be a subarray
        if (arr2.length > array1.length) {
            return false;
        }

        // Iterate through all possible starting positions in arr1
        for (int i = 0; i <= array1.length - arr2.length; i++) {
            boolean isMatch = true;
            // Compare each element of arr2 to the consecutive elements in arr1
            for (int j = 0; j < arr2.length; j++) {
                if (array1[i + j] != arr2[j]) {
                    isMatch = false;
                    break;
                }
            }
            if (isMatch) {
                return true;
            }
        }
        // No matching consecutive block found
        return false;
    }

    // Get user input to create arr2
    public static int[] getUserInputArray() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of elements in arr2: ");
        int size = scanner.nextInt();
        int[] arr2 = new int[size];
        System.out.println("Enter the elements separated by spaces:");
        for (int i = 0; i < size; i++) {
            arr2[i] = scanner.nextInt();
        }
        scanner.close();
        return arr2;
    }

    public static void main(String[] args) {
        // Initialize the random array arr1
        array1 = list();
        System.out.println("Generated arr1: ");
        for (int num : array1) {
            System.out.print(num + " ");
        }
        System.out.println();

        // Get user's arr2
        int[] arr2 = getUserInputArray();

        // Check and print result
        boolean result = isConsecutiveSubarray(arr2);
        System.out.println("Does arr1 contain arr2 as a consecutive subarray? " + result);
    }
}

Solution 2: Check for Subsequence (Order Matters, No Need for Consecutive)

If you ever need to allow arr2 elements to appear in order but not necessarily next to each other (e.g., [21,19] would return true for your sample arr1), use this method instead:

// Check if arr2 is a subsequence of arr1
public static boolean isSubsequence(int[] arr2) {
    if (arr2 == null || arr2.length == 0) {
        return true;
    }
    int arr2Pointer = 0;
    // Traverse arr1 and look for arr2 elements in order
    for (int num : array1) {
        if (num == arr2[arr2Pointer]) {
            arr2Pointer++;
            // If we've found all elements of arr2, return true
            if (arr2Pointer == arr2.length) {
                return true;
            }
        }
    }
    // Return true only if all elements of arr2 were found in order
    return arr2Pointer == arr2.length;
}

You can replace isConsecutiveSubarray with isSubsequence in the main method to use this logic instead.

内容的提问来源于stack exchange,提问作者Ali Göktaş

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:54:30