350. Intersection of Two Arrays II

350. Intersection of Two Arrays II

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
       Arrays.sort(nums1);
       Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        ArrayList intersection = new ArrayList();
        while  (i < nums1.length && j < nums2.length){
            if(nums1[i] == nums2[j]){
                intersection.add(nums1[i]);
                i++;
                j++;
            }else if (nums1[i] < nums2[j]){
                i++;
            } else if (nums2[j] < nums1[i]){
                j++;
            }
        }
        int[] out = new int[intersection.size()];
        for(int k = 0; k < intersection.size(); k++)
            out[k] = intersection.get(k);
      return out;  
        }
    
    
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s