今天群里有同学问这个题目,写了下,想想还是记下来吧,写都写了。
package study;
import java.util.ArrayList;
import java.util.List;
public class T4 {
/**
* @param arr
* @param b
* @return
*/
public static boolean isSubarray(int[] arr, int[] b) {
boolean boo =false;
int num =0;
ArrayList <Integer> A = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
int a = arr[i];
A.add(a);
}
ArrayList <Integer> B = new ArrayList<Integer>();
for(int i = 0;i < b.length; i++){
int c = b[i];
B.add(c);
}
System.out.println(A+"--------------"+B);
List tempList= new ArrayList();
if(A.size()<B.size()){
List exchangeList =new ArrayList();
exchangeList = B;
B = A;
A = (ArrayList<Integer>) exchangeList;
}
for (int i = 0; i < A.size() && !boo; i++) {
if(i<=A.size()-B.size()){
tempList = (List) A.subList(i, B.size()+i);
for (int j = 0; j <B.size(); j++) {
if(tempList.get(j) == B.get(j) ){
num = num+1;
}
}
if(num == B.size()){
boo = true;
}
System.out.println(num+"---"+i);
num = 0;
}
}
return boo;
}
public static void main(String[] args) {
int [] first = {1,2,2,2,3,3,4};
int [] second = {1,2,2};
int [] thred = {1,2,33,2,2,3,3,4,5};
System.out.println(T4.isSubarray(first, second));
System.out.println(T4.isSubarray(first, thred));
}
}