Java: HashMap Based Solution


  • 0
    E
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Map<Integer, Integer> interMap = new HashMap<>();
            for(int i = 0; i < nums1.length; i++) {
                    interMap.put(nums1[i], nums1[i]);
            }
            Set<Integer> interSet = new HashSet<>();
            for(int i = 0; i < nums2.length; i++) {
                    if(interMap.get(nums2[i]) != null) {
                        interSet.add(nums2[i]);
                    }
            }
            int[] result = new int[interSet.size()];
            int index = 0;
            for(Integer num : interSet) {
                result[index++] = num;
            }
            return result;
            
        }
    }
    

Log in to reply
 

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