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;
    }
相关推荐
程序员yu8 小时前
会编网络:别被入门教程骗了,Python实用能力不在语法本身
开发语言·python·学习·算法
LuminousCPP8 小时前
从零开始学 C++(三):类和对象入门|从 struct 到 class,理解封装、对象与 this 指针
c++·笔记·学习·类和对象
郝学胜-神的一滴8 小时前
游戏引擎原理与实践 01:聊聊游戏引擎的前世今生
开发语言·c++·游戏引擎·产品运营·软件工程·产品经理·untiy
Allen_LVyingbo8 小时前
信息化部门在AI时代的编程转移路径分析(上)
人工智能·python·算法·健康医疗·数据库开发·时序数据库·数据库架构
七牛云行业应用8 小时前
Jev 报 401 / api_key_required 怎么解决:TypeSafe AI 官方错误码表与排查步骤
算法·github
晴天的雨.9929 小时前
【C++算法】三数之和
开发语言·c++·算法
pippocao9 小时前
王者荣耀日志组件BqLog 为何如此快之3——压缩日志执行路径优化
c++
AC赳赳老秦9 小时前
公开 CSV 数据集批量处理实战:用 OpenClaw 高效完成下载、清洗与标准化分析样本生成
java·开发语言·汇编·c++·python·deepseek·openclaw
凉茶钱9 小时前
【吃透C++】static、友元、内部类、匿名对象与拷贝编译器优化全解析
c++·青少年编程·visual studio
无名猿10 小时前
左值引用、右值引用与万能引用:引用折叠全解
c++·现代c++·模板元编程·语法基础