N

(Leet Code c++)Intersection of Two Arrays 본문

Leet Code 알고리즘

(Leet Code c++)Intersection of Two Arrays

naeunchan 2021. 8. 3. 19:36
728x90
반응형

349. 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:

Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Explanation: [4,9] is also accepted.

 

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

주어진 두 벡터 배열 중 공통 원소를 담아 리턴해야 한다.

0 ~ 1000의 원소를 가지기 때문에 bool형 벡터 check를 1001 크기만큼 선언한다.(false로 초기화)

 

for문을 통해 nums1의 원소를 check에서 true로 바꿔준다.

 

이제 nums2를 for문으로 각 원소를 방문한다.

nums2의 원소가 check에서 true 상태라면 공통 원소이므로 answer에 push.

이후 해당 원소의 check 상태를 false로 바꿔 중복이 없게 방지한다.

 

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> answer;
        vector<bool> check(1001, false);
        
        for(int i = 0; i < nums1.size(); i++){
            check[nums1[i]] = true;
        }
        
        for(int i = 0; i < nums2.size(); i++){
            if(check[nums2[i]]){
                answer.push_back(nums2[i]);
                check[nums2[i]] = false;
            }
        }
        
        return answer;
    }
};
728x90
반응형