算法笔试题--有两个数组,求第二个数组在第一个数组中的位置(数组要连续比对)

今天面试的时候,遇到了这道面试题,自己思路上是对的,但是因为是手写的,可能细节上有错误,导致被刷下来
百度了一下,找到有人使用双重for循环的写法
https://www.cnblogs.com/jasonboren/p/13284829.html
下面贴上我自己在面试时的的代码(已修改)
1 public class SubArrayDemo { 2 public static void main(String[] args) { 3 System.out.println(sub(new int[]{4,5,6,7,5,6,8},new int[]{5,6})); //4 4 System.out.println(sub(new int[]{4,5,7,5,8},new int[]{5,6})); //-1 5 System.out.println(sub(new int[]{4,5,6,7,5,6,8},new int[]{6})); //5 6 System.out.println(sub(new int[]{4,5,6,7,5,6,8},new int[]{4,5,6})); //0 7 } 8 9 public static int sub(int[] A,int[] B){ 10 Map<Integer,Integer> map = new HashMap<>(); 11 int i = 0;int j = 0; 12 while (i < A.length){ 13 if (A[i] == B[j]){ 14 map.put(j,i); 15 i++; 16 j++; 17 }else{ 18 j = 0; 19 i++; 20 } 21 if (j >= B.length){ 22 j = 0; 23 } 24 } 25 if (!map.containsKey(B.length - 1)){ 26 return -1; 27 }else { 28 return map.get(B.length - 1) - B.length + 1; 29 } 30 } 31 }
作者水平有限,如有错误,欢迎指出

浙公网安备 33010602011771号