跳到主要内容

2367.算术三元组的数目

链接:2367.算术三元组的数目
难度:Easy
标签:数组、哈希表、双指针、枚举
简介:给你一个下标从 0 开始、严格递增 的整数数组 nums 和一个正整数 diff 。返回不同 算术三元组 的数目。

题解 1 - cpp

  • 编辑时间:2023-03-31
  • 执行用时:4ms
  • 内存消耗:9.3MB
  • 编程语言:cpp
  • 解法介绍:哈希表+遍历。
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
unordered_map<int, int> m1, m2;
int res = 0;
for (auto &num : nums) {
res += m2[num - diff];
m2[num] += m1[num - diff];
m1[num] += 1;
}
return res;
}
};

题解 2 - python

  • 编辑时间:2023-03-31
  • 执行用时:44ms
  • 内存消耗:14.9MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
m1, m2 = Counter(), Counter()
res = 0
for num in nums:
res += m2[num-diff]
m2[num] += m1[num-diff]
m1[num] += 1
return res

题解 3 - rust

  • 编辑时间:2023-03-31
  • 内存消耗:2.1MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32 {
use std::collections::HashMap;
let (mut m1, mut m2) = (HashMap::<i32, i32>::new(), HashMap::<i32, i32>::new());
let mut res = 0;
for num in nums {
res += *m2.entry(num - diff).or_insert(0);
*m2.entry(num).or_insert(0) += *m1.entry(num - diff).or_insert(0);
*m1.entry(num).or_insert(0) += 1;
}
res
}
}