718. 最长重复子数组

给两个整数数组 AB ,返回两个数组中公共的、长度最长的子数组的长度。

  1. class Solution {
  2. public int findLength(int[] A, int[] B) {
  3. int lenA = A.length, lenB = B.length;
  4. int res = 0;
  5. int[][] dp = new int[lenA+1][lenB+1];
  6. for (int i = 1; i <= lenA; i++) {
  7. for (int j = 1; j <= lenB; j++) {
  8. if (A[i - 1] == B[j - 1]) {
  9. dp[i][j] = dp[i - 1][j - 1] + 1;
  10. }
  11. res = Math.max(dp[i][j], res);
  12. }
  13. }
  14. return res;
  15. }
  16. }

560. 和为K的子数组

给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。

  1. package code
  2. # subarray.go
  3. // a,b都为有序数组, 判断a是否为b的子数组
  4. func IsSubArray(a []int, b []int) bool {
  5. m, n := len(a), len(b)
  6. if m == 0 || m > n {
  7. return false
  8. }
  9. for j := 0; j < n; j++ {
  10. i := 0
  11. s := j
  12. for i < m && s < n {
  13. if a[i] == b[s] {
  14. i++
  15. s++
  16. } else {
  17. break
  18. }
  19. }
  20. if i == m {
  21. return true
  22. }
  23. }
  24. return false
  25. }
package code
# subarray_test.go

import (
    "reflect"
    "testing"
)

func TestIsSubArray(t *testing.T) {
    type testCase struct {
        arrA []int
        arrB []int
        want bool //期望的结果
    }
    testGroup := map[string]testCase{
        "case1": testCase{[]int{3, 4}, []int{1, 2, 3, 3, 4, 5}, true},
        "case2": testCase{[]int{3, 5}, []int{1, 2, 3, 3, 4, 5}, false},
        "case3": testCase{[]int{3, 3}, []int{1, 2, 3, 3, 3, 3}, true},
        "case4": testCase{[]int{1, 3, 4}, []int{1, 3, 5}, false},
    }

    for key, v := range testGroup { //遍历
        t.Run(key, func(t *testing.T) {
            got := IsSubArray(v.arrA, v.arrB)
            want := v.want
            if !reflect.DeepEqual(want, got) { //比较
                t.Errorf("excepted:%v, got:%v", want, got)
            }
        })
    }
}