Java two simple solutions


  • 0
    M

    First solution is O (n * m)

    public class Solution {
        
        public int[] intersection(int[] nums1, int[] nums2) {
        
            Set<Integer> set = new HashSet<>();
            
            for (int i = 0; i < nums1.length; i++) {
                
                for (int j = 0; j < nums2.length; j++) {
                    
                    if (nums1[i] == nums2[j]) {
                        set.add(nums1[i]);
                    }
                    
                }
                
            }
            int[] result = set.stream().mapToInt(Number::intValue).toArray();
            return result;
        }
    }
    

    Second solution O (n + m)

    public class Solution {
        
        public int[] intersection(int[] nums1, int[] nums2) {
        
            Set<Integer> nums1Set = new HashSet<>();
            Set<Integer> resultSet = new HashSet<>();
            
            for (int i = 0; i < nums1.length; i++) {
                nums1Set.add(nums1[i]);
            }
            
            for (int j = 0; j < nums2.length; j++) {
                if (nums1Set.contains(nums2[j])) {
                    resultSet.add(nums2[j]);
                }
            }
    
            int[] result = resultSet.stream().mapToInt(Number::intValue).toArray();
            return result;
        }
    }
    

Log in to reply
 

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