728x90
https://leetcode.com/problems/intersection-of-two-arrays-ii/
정수 배열 nums1, num2가 주어지고 교집합 배열을 반환해라.
결과의 각 요소는 두 배열에 표시된 횟수만큼 나타나야 하며, 원하는 순서로 결과를 반환할 수 있습니다.
Intersection of Two Arrays 문제에서는
예제 1) nums1 = [1,2,2,1], nums2 = [2,2] -> output: [2] 였는데 이번 문제는 output: [2,2]
각각의 배열 원소를 가리키는 pointer를 두고 비교하면서 ans에 넣기 -> 최대 1000이라서 괜찮음
vector<int> intersect(vector<int> nums1, vector<int> nums2) {
vector<int> ans;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int i=0, j=0;
while(nums1.size() > i && nums2.size() > j){
if(nums1[i] == nums2[j]){
ans.push_back(nums1[i++]);
j++;
}else if(nums1[i] > nums2[j]){
j++;
}else{
i++;
}
}
return ans;
}
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy/Simulation] Add Digits (0) | 2022.09.21 |
---|---|
[LeetCode/easy/BinarySearch] Valid Perfect Square (1) | 2022.09.21 |
[LeetCode/easy/BinarySearch] First Bad Version (0) | 2022.09.21 |
[LeetCode/easy/BinarySearch] Sort(x) (0) | 2022.09.20 |
[LeetCode/easy/TwoPointer] Reverse String II (0) | 2022.09.20 |