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

如何高效提取嵌套列表中的不同元素(满足O(UCK)复杂度)

Efficiently Extract Unique Elements with O(UCK) Time Complexity

The most straightforward and efficient way to solve this problem aligns perfectly with your required time complexity, leveraging a hash set to automatically handle duplicates while keeping operations lean. Here's how to implement it:

Step-by-Step Approach

  1. Iterate over each entry in your main list x (each entry has an ID and a sublist of animals).
  2. Ignore the ID value—we only care about the animal strings in the sublist.
  3. Add each animal to a set: sets inherently store only unique values, so we don’t need manual duplicate checks.
  4. Convert the set to a list if you need the final result in list format.

Code Implementation

x = [ [1, ["cat","dog"]], [2, ["dog", "mouse", "elephant"]], [3, ["mouse", "giraffe"]] ]

unique_animals = set()
for entry in x:
    # Skip the ID (entry[0]) and process the animal sublist
    for animal in entry[1]:
        unique_animals.add(animal)

# Convert set to list if required
unique_animals_list = list(unique_animals)
print(unique_animals_list)  # Output: ['cat', 'dog', 'mouse', 'elephant', 'giraffe'] (order may vary)

Time Complexity Verification

Let’s confirm this meets your O(UCK) requirement:

  • U: Number of entries in the main list (3 in the example). We loop through every entry once.
  • K: Maximum number of animals in any sublist (3 in the example, from the second entry). For each entry, we process up to K animals.
  • C: Maximum character count of any animal name (e.g., "elephant" has 8 characters). Hashing a string to insert into a set takes O(C) time per string.

Multiplying these factors gives us O(UKC)—exactly the O(UCK) complexity you specified. Set insertions have average O(1) time once the hash is computed, so the dominant cost is the string hashing step.

Bonus: Preserving Insertion Order

If you need the unique list to maintain the order of first occurrence of each animal, use a Python 3.7+ dictionary (which preserves insertion order) instead of a set:

unique_animals_ordered = {}
for entry in x:
    for animal in entry[1]:
        unique_animals_ordered[animal] = None  # Value is irrelevant, we only care about keys
unique_animals_list_ordered = list(unique_animals_ordered.keys())
print(unique_animals_list_ordered)  # Output: ['cat', 'dog', 'mouse', 'elephant', 'giraffe']

This still maintains O(UCK) time complexity, as dictionary insertions behave the same as set operations under the hood.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:30:12