【算法題】給定兩個數組a和b,判斷a中是否有全局順序出現的b序列

例如:java

int[] a = {3, 1, 2, 5, 4, 6, 8, 7, 3, 2, 5, 9, 4};
int[] b = {2, 3, 4};

由於a中的第三、九、13 個元素分別就是b中的元素順序,所以判斷結果爲Trueide

int[] a = {3, 1, 2, 5, 4, 6, 8, 7, 3, 2, 5, 9, 4};
int[] b = {1, 9, 3};

這種狀況就爲false,由於a中沒有全局順序出現的1, 9, 3序列。code

解題思路:

public boolean  test() {

        int n = 0;

        int[] a = {3, 1, 2, 5, 4, 6, 8, 7, 3, 2, 5, 9,4};

        int[] dest = {2, 3, 9};

        int[] index = new int[dest.length];

        for (int i = 0; i < dest.length; i++) {
            for (int i1 = n; i1 < a.length; i1++) {
                if (dest[i] == a[i1]) {
                    n = index[i] = i1;
                    break;
                }
            }
        }
      return  isIncrease(index,index.length);
}


private boolean isIncrease(int[] x, int n) {
    if (n == 1) {
        return true;
    }
    return (x[n - 1] >= x[n - 2]) && isIncrease(x, n - 1);
}
相關文章
相關標籤/搜索