Maximum Length of Repeated Subarray LeetCode solution in C++

1
class Solution {
2
public:
3
int findLength(vector<int> &nums1, vector<int> &nums2) {
4
int n1 = nums1.size();
5
int n2 = nums2.size();
6

7
// moving num2 on num1
8

9
int ptr2 = 0;
10

11
int cnt = 0;
12

13
int largest = INT_MIN;
14

15
for (int i = 0; i < n1; i++) {
16
cnt = 0;
17
for (int j = i, ptr2 = 0; j < n1 && ptr2 < n2; j++, ptr2++) {
18
if (nums1[j] == nums2[ptr2]) {
19
cnt++;
20

21
} else {
22
cnt = 0;
23
}
24
largest = max(largest, cnt);
25
}
26
}
27

28
// moving num1 on num2
29
ptr2 = 0;
30
cnt = 0;
31
for (int i = 0; i < n2; i++) {
32
cnt = 0;
33
for (int j = i, ptr2 = 0; j < n2 && ptr2 < n1; j++, ptr2++) {
34
if (nums2[j] == nums1[ptr2]) {
35
cnt++;
36
} else {
37
cnt = 0;
38
}
39
largest = max(largest, cnt);
40
}
41
}
42

43
return largest;
44
}
45
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0