如何高效提取嵌套列表中的不同元素(满足O(UCK)复杂度)
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
- Iterate over each entry in your main list
x(each entry has an ID and a sublist of animals). - Ignore the ID value—we only care about the animal strings in the sublist.
- Add each animal to a set: sets inherently store only unique values, so we don’t need manual duplicate checks.
- 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

