본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 350] Intersection of Two Arrays II

by m2162003 2020. 12. 1.

Given two arrays, write a function to compute their intersection.

Example 1:

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

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

두 배열 사이의 교차지점을 리턴하는 문제

문제에서 교차지점이 존재한다고 가정하기 때문에 배열을 sort하면 쉽게 풀린다.

소트한 후 투포인터로 값이 일치할때마다 result배열에 푸쉬한다.

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        
        vector<int> result;
        int len1 = nums1.size();
        int len2 = nums2.size();
        
        if(len1 == 0 && len2 == 0) return result;
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        
        int i=0, j=0;
        while(i<len1 && j < len2){
            if(nums1[i] == nums2[j]){
                result.push_back(nums1[i]);
                i++;
                j++;
            }else if(nums1[i] < nums2[j]){
                i++;
            }else {
                j++;
            }
        }
        
        return result;
        
    }
};

'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글

[leetcode 242] Valid Anagram  (0) 2020.12.01
[leetcode 344] Reverse String  (0) 2020.12.01
[leetcode 191] Number of 1 Bits  (0) 2020.11.30
[leetcode 237] Delete Node in a Linked List  (0) 2020.11.27
[leetcode 202] Happy Number  (0) 2020.11.25

댓글