Search code examples
rustintersection

Problems trying to get intersection of a Vector


I am having a problem whilst trying to get the intersection of two Vectors.

impl Solution {
    pub fn intersection(nums: Vec<Vec<i32>>) -> Vec<i32> {
        // Intended strategy:
        // Store the first element into an intersect_result
        // Iterate over the remaining elements for each element:
        //       Determine the intersection of the current element and the intersect result
        //       set intersect result to this.
        // Sort the intersect result
        // Return the intersect result back to the caller.


        let len:i32 = nums.len() as i32;
        let intersect_result:Vec<i32> = nums[0].clone();
    
        for i in 1..len{
           println!("i is: {}", i);
           let temp_vec:Vec<i32> = nums[i as usize].clone();
           // find the intersection of the current element with the intersect result
           let unique_a:HashSet<i32> = temp_vec.into_iter().collect();
           let unique_b:HashSet<i32> = intersect_result.clone().into_iter().collect();
           intersect_result = unique_a.intersection(&unique_b).collect::<Vec<_>>();
        }

        vec![]
    }
}

The error message I get is:

= note: expected struct `Vec<i32>`
           found struct `Vec<&i32>`

This happens in the call unique_a.intersection().

Any thoughts guys?


Solution

  • You can add a map(|i| *i) in the iterator chain that causes the error:

    intersect_result = unique_a.intersection(&unique_b).map(|i| *i).collect::<Vec<_>>();
    

    When fixing this, the code also seems to work as intended. I think there are a few improvements possible (probably more, but these immediately tracked my attention):

    use hashbrown::HashSet;
    
    pub fn intersection(nums: Vec<Vec<i32>>) -> Vec<i32> {
        let mut intersect_result: Vec<i32> = nums[0].clone();
    
        for temp_vec in nums {
            let unique_a: HashSet<i32> = temp_vec.into_iter().collect();
            intersect_result = unique_a
                .intersection(&intersect_result.into_iter().collect())
                .map(|i| *i)
                .collect::<Vec<_>>();
        }
        intersect_result
    }
    
    fn main() {
        let a = vec![1, 2, 3];
        let b = vec![2, 3, 4];
        let c = vec![3, 4, 5];
        let v = vec![a, b, c];
        let res = intersection(v);
        println!("res: {:?}", res);
    }