Google 面试题 #1:统计三元组数量(和小于等于 N)- 一亩三分地 – 谷歌面试真题

4次阅读
没有评论

You are given a list of integers A and an integer N. Implement a function
countTriplets(A, N) that returns the number of unique triplets that can be created from A whose elements sum to ≤ N.

Triplets are order-insensitive (so the order you choose the elements doesn’t matter) and elements may include duplicate values if A has elements with the same value, but they can only choose a given index once.

Note that countTriplets() returns a single integer. You should NOT return the entire list of triplets.

Example:

A = [-4, 2, 2, -7, 5, 3]  
N = 4  
 
countTriplets(A, N) == 16  
 
(-4, 3, 5) == (5, 3, -4)

Examples of valid triplets:

(-4, 2, 5)   // Sum = -4 + 2 + 5 = 3 <= N  
(-4, 2, 2)   // Sum = -4 + 2 + 2 = 0 <= N  

Examples of invalid triplets:

(2, 5, 3)    // Sum = 2 + 5 + 3 = 10 > N

总结

  • 给定数组 A 和整数 N,要统计 所有三元组数量 (选 3 个不同下标)使其 和 ≤ N
  • 三元组 不区分顺序,可以使用重复值(如果 A 中有重复元素),但不能重复下标。
  • 返回的是 数量,不是三元组本身。
  • 典型解法:排序 + 双指针 + 二分查找,时间复杂度 O(n² log n) 或 O(n²)。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 OpenAI、Google、Amazon、Citadel、SIG 等,提供实时语音助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Stripe 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0