java with hashmap


  • 0
    P
    class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if(nums1.length == 0)
        {
            return nums1;
        }
        if(nums2.length == 0)
        {
            return nums2;
        }
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        int[] temp;
        int[] shorter;
        int[] result = new int[Math.max(nums1.length,nums2.length)];
        if(nums1.length<nums2.length)
        {
            temp = nums2;
            shorter = nums1;
        }
        else
        {
            temp = nums1;
            shorter = nums2;
        }
        for(int i = 0;i<temp.length;i++)
        {
            if(!map.containsKey(temp[i]))
            {
                map.put(temp[i],1);
            }
            else
            {
                map.put(temp[i],map.get(temp[i])+1);
            }
        }
        int count = 0;
        for(int i = 0;i<shorter.length;i++)
        {
            if(map.containsKey(shorter[i])&&map.get(shorter[i])!=0)
            {
            	result[count++] = shorter[i];
                map.put(shorter[i],map.get(shorter[i])-1);
            }
        }
        int[] trueresult = new int[count];
        for(int i = 0;i<count;i++)
        {
        	trueresult[i] = result[i]; 
        }
        return trueresult;
    }
    }
    

Log in to reply
 

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