Algorithm to determine indices i..j of array A containing all the elements of another array B

前端 未结 4 1279
野性不改
野性不改 2021-02-04 14:15

I came across this question on an interview questions thread. Here is the question:

Given two integer arrays A [1..n] and B[1..m], find the smallest<

4条回答
  •  别跟我提以往
    2021-02-04 14:49

    struct Pair {
        int i;
        int j;
    };
    
    Pair
    find_smallest_subarray_window(int *A, size_t n, int *B, size_t m)
    {
        Pair p;
    
        p.i = -1;
        p.j = -1;
    
        // key is array value, value is array index
        std::map map;
        size_t count = 0;
    
        int i;
        int j;
        for(i = 0; i < n, ++i) {
            for(j = 0; j < m; ++j) {
                if(A[i] == B[j]) {
                    if(map.find(A[i]) == map.end()) {
                        map.insert(std::pair(A[i], i));
                    } else {
                        int start = findSmallestVal(map);
                        int end = findLargestVal(map);
                        int oldLength = end-start;
                        int oldIndex = map[A[i]];
    
                        map[A[i]] = i;
                        int _start = findSmallestVal(map);
                        int _end = findLargestVal(map);
                        int newLength = _end - _start;
                        if(newLength > oldLength) {
                            // revert back
                            map[A[i]] = oldIndex;
                        }
                    }
                }
            }
    
            if(count == m) {
                break;
            }
        }
    
        p.i = findSmallestVal(map);
        p.j = findLargestVal(map);
    
        return p;
    }
    

提交回复
热议问题