题目:
给定一个长度为 n 的整数序列,一级一个长度为 m 的整数序列,判断 a 序列是否为 b 序列的子列。子序列指序列的一部分项按原有次序排列。
思路:
使用双指针算法,两个指针分别指向 a 和 b 的首部。一次检查 a [ i ] 是否等于 b [ j ],若相等,则 i 和 j 均加 1。若不相等则 i 不动,j 加1。
最后判断 i 与 a 的长度是否相等。若相等则为子序列,反之则不是。
代码如下:
package cn.liyi.day08;
import java.util.Scanner;
public class Demo2816 {
public static int N = 10010;
public static int[] a = new int[N];
public static int[] b = new int[N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for (int i = 0; i < n; i ++)
a[i] = sc.nextInt();
for (int i = 0; i < m; i ++)
b[i] = sc.nextInt();
int i = 0, j = 0;
while(i < n && j < m) {
if(a[i] == b[j])
i ++;
j ++;
}
if(i == n)
System.out.println("YES");
else
System.out.println("NO");
}
}