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

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_result is immutable: You need to update it in each iteration, so it should be declared with mut.
  • Type mismatch from intersection(): The method returns references, not owned values. Since i32 implements the Copy trait, we can easily convert these references to owned values.
  • Unnecessary type conversions: Converting nums.len() to i32 is unnecessary—Rust prefers using usize for 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(&current_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: Since i32 is a Copy type, copied() takes each &i32 from the intersection iterator and copies it into an owned i32, which matches the Vec<i32> type we need. If you were working with non-Copy types, you'd use clone() instead.
  • Mutable Result Variable: let mut intersect_result allows 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:48:12