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

java代码实现

public class SubArray {
    public static int sub(int[] A, int[] B) {
        int flag = -1;
        for (int i = 0; i < A.length - B.length + 1; i++) {//7
            for (int j = 0; j < B.length; j++) {//1
                if (A[i + j] != B[j])//判断b中元素与a中的元素是否相等,不等就跳出循环
                    break;
                if (j == B.length - 1 && A[i + j] == B[j]) {//j == B.length - 1 判断是否是b中最后一个元素,用于确定全部比对完成
                    System.out.println("j=" + j + " i=" + i);
                    flag = i;//第二个数组在第一个数组中的下标
                }
            }
        }
        if (flag != -1)
            return flag;
        return -1;
    }

    public static void main(String[] args) {
        int[] A = new int[]{4, 5, 6, 7, 5, 6, 6, 8};
        int[] B = new int[]{6, 8};
        System.out.println(sub(A, B));//结果为6
    }

}

posted @ 2020-07-11 18:15  jason小蜗牛  阅读(392)  评论(0编辑  收藏  举报