@@ -62,22 +62,109 @@ i和j之间的距离是j - i + 1 = 1 - 1 + 1 = 1。
62
62
63
63
<!-- 这里可写通用的实现逻辑 -->
64
64
65
+ ** 方法一:前缀和 + 哈希表**
66
+
67
+ 我们观察到,对于任意的索引对 $(i, j)$,如果 $nums1[ i] + nums1[ i+1] + ... + nums1[ j] = nums2[ i] + nums2[ i+1] + ... + nums2[ j] $,那么 $nums1[ i] - nums2[ i] + nums1[ i+1] - nums2[ i+1] + ... + nums1[ j] - nums2[ j] = 0$。如果我们将数组 $nums1$ 与数组 $nums2$ 对应位置的元素相减,得到一个新的数组 $nums$,那么问题转换为在数组 $nums$ 中找到一个最长的子数组,使得子数组的和为 $0$。这可以通过前缀和 + 哈希表的方法求解。
68
+
69
+ 我们定义一个变量 $s$ 表示当前 $nums$ 的前缀和,用一个哈希表 $d$ 保存每个前缀和第一次出现的位置。初始时 $s = 0$, $d[ 0] = -1$。
70
+
71
+ 接下来,我们遍历数组 $nums$ 中的每个元素 $x$,计算 $s$ 的值,然后检查哈希表中是否存在 $s$,如果哈希表存在 $s$,那么说明存在一个子数组 $nums[ d[ s] +1,..i] $,使得子数组的和为 $0$,我们更新答案为 $max(ans, i - d[ s] )$。否则,我们将 $s$ 的值加入哈希表中,表示 $s$ 第一次出现的位置为 $i$。
72
+
73
+ 遍历结束,即可得到最终的答案。
74
+
75
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。
76
+
65
77
<!-- tabs:start -->
66
78
67
79
### ** Python3**
68
80
69
81
<!-- 这里可写当前语言的特殊实现逻辑 -->
70
82
71
83
``` python
72
-
84
+ class Solution :
85
+ def widestPairOfIndices (self , nums1 : List[int ], nums2 : List[int ]) -> int :
86
+ d = {0 : - 1 }
87
+ ans = s = 0
88
+ for i, (a, b) in enumerate (zip (nums1, nums2)):
89
+ s += a - b
90
+ if s in d:
91
+ ans = max (ans, i - d[s])
92
+ else :
93
+ d[s] = i
94
+ return ans
73
95
```
74
96
75
97
### ** Java**
76
98
77
99
<!-- 这里可写当前语言的特殊实现逻辑 -->
78
100
79
101
``` java
102
+ class Solution {
103
+ public int widestPairOfIndices (int [] nums1 , int [] nums2 ) {
104
+ Map<Integer , Integer > d = new HashMap<> ();
105
+ d. put(0 , - 1 );
106
+ int n = nums1. length;
107
+ int s = 0 ;
108
+ int ans = 0 ;
109
+ for (int i = 0 ; i < n; ++ i) {
110
+ s += nums1[i] - nums2[i];
111
+ if (d. containsKey(s)) {
112
+ ans = Math . max(ans, i - d. get(s));
113
+ } else {
114
+ d. put(s, i);
115
+ }
116
+ }
117
+ return ans;
118
+ }
119
+ }
120
+ ```
121
+
122
+ ### ** C++**
123
+
124
+ ``` cpp
125
+ class Solution {
126
+ public:
127
+ int widestPairOfIndices(vector<int >& nums1, vector<int >& nums2) {
128
+ unordered_map<int, int> d;
129
+ d[ 0] = -1;
130
+ int ans = 0, s = 0;
131
+ int n = nums1.size();
132
+ for (int i = 0; i < n; ++i) {
133
+ s += nums1[ i] - nums2[ i] ;
134
+ if (d.count(s)) {
135
+ ans = max(ans, i - d[ s] );
136
+ } else {
137
+ d[ s] = i;
138
+ }
139
+ }
140
+ return ans;
141
+ }
142
+ };
143
+ ```
80
144
145
+ ### **Go**
146
+
147
+ ```go
148
+ func widestPairOfIndices(nums1 []int, nums2 []int) (ans int) {
149
+ d := map[int]int{0: -1}
150
+ s := 0
151
+ for i := range nums1 {
152
+ s += nums1[i] - nums2[i]
153
+ if j, ok := d[s]; ok {
154
+ ans = max(ans, i-j)
155
+ } else {
156
+ d[s] = i
157
+ }
158
+ }
159
+ return
160
+ }
161
+
162
+ func max(a, b int) int {
163
+ if a > b {
164
+ return a
165
+ }
166
+ return b
167
+ }
81
168
```
82
169
83
170
### ** ...**
0 commit comments