当前位置:   article > 正文

【Daily Pratice】【数组】之子数组问题--题解(7)

【Daily Pratice】【数组】之子数组问题--题解(7)
  • Question

Check whether an Array is Subarray of another Array(Visa)

  • Description

Given two arrays A[] and B[] consisting of n and m integers. The task is to check whether the array B[] is a subarray of the array A[] or not.

  • Examples:
Input : A[] = {2, 3, 0, 5, 1, 1, 2}, B[] = {3, 0, 5, 1} 
Output : Yes

Input : A[] = {1, 2, 3, 4, 5}, B[] = {2, 5, 6} 
Output : No 
  • 1
  • 2
  • 3
  • 4
  • 5
  • Solution(BruteForce/TwoPointers)
let solution = (a, b)=>{
    // 当a[i] = b[j] 时 i++ j++,如果j=b.length 返回true
    // 当a[i] != b[j] 时 i=j-j+1  j=0
    let [i,j] = [0,0]
    let [n,m] = [a.length,b.length]
    while(i < n && j < m){

        if(a[i] == b[j]){
            i++
            j++
            if(j == m){
                return true
            }
        }else{
            i = i - j + 1
            j = 0
        }
    }
    return false
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/658159
推荐阅读
相关标签
  

闽ICP备14008679号