ZZULIOJ 1147: 하위 배열 찾기, Java

ZZULIOJ 1147: 하위 배열 찾기, Java

질문 설명

두 개의 정수 배열이 주어지면 배열 a에는 n개의 요소가 있고 배열 b에는 m개의 요소가 있으며 1<=m<=n<100입니다. 배열 b가 배열 a의 하위 배열인지 확인하세요. 배열 a의 요소 a[i]에서 시작하면 b[0]=a[i], b[1]=a[i+1],…, b[m]=a[i+m]이 됩니다. 이면 배열 b는 배열 a의 하위 배열이라고 합니다.

입력하다

입력의 첫 번째 줄은 두 개의 정수 n과 m이고, 두 번째 줄은 배열 a의 n개의 정수이고, 세 번째 줄은 배열 b의 m개의 정수이며, 각 데이터는 공백으로 구분됩니다.

산출

출력은 한 줄을 차지합니다. b가 a의 하위 배열이면 하위 배열의 i 위치를 출력합니다. 아래 첨자는 0부터 시작하고, 그렇지 않으면 을 출력합니다 No Answer.

샘플 입력복사
8 3
3 2 6 7 8 3 2 5
3 2 5
샘플 출력복사
5
import java.io.*;

public class Main {
    
    
    public static void main(String[] args) throws IOException {
    
    
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        String[] str = bf.readLine().split(" ");
        int n = Integer.parseInt(str[0]);
        int m = Integer.parseInt(str[1]);
        int[] a = new int[n], b = new int[m];
        str = bf.readLine().split(" ");
        for (int i = 0; i < n; i++) {
    
    
            a[i] = Integer.parseInt(str[i]);
        }
        str = bf.readLine().split(" ");
        for (int i = 0; i < m; i++) {
    
    
            b[i] = Integer.parseInt(str[i]);
        }
        boolean ok = false;
        for (int i = 0; i < n - m + 1; i++) {
    
    
            int j;
            for (j = 0; j < m; j++) {
    
    
                if (a[i + j] != b[j]) {
    
    
                    break;
                }
            }
            if (j == m) {
    
    
                ok = true;
                bw.write(i + "\n");
                break;
            }
        }
        if (!ok) bw.write("No Answer\n");
        bw.close();
    }
}

Supongo que te gusta

Origin blog.csdn.net/qq_52792570/article/details/132567018
Recomendado
Clasificación