You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
From the problem description, we know that for any $i < j$, if $j - i \neq nums[j] - nums[i]$, then $(i, j)$ is a bad pair.
66
+
According to the problem description, for any $i \lt j$, if $j - i \neq \textit{nums}[j] - \textit{nums}[i]$, then $(i, j)$ is a bad pair.
67
67
68
-
We can transform the equation to $i - nums[i] \neq j - nums[j]$. This inspires us to use a hash table $cnt$ to count the occurrences of $i - nums[i]$.
68
+
We can transform the equation into $i - \textit{nums}[i] \neq j - \textit{nums}[j]$. This suggests using a hash table $cnt$ to count the occurrences of $i - \textit{nums}[i]$.
69
69
70
-
We iterate through the array. For the current element $nums[i]$, we add $i - cnt[i - nums[i]]$ to the answer, then increment the count of $i - nums[i]$ by $1$.
70
+
While iterating through the array, for the current element $\textit{nums}[i]$, we add $i - cnt[i - \textit{nums}[i]]$ to the answer, and then increment the count of $i - \textit{nums}[i]$ by $1$.
71
71
72
72
Finally, we return the answer.
73
73
74
-
The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array.
74
+
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$.
75
75
76
76
<!-- tabs:start -->
77
77
@@ -97,8 +97,7 @@ class Solution {
97
97
long ans =0;
98
98
for (int i =0; i < nums.length; ++i) {
99
99
int x = i - nums[i];
100
-
ans += i - cnt.getOrDefault(x, 0);
101
-
cnt.merge(x, 1, Integer::sum);
100
+
ans += i - cnt.merge(x, 1, Integer::sum) +1;
102
101
}
103
102
return ans;
104
103
}
@@ -115,8 +114,7 @@ public:
115
114
long long ans = 0;
116
115
for (int i = 0; i < nums.size(); ++i) {
117
116
int x = i - nums[i];
118
-
ans += i - cnt[x];
119
-
++cnt[x];
117
+
ans += i - cnt[x]++;
120
118
}
121
119
return ans;
122
120
}
@@ -152,6 +150,26 @@ function countBadPairs(nums: number[]): number {
0 commit comments