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

如何将数组唯一元素检查的时间复杂度从O(n²)优化至O(nlogn)及以下?

Hey there! Let's break down how to optimize your duplicate check from O(n²) to something way more efficient. I'll walk you through both the O(nlogn) approach and an even faster O(n) method, with code examples to make it concrete.

O(nlogn) Approach: Sort First, Then Check Adjacent Elements

The core idea here is that sorting groups duplicate elements next to each other, so we only need a single pass to spot duplicates. Sorting typically takes O(nlogn) time, and the subsequent linear scan is O(n)—so the overall time complexity is dominated by the sort, landing us at O(nlogn).

Here's a Python example:

def has_duplicates(arr):
    if len(arr) <= 1:
        return False
    # Perform in-place sort to save space (O(logn) auxiliary space for most built-in sorts)
    arr.sort()
    # Check each pair of adjacent elements
    for i in range(len(arr) - 1):
        if arr[i] == arr[i + 1]:
            return True
    return False

If you can't modify the original array, use sorted(arr) instead (this creates a copy, adding O(n) space overhead, but time complexity stays O(nlogn)).

Even Faster: O(n) Time with a Hash Set

If you're okay with trading a bit of space for speed, a hash set lets us check for duplicates in linear time. Hash set lookups and insertions are average O(1), so we can traverse the array once, tracking elements we've already seen.

Python example:

def has_duplicates(arr):
    seen = set()
    for element in arr:
        if element in seen:
            # Found a duplicate
            return True
        seen.add(element)
    # No duplicates found
    return False

This runs in O(n) average time, with O(n) space to store the set. It's the fastest approach for most cases, unless memory is extremely constrained (then the O(nlogn) sort-based method is better, as it uses minimal extra space).

Why Your Original O(n²) Approach Is Slow

Just to recap: the typical O(n²) method uses nested loops, where each element is compared to every other element. That's n*(n-1)/2 comparisons total—great for small arrays, but it gets exponentially slower as the array grows (e.g., an array of 10,000 elements would require ~50 million comparisons!).

内容的提问来源于stack exchange,提问作者b.x

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:08:35