본문 바로가기

Algorithm/Brute Force

(C++) - LeetCode (easy) 349. Intersection of Two Arrays

반응형

https://leetcode.com/problems/intersection-of-two-arrays/description/

 

Intersection of Two Arrays - LeetCode

Can you solve this real interview question? Intersection of Two Arrays - Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.   Example 1: In

leetcode.com

간단 전수조사 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. nums1의 원소를 저장할 map nums1Map을 선언 후 원소들을 {nums1의 원소, 1}로 저장해 줍니다.2. 정답변수 ans를 선언해 줍니다.

📔 풀이과정

1. nums2에 대해 for loop를 수행합니다.

2. nums1Map에 nums2의 원소가 있다면 중복방지를 위해 value를 0으로 바꿔준 뒤 ans에 원소를 저장해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector <int> ans;
        map <int, int> nums1Map;
        
        for(auto n : nums1) {
            nums1Map[n] = 1;
        }

        for(auto n : nums2) {
            if(nums1Map[n]) {
                nums1Map[n] = 0;
                ans.push_back(n);
            }
        }

        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.