侧边栏壁纸
博主头像
GabrielxD

列車は必ず次の駅へ。では舞台は?私たちは?

  • 累计撰写 675 篇文章
  • 累计创建 128 个标签
  • 累计收到 26 条评论

目 录CONTENT

文章目录

【哈希表, 二分查找】算术三元组的数目

GabrielxD
2022-08-08 / 0 评论 / 0 点赞 / 366 阅读 / 517 字
温馨提示:
本文最后更新于 2022-09-02,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

题目

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 严格 递增

解题

方法一:哈希表

思路

把所有数存入哈希集合中,枚举所有数,如果集合中同时存在 num - diffnum + diff 就把计数器自增。

代码

class Solution {
    public int arithmeticTriplets(int[] nums, int diff) {
        Set<Integer> set = new HashSet<>(){{
            for (int num : nums) this.add(num);
        }};
        int count = 0;
        for (int num : nums) {
            if (set.contains(num - diff) && set.contains(num + diff)) count++;
        }
        return count;
    }
}
class Solution {
public:
    int arithmeticTriplets(vector<int>& nums, int diff) {
        unordered_set<int> st(nums.begin(), nums.end());
        int count = 0;
        for (int& num : nums) {
            if (st.count(num - diff) && st.count(num + diff)) ++count;
        }
        return count;
    }
};

方法二:二分查找

思路

数组是严格递增的,所以可以直接用二分查找 num - diffnum + diff ,如果同时存在直接把计数器自增。

代码

class Solution {
    public int arithmeticTriplets(int[] nums, int diff) {
        int count = 0;
        for (int num : nums) {
            if (Arrays.binarySearch(nums, num - diff) >= 0 &&
                Arrays.binarySearch(nums, num + diff) >= 0) count++;
        }
        return count;
    }
}
class Solution {
public:
    int arithmeticTriplets(vector<int>& nums, int diff) {
        int count = 0;
        for (int& num : nums) {
            if (binary_search(nums.begin(), nums.end(), num - diff) &&
                binary_search(nums.begin(), nums.end(), num + diff)) count++;
        }
        return count;
    }
};
0

评论区