728x90
https://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개 주어지고, 교집합 구하기
→ 동일한 값이면 하나로 취급
ex) num1 = [4,9,5], num2 = [9,4,9,8,4] -> [9,4] or [4,9]
vector<int> intersection(vector<int> nums1, vector<int> nums2) {
vector<int> ans;
//remove duplicated values
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
nums1.erase(unique(nums1.begin(), nums1.end()),nums1.end());
nums2.erase(unique(nums2.begin(), nums2.end()),nums2.end());
for(int i=0; i<nums1.size(); i++){
for(int j=0; j<nums2.size(); j++){
if(nums1[i] == nums2[j]) ans.push_back(nums1[i]);
}
}
return ans;
}
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy/TwoPointer] Reverse String II (0) | 2022.09.20 |
---|---|
[LeetCode/easy/TwoPointer] Assign Cookies (0) | 2022.09.20 |
[LeetCode/easy/String] Is Subsequence (0) | 2022.09.20 |
[LeetCode/easy/String] First The Difference (1) | 2022.09.20 |
[LeetCode/easy/String] First Unique Character in a String (0) | 2022.09.20 |