티스토리 뷰

leetcode.com/problems/intersection-of-two-arrays/

 

Intersection of Two Arrays - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

배열 2개 주고 중복되는 원소 있으면 그 원소를 배열에 담아서 반환 시키는 문제

2중 반복문으로 중복 원소를 배열에 쌓고 중복 제거

use std::collections::HashSet;

impl Solution {
    pub fn intersection(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
        let mut answer = Vec::new();
        for n1 in nums1.iter(){
            for n2 in nums2.iter(){
                if n1 == n2 { answer.push(*n1) };
            }
        }
        Solution::remove_duplicates(&mut answer);
        answer
    }

    fn remove_duplicates(input : &mut Vec<i32>){
        let set : HashSet<i32> = input.drain(..).collect();
        input.extend(set.into_iter());
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함