Leetcode18-算术三元组的数目(2367)

1、题目

给你一个下标从 0 开始、严格递增 的整数数组 nums 和一个正整数 diff 。如果满足下述全部条件,则三元组 (i, j, k) 就是一个 算术三元组 :

i < j < k ,

numsj - numsi == diff 且

numsk - numsj == 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 <= numsi <= 200

1 <= diff <= 50

nums 严格 递增。

2、解

对nums进行遍历,每个三元组即为{numi. numsi + diff, numsi + 2*diff}

寻找其是否存在每个元素对应的三元组中的后两个元素, 如果存在结果+1。

cpp 复制代码
    int arithmeticTriplets(vector<int> &nums, int diff)
    {
        int result = 0;
        for(int i = 0; i < nums.size(); i++){
            vector<int>::iterator mid = find((nums.begin() + i), nums.end(), nums[i] + diff);
            vector<int>::iterator last = find((nums.begin() + i + 1), nums.end(), nums[i] + 2*diff);
            if(mid != nums.end() && last != nums.end()){
                result++;
            }
        }
        return result;
    }

也可以先将nums通过哈希集合存储后进行查找

cpp 复制代码
    int arithmeticTriplets(vector<int>& nums, int diff) {
        unordered_set<int> hashSet;
        for (int x : nums) {
            hashSet.emplace(x);
        }
        int ans = 0;
        for (int x : nums) {
            if (hashSet.count(x + diff) && hashSet.count(x + 2 * diff)) {
                ans++;
            }
        }
        return ans;
    }
相关推荐
San813_LDD14 分钟前
[数据结构]LeetCode学习
数据结构·算法·图论
x1387028595719 分钟前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油1 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
.千余2 小时前
【C++】手写双向链表:list容器模拟实现
开发语言·c++·笔记·学习·其他
QuZero2 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称2 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划
liulilittle3 小时前
过冲:拥塞控制的呼吸与盲行
linux·网络·c++·tcp/ip·计算机网络·tcp·通信
Felven3 小时前
B. Fair Numbers
数据结构·算法