Rust中获取多组Vector交集时类型不匹配问题求助
Fixing Vec vs Vec<&i32> Mismatch in Multi-Vector Intersection in Rust
Let's break down the issue and fix your code step by step. The error you're seeing happens because HashSet::intersection() returns an iterator over references to the shared elements (&i32), but your intersect_result is declared as a Vec<i32>—the types don't line up. Here's how to fix this, plus some other improvements to make your code more idiomatic Rust:
Key Issues in Your Original Code
intersect_resultis immutable: You need to update it in each iteration, so it should be declared withmut.- Type mismatch from
intersection(): The method returns references, not owned values. Sincei32implements theCopytrait, we can easily convert these references to owned values. - Unnecessary type conversions: Converting
nums.len()toi32is unnecessary—Rust prefers usingusizefor collection lengths and indices. - Empty return at the end: Your code returns an empty vector instead of the computed intersection.
Fixed Code (Idiomatic Version)
use std::collections::HashSet; impl Solution { pub fn intersection(nums: Vec<Vec<i32>>) -> Vec<i32> { // Handle edge case: empty input if nums.is_empty() { return vec![]; } // Start with the first vector's elements as our initial intersection let mut intersect_result: Vec<i32> = nums[0].clone(); // Iterate over all remaining vectors in the input for current_vec in &nums[1..] { // Convert both the current vector and our current intersection to HashSets let current_set: HashSet<i32> = current_vec.iter().cloned().collect(); let result_set: HashSet<i32> = intersect_result.iter().cloned().collect(); // Compute the intersection, converting &i32 references to owned i32 values intersect_result = current_set.intersection(&result_set) .copied() // Uses Copy trait to convert &i32 to i32 (more efficient than clone()) .collect(); // Early exit if intersection becomes empty (no need to check further) if intersect_result.is_empty() { break; } } // Sort the final result as required intersect_result.sort(); intersect_result } }
Even More Efficient Version (HashSet-First Approach)
Instead of switching between Vec and HashSet each iteration, we can work with HashSet throughout to avoid redundant conversions:
use std::collections::HashSet; impl Solution { pub fn intersection(nums: Vec<Vec<i32>>) -> Vec<i32> { if nums.is_empty() { return vec![]; } // Initialize our result set with the first vector's elements let mut result_set: HashSet<i32> = nums[0].iter().cloned().collect(); for current_vec in &nums[1..] { let current_set: HashSet<i32> = current_vec.iter().cloned().collect(); // Update the result set to be the intersection of itself and the current set result_set = result_set.intersection(¤t_set) .copied() .collect(); // Early exit if no elements left to intersect if result_set.is_empty() { break; } } // Convert the final HashSet to a sorted Vec let mut final_result: Vec<i32> = result_set.into_iter().collect(); final_result.sort(); final_result } }
Key Fixes Explained
copied()for Reference-to-Value Conversion: Sincei32is aCopytype,copied()takes each&i32from the intersection iterator and copies it into an ownedi32, which matches theVec<i32>type we need. If you were working with non-Copy types, you'd useclone()instead.- Mutable Result Variable:
let mut intersect_resultallows us to update the variable in each iteration. - Early Exit Optimization: If the intersection becomes empty at any point, we can break out of the loop early to save computation time.
- Proper Return: We sort the final intersection and return it, instead of returning an empty vector.
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

