aboutsummaryrefslogtreecommitdiff
path: root/other/num_bad_pairs.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'other/num_bad_pairs.cpp')
-rw-r--r--other/num_bad_pairs.cpp28
1 files changed, 28 insertions, 0 deletions
diff --git a/other/num_bad_pairs.cpp b/other/num_bad_pairs.cpp
new file mode 100644
index 0000000..144e6ef
--- /dev/null
+++ b/other/num_bad_pairs.cpp
@@ -0,0 +1,28 @@
+// 2364. Count Number of Bad Pairs
+#include "leetcode.h"
+
+/*
+ * you are given a 0-indexed integer array 'nums'. a pair of indices '(i, j)' is
+ * a bad pair if 'i < j' and 'j - i != nums[j] - nums[i]'. return the total
+ * number of bad pairs in 'nums'.
+ */
+
+class Solution {
+public:
+ long long countBadPairs(vector<int> &nums) {
+ long long ans = 0;
+ unordered_map<int, int> mp;
+ for (int i = 0; i < nums.size(); ++i) {
+ ans += i - mp[nums[i] - i];
+ mp[nums[i] - i]++;
+ }
+ return ans;
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<int> n1 = {4, 1, 3, 3}, n2 = {1, 2, 3, 4, 5};
+ printf("%lld\n", obj.countBadPairs(n1)); // expect: 5
+ printf("%lld\n", obj.countBadPairs(n2)); // expect: 0
+}