go陣列去除重複_leetcode718_go_最長重複子陣列
阿新 • • 發佈:2021-01-30
技術標籤:go陣列去除重複
題目
給兩個整數陣列 A 和 B ,返回兩個陣列中公共的、長度最長的子陣列的長度。
示例:輸入:A: [1,2,3,2,1] B: [3,2,1,4,7]
輸出:3
解釋:長度最長的公共子陣列是 [3, 2, 1] 。
提示:1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100
解題思路分析
1、動態規劃;時間複雜度O(n^2),空間複雜度O(n^2)
func findLength(A []int, B []int) int {n, m := len(A), len(B)dp := make([][]int, n+1)for i := 0; i <= n; i++ {dp[i] = make([]int, m+1)}res := math.MinInt32for i := 1; i <= n; i++ {for j := 1; j <= m; j++ {if A[i-1] == B[j-1] {dp[i][j] = dp[i-1][j-1] + 1}if dp[i][j] > res {res = dp[i][j]}}}return res}
2、動態規劃;時間複雜度O(n^2),空間複雜度O(n)
func findLength(A []int, B []int) int {n, m := len(A), len(B)dp := make([]int, m+1)res := math.MinInt32for i := 1; i <= n; i++ {for j := m; j >= 1; j-- {if A[i-1] == B[j-1] {dp[j] = dp[j-1] + 1} else {dp[j] = 0 // 需要清0}if dp[j] > res {res = dp[j]}}}return res}
3、滑動視窗;時間複雜度O(n^2),空間複雜度O(1)
func findLength(A []int, B []int) int {n, m := len(A), len(B)res := math.MinInt32for i := 0; i < n; i++ {length := min(n-i, m)maxLength := getMaxLength(A, B, i, 0, length)res = max(res, maxLength)}for i := 0; i < m; i++ {length := min(n, m-i)maxLength := getMaxLength(A, B, 0, i, length)res = max(res, maxLength)}return res}func getMaxLength(A, B []int, a, b int, length int) int {res := 0count := 0for i := 0; i < length; i++ {if A[a+i] == B[b+i] {count++} else {count = 0}res = max(res, count)}return res}func max(a, b int) int {if a > b {return a}return b}func min(a, b int) int {if a > b {return b}return a}
總結
Medium題目,子陣列系列題目,滑動視窗和動態規劃方法需要掌握