Java solution using Maps [O(N)]


  • 1
    U
    class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            HashMap <Integer, Integer> objMap = new HashMap<Integer, Integer>();
            ArrayList <Integer> objArray = new ArrayList <Integer>();
            
            for (int i : nums1) {
                if(objMap.get(i) == null) {
                    objMap.put(i, 1);
                } else {
                    objMap.put(i, objMap.get(i) + 1);
                }
            }
            
            for (int j : nums2) {
                if(objMap.get(j) != null && objMap.get(j) > 0) {
                    objArray.add(j);
                    objMap.put(j, objMap.get(j) - 1);
                }
            }
            return objArray.stream().mapToInt(Integer::intValue).toArray();
        }
    }
    

Log in to reply
 

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