鱼C论坛

 找回密码
 立即注册
查看: 3151|回复: 0

[学习笔记] Leetcode 1534. Count Good Triplets

[复制链接]
发表于 2020-8-2 12:33:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.

  2. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

  3. 0 <= i < j < k < arr.length
  4. |arr[i] - arr[j]| <= a
  5. |arr[j] - arr[k]| <= b
  6. |arr[i] - arr[k]| <= c
  7. Where |x| denotes the absolute value of x.

  8. Return the number of good triplets.



  9. Example 1:

  10. Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
  11. Output: 4
  12. Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
  13. Example 2:

  14. Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
  15. Output: 0
  16. Explanation: No triplet satisfies all conditions.


  17. Constraints:

  18. 3 <= arr.length <= 100
  19. 0 <= arr[i] <= 1000
  20. 0 <= a, b, c <= 1000
复制代码

  1. class Solution:
  2.     def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
  3.         result = []
  4.         for i in range(len(arr)):
  5.             for j in range(i + 1, len(arr)):
  6.                 for k in range(j + 1, len(arr)):
  7.                     f = arr[i]
  8.                     s = arr[j]
  9.                     t = arr[k]
  10.                     if abs(f - s) <= a and abs(s - t) <= b and abs(f - t) <= c:
  11.                         result.append((f, s, t))
  12.         return len(result)
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-26 12:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表