You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否使用Binary Search解决「寻找和为定值的三元组」并统计输出?

Using Binary Search to Count Triplets with a Given Sum

Absolutely you can use binary search to solve this triplet sum count problem! Here's how it works, along with key details to watch out for:

Core Idea

  1. Sort the array first: Binary search relies on a sorted dataset, so this step is non-negotiable. Sorting takes O(n log n) time upfront.
  2. Fix one element, reduce to a two-sum problem: For each element nums[i] in the array, we need to find pairs (nums[j], nums[k]) where j > i, k > j, and nums[j] + nums[k] = target - nums[i]. For each j, we use binary search to check (and count) how many times the required complement exists in the subarray from j+1 to the end.
  3. Count valid complements: Binary search helps us find the range of elements matching the complement, so we can add the total number of matches to our count instead of just checking existence.

Step-by-Step Implementation

Here’s a Python example using the built-in bisect module for clean binary search logic:

import bisect

def count_triplets(nums, target):
    nums.sort()
    count = 0
    n = len(nums)
    
    for i in range(n - 2):
        # Skip duplicate i values to avoid counting identical triplets repeatedly
        if i > 0 and nums[i] == nums[i-1]:
            continue
        remaining_sum = target - nums[i]
        for j in range(i + 1, n - 1):
            # Skip duplicate j values for the same i
            if j > i + 1 and nums[j] == nums[j-1]:
                continue
            complement = remaining_sum - nums[j]
            # Find the first index where element >= complement
            left_bound = bisect.bisect_left(nums, complement, j + 1, n)
            # Find the first index where element > complement
            right_bound = bisect.bisect_right(nums, complement, j + 1, n)
            # Add the number of elements equal to the complement
            count += right_bound - left_bound
    return count

Key Notes

  • Time Complexity: Sorting takes O(n log n), and the nested loops plus binary search result in O(n² log n) time overall. This is better than the brute-force triple loop’s O(n³) but slower than the hash map approach’s O(n²).
  • Duplicate Handling: Skipping duplicate i and j values ensures we don’t count identical triplets multiple times (e.g., an array like [2,2,2] with target 6 should count as 1 triplet, not 3).
  • Edge Cases: The code automatically handles empty arrays, arrays with fewer than 3 elements, and cases where no valid triplets exist (returning 0 in those scenarios).

Comparison to Other Methods

  • Brute Force (Triple Loop): Simple to write but horribly inefficient for large datasets.
  • Hash Map: Faster at O(n²) time, but requires O(n) extra space for the hash table.
  • Binary Search: Uses O(1) extra space (if sorting in-place) and is intuitive if you’re already familiar with binary search mechanics.

内容的提问来源于stack exchange,提问作者user9306160

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:31:12