Easy Java Solution.


  • 0
    S

    public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
    int[] arr = new int[0];
    int len1 = nums1.length;
    int len2 = nums2.length;
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    if(len1 == 0 || len2 == 0) return arr;
    int i = 0, j = 0;
    while(i<len1 && j < len2){
    if(nums1[i]==nums2[j]){
    arr= addElement(arr, nums1[i]);
    i++;j++;
    }else if(nums1[i]!=nums2[j] && nums1[i]<=nums2[j]) i++;
    else if(nums1[i]!=nums2[j] && nums1[i]>nums2[j]) j++;
    }

        return arr;
    }
    
    static int[] addElement(int[] a, int e) {
    a  = Arrays.copyOf(a, a.length + 1);
    a[a.length - 1] = e;
    return a;
    

    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.