상세 컨텐츠

본문 제목

2032. Two Out of Three

Developer/LEETCODE

by cepiloth 2021. 10. 10. 17:24

본문

728x90
반응형

https://leetcode.com/problems/two-out-of-three/

난이도 : easy

문제

3개의 배열에서 중복되는 원소를 출력 하라.

 

배열에서 같은 원소가 있을수 있어 정렬과 unique, erase 를 사용하여 중복이 없는 어레이를 만든다.

소스코드

class Solution {
public:
    
    // 배열에서 같은 원소가 나올 수 가 있어서 정렬을 통하여 중복된 원소를 제거하고
    // 중복이 없는 고유의 값만 갖고 있는 원소를  만든다.
    void erase(vector<int>& nums1)  {
        sort(nums1.begin(), nums1.end());
        nums1.erase(unique(nums1.begin(),nums1.end()),nums1.end());
    }
    
    // 데이터가 중복되는 원소가 없는지 확인하기 위한 디버그 함수
    void print(const vector<int> arr) {
        for(auto a:arr) {
            cout  << a << " ";
        }
        cout << endl;
    }
    vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) {
        
        erase(nums1);
        print(nums1);
        erase(nums2);
        print(nums2);
        erase(nums3);
        print(nums3);
        map<int, int> m;
        
        // 3개의 배열을 순회하면서 map 에 key 원소를 삽입하고 value 는 원소의 개수를 카운트 한다.
    
        for(auto a:nums1)  {
            m[a]++;
        }
        for(auto a:nums2)  {
            m[a]++;
        }
        for(auto a:nums3)  {
            m[a]++;
        }
        
        // 마지막으로 map 을 순회하면서 key 의 count 가 2 이상인 원소를 vector<int> 에 삽입한다.
        vector<int> arr;
        for(auto a:m) {
            if (a.second >= 2) {
                arr.push_back(a.first);
            }
        }
        
        return arr;
    }
};

 

728x90
반응형

'Developer > LEETCODE' 카테고리의 다른 글

Weekly Contest 277  (0) 2022.01.23
2033. Minimum Operations to Make a Uni-Value Grid  (0) 2021.10.10
442. Find All Duplicates in an Array  (0) 2021.10.07
463. Island Perimeter  (0) 2021.10.05
2028. Find Missing Observations  (0) 2021.10.03

관련글 더보기

댓글 영역