aboutsummaryrefslogtreecommitdiff
path: root/other/num_bad_pairs.rs
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/num_bad_pairs.rs
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/num_bad_pairs.rs')
-rw-r--r--other/num_bad_pairs.rs30
1 files changed, 30 insertions, 0 deletions
diff --git a/other/num_bad_pairs.rs b/other/num_bad_pairs.rs
new file mode 100644
index 0000000..88119d8
--- /dev/null
+++ b/other/num_bad_pairs.rs
@@ -0,0 +1,30 @@
+// 2364. Count Number of Bad Pairs
+use std::collections::HashMap;
+struct Solution;
+
+/*
+ * 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'.
+ */
+
+impl Solution {
+ pub fn count_bad_pairs(nums: Vec<i32>) -> i64 {
+ let mut hm: HashMap<i32, i32> = HashMap::with_capacity(nums.len());
+ let mut ans = 0;
+ nums.iter().zip(0..).for_each(|(&x, i)| {
+ let delta = x - i;
+ let e = hm.entry(delta).or_default();
+ ans += (i - *e) as i64;
+ *e += 1;
+ });
+ ans
+ }
+}
+
+fn main() {
+ let n1 = vec![4, 1, 3, 3];
+ let n2 = vec![1, 2, 3, 4, 5];
+ println!("{}", Solution::count_bad_pairs(n1)); //expect: 5
+ println!("{}", Solution::count_bad_pairs(n2)); //expect: 0
+}