6136. 算术三元组的数目:
给你一个下标从 0 开始、严格递增 的整数数组 nums 和一个正整数 diff 。如果满足下述全部条件,则三元组 (i, j, k) 就是一个 算术三元组 :
- i < j < k ,
- nums[j] - nums[i] == diff 且
- nums[k] - nums[j] == diff
返回不同 算术三元组 的数目。
样例 1:
输入:
nums = [0,1,4,6,7,10], diff = 3
输出:
2
解释:
(1, 2, 4) 是算术三元组:7 - 4 == 3 且 4 - 1 == 3 。
(2, 4, 5) 是算术三元组:10 - 7 == 3 且 7 - 4 == 3 。
样例 2:
输入:
nums = [4,5,6,7,8,9], diff = 2
输出:
2
解释:
(0, 2, 4) 是算术三元组:8 - 6 == 2 且 6 - 4 == 2 。
(1, 3, 5) 是算术三元组:9 - 7 == 2 且 7 - 5 == 2 。
提示:
- 3 <= nums.length <= 200
- 0 <= nums[i] <= 200
- 1 <= diff <= 50
- nums 严格 递增
分析
- 面对这道算法题目,二当家的陷入了沉思。
- 根据题意可以知道,当遍历到nums[k] 时,满足条件的三元组nums[j] = nums[k] - diff,nums[i] = nums[k] - diff - diff,只需要判断数字是否存在即可。
题解
rust
impl Solution {
pub fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32 {
let mut flag = vec![false; 201];
nums.iter().filter(|&&n| {
flag[n as usize] = true;
n >= diff + diff && flag[(n - diff) as usize] && flag[(n - diff - diff) as usize]
}).count() as i32
}
}
go
func arithmeticTriplets(nums []int, diff int) int {
ans := 0
flag := make([]bool, 201)
for _, n := range nums {
flag[n] = true
if n >= diff+diff && flag[n-diff] && flag[n-diff-diff] {
ans++
}
}
return ans
}
c++
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int ans = 0;
bool flag[201] = {};
for (int n: nums) {
flag[n] = true;
if (n >= diff + diff && flag[n - diff] && flag[n - diff - diff]) {
++ans;
}
}
return ans;
}
};
java
class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
int ans = 0;
boolean[] flag = new boolean[201];
for (int n : nums) {
flag[n] = true;
if (n >= diff + diff && flag[n - diff] && flag[n - diff - diff]) {
++ans;
}
}
return ans;
}
}
python
class Solution:
def arithmeticTriplets(self, nums: List[int], diff: int) -> int:
ans = 0
flag = [False] * 201
for n in nums:
flag[n] = True
if n >= diff + diff and flag[n - diff] and flag[n - diff - diff]:
ans += 1
return ans
非常感谢你阅读本文~ 欢迎【点赞】【收藏】【评论】~ 放弃不难,但坚持一定很酷~ 希望我们大家都能每天进步一点点~ 本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~
|