算法leetcode|6136. 算术三元组的数目(rust和go全部双百)

Posted 二当家的白帽子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法leetcode|6136. 算术三元组的数目(rust和go全部双百)相关的知识,希望对你有一定的参考价值。


文章目录


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://leetcode.cn/problems/number-of-arithmetic-triplets/


非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


以上是关于算法leetcode|6136. 算术三元组的数目(rust和go全部双百)的主要内容,如果未能解决你的问题,请参考以下文章

算法leetcode|6136. 算术三元组的数目(rust和go全部双百)

LeetCode Algorithm 1925. 统计平方和三元组的数目

leetcode算法题 pro1442 形成两个异或相等数组的三元组数目

算法leetcode1442. 形成两个异或相等数组的三元组数目(rust真是好用)

算法leetcode1442. 形成两个异或相等数组的三元组数目(rust真是好用)

LeetCode 1442. 形成两个异或相等数组的三元组数目