718. 最長重複子數組:滑動視窗解法注釋 優秀解法:滑動視窗
718. 最長重複子數組:滑動視窗解法注釋 class Solution {
public int findLength(int[] nums1, int[] nums2) {
return nums1.length < nums2.length ? changeList(nums1,nums2) : changeList(nums2,nums1);
}
public int changeList(int[] nums1,int[] nums2){
int res = 0;
int an = nums1.length,bn = nums2.length;
//長的數組的右端從未進入到到達短數組右端
for(int i = an; i > 0; i--)
res = Math.max(res,getMaxLength(nums1,0,nums2,bn - i,i));
//在上面的情況下開始 讓長的數組左端和短數組左端對齊
for(int j = 0; j <= bn - an; j++)
res = Math.max(res,getMaxLength(nums1,0,nums2,j,an));
//在上面的情況下開始 讓長的數組左端脫離短的數組
for(int k = 0; k < an; k++)
res = Math.max(res,getMaxLength(nums1,k,nums2,0,an - k));
return res;
}
//給兩個數組的子序列 對比它們的按位置是否相同
public int getMaxLength(int[] nums1,int one,int[] nums2,int two,int len){
int count = 0,max = 0;
for(int i = 0; i < len; i++){
if(nums1[one + i] == nums2[two + i]){
count++;
}else if(count > 0){
max = Math.max(max,count);
count = 0;
}
}
return Math.max(max,count);
}
}