菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
302
0

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

原创
05/13 14:22
阅读数 19892

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
    }

}

发表评论

0/200
302 点赞
0 评论
收藏