Easy Java Solution


  • -1
    2
    public int[] intersect(int[] nums1, int[] nums2)
    {
    	HashSet<Integer> set = new HashSet<>();
    	int index1, index2;
    	 Arrays.sort(nums1);
    	 Arrays.sort(nums2);
    	for (index1 = 0, index2 = 0; index1 < nums1.length && index2 < nums2.length;)
    	{
    		if (nums1[index1] == nums2[index2])
    		{
    			set.add(index1);
    			index1++;
    			index2++;
    		} else if (nums1[index1] < nums2[index2])
    		{
    			index1++;
    		} else
    		{
    			index2++;
    		}
    
    	}
    	int[] result = new int[set.size()];
    	int i = 0;
    	for (Integer index : set)
    	{
    		result[i++] = nums1[index];
    	}
    	return result;
    }

  • 1
    P

    If you take a set, you won't get the intersecting numbers in the result as many times as they appear in the original arrays.


  • 1
    2

    I use set to record the index of number not the number.


  • 0
    C
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int ind1 = 0;
            int ind2 = 0;
            ArrayList<Integer> myList = new ArrayList<Integer>();
            while((ind1 < nums1.length) &&(ind2< nums2.length)){
                if(nums1[ind1]<nums2[ind2]){
                    ind1++;
                }else{
                    if(nums1[ind1]==nums2[ind2]){
                        myList.add(nums1[ind1]);
                        ind1++;
                    }
                    ind2++;
                }
            }
            int[] res = new int[myList.size()];
            for(int i = 0; i<res.length; i++){
                res[i] = (Integer)myList.get(i);
            }
            return res;
        }```

Log in to reply
 

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