My Accepted Java Solution with 7ms


  • 2
    G
    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            Map<Integer,Integer> hm = new HashMap<>();
            int val;
            for(int num : nums1){
                val = 0;
                if(hm.containsKey(num)){
                    val = hm.get(num);
                }
                hm.put(num,++val);
            }
            
            List<Integer> intersect = new ArrayList<Integer>();
            for(int num : nums2){
               if(hm.containsKey(num)){
                   val = hm.get(num);
                   if (val > 0){
                       intersect.add(num);
                       hm.put(num,--val);
                   }
               } 
            }
            
            int[] intersect_arr = new int[intersect.size()];
            for(int i=0;i<intersect.size();i++){
                intersect_arr[i] = intersect.get(i).intValue();
            }
            return intersect_arr;              
        }
    }

Log in to reply
 

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